diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 50b1bb94bf..c0e75d6b6a 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -34,6 +34,12 @@ 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. 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, * and one settles within its HTLC timeout, which LDK caps at 1008 blocks (about a week) and Spark's routes keep @@ -51,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) @@ -167,6 +177,27 @@ 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) { + var dropped = 0 + store.updateData { data -> + val unexpired = (data.sparkOwnInvoices + (paymentHash.lowercase() to expiresAt)).entries + .filter { it.value > now } + 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. */ + 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 @@ -454,6 +485,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 1f3fa591d9..835f80c5ce 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3023,6 +3023,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 81ffbfec7d..5b6ded3929 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -529,11 +529,39 @@ 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. 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 { 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) ?: 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. 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) + } + /** 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..e83a08c90c 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 @@ -393,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/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a19961687c..f71e337fc3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3868,7 +3868,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 @@ -3879,7 +3887,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/models/WatchBackupContractTest.kt b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt new file mode 100644 index 0000000000..52817bf0f9 --- /dev/null +++ b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt @@ -0,0 +1,87 @@ +package to.bitkit.models + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assume.assumeFalse +import org.junit.Assume.assumeTrue +import org.junit.Test +import to.bitkit.data.SettingsData +import to.bitkit.di.json +import to.bitkit.env.Env +import java.io.File +import kotlin.test.assertEquals + +/** + * The Wear OS app imports the phone's settings by reading the settings backup from VSS (docs/wear.md, Settings + * sync). `wear/src/test/resources/phone-backup-contract.json` holds what it relies on: the backup's key, six + * settings as this app encodes them, and where each network's backups live. The watch's `PhoneBackupContractTest` + * reads the same file. When a test here fails, the watch stops reading the phone's settings: change the watch's + * reader and the file together with the phone. + */ +class WatchBackupContractTest { + private val contract: JsonObject by lazy { + val file = generateSequence(File("").absoluteFile) { it.parentFile } + .map { File(it, "wear/src/test/resources/phone-backup-contract.json") } + .first { it.isFile } + Json.parseToJsonElement(file.readText()).jsonObject + } + + @Test + fun `the settings backup is stored under the key the watch reads`() { + assertEquals(contract.getValue("settingsKey").jsonPrimitive.content, BackupCategory.SETTINGS.name) + } + + @Test + fun `the settings backup holds the six settings the watch reads, in the form it reads`() { + val expected = contract.getValue("settingsBackup").jsonObject + val expectedSettings = expected.getValue("settings").jsonObject + val settings = SettingsData( + primaryDisplay = PrimaryDisplay.FIAT, + displayUnit = BitcoinDisplayUnit.CLASSIC, + selectedCurrency = "EUR", + isQuickPayEnabled = true, + quickPayAmount = 10, + quickPayDailyLimitMultiplier = 3, + ) + + val written = written(settings) + + assertEquals(expected.getValue("version"), written.getValue("version")) + val writtenSettings = written.getValue("settings").jsonObject + assertEquals(expectedSettings, JsonObject(writtenSettings.filterKeys { it in expectedSettings.keys })) + } + + @Test + fun `default settings are written too, so the watch always finds all six`() { + val keys = contract.getValue("settingsBackup").jsonObject.getValue("settings").jsonObject.keys + + val written = written(SettingsData()).getValue("settings").jsonObject + + assertEquals(keys, written.keys.intersect(keys)) + } + + @Test + fun `this network's backups live where the watch looks for them`() { + // An E2E build may point the backups at a local server, which the watch never reads. + assumeFalse(Env.isE2eTest) + val network = contract.getValue("networks").jsonObject[Env.network.name]?.jsonObject + // The watch runs on fewer networks than the phone. + assumeTrue(network != null) + + val expected = checkNotNull(network).mapValues { it.value.jsonPrimitive.content } + val actual = mapOf( + "storeIdPrefix" to Env.vssStoreIdPrefix, + "vssServerUrl" to Env.vssServerUrl, + "lnurlAuthServerUrl" to Env.lnurlAuthServerUrl, + ) + assertEquals(expected, actual) + } + + /** The settings backup of [settings] as this app uploads it. */ + private fun written(settings: SettingsData): JsonObject { + val backup = SettingsBackupV1(createdAt = 0, settings = settings) + return json.parseToJsonElement(json.encodeToString(SettingsBackupV1.serializer(), backup)).jsonObject + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0304a6a5a0..cf6f34f8d2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -187,6 +187,70 @@ 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 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) + 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 b0f0c8bab3..c79753445e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -431,6 +431,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) @@ -12001,6 +12002,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" 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. diff --git a/docs/screens-map.md b/docs/screens-map.md index c957fd56f3..3f09d7f30a 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -375,7 +375,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 @@ -387,6 +387,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 | @@ -399,6 +406,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 | @@ -414,6 +428,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/docs/wear.md b/docs/wear.md index 222af2f6ab..c8b06098eb 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -3,7 +3,8 @@ > Do not publish the watch app yet: two live Spark instances on one seed are unsafe until #2152 is resolved. The `:wear` module is a standalone Wear OS app (issue #2105, epic #2077). It runs its own Spark wallet through the -Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only needed to set it up (from PR 3). +Breez SDK, with no LDK node, no Room database and no Firebase. It needs no phone nearby: it adopts the phone's +settings by reading the phone's backup (see Settings sync). ## Module overview @@ -25,8 +26,8 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only 2 100 000 000. - **NFC required.** The manifest requires `android.hardware.nfc` (`android:required="true"`), so Play offers the app only to watches with NFC. It is a store filter only: `pm install` ignores it, so `just wear-install` still - installs on the NFC-less emulators. Host card emulation (`android.hardware.nfc.hce`) is not required yet; PR 4 - decides that with the tap-to-pay work. + installs on the NFC-less emulators. Host card emulation (`android.hardware.nfc.hce`) is declared but not required + (`android:required="false"`), as on the phone: see NFC › Manifest. - **SDK levels.** `minSdk` 34 (Wear OS 5), `targetSdk` 36, `compileSdk` 37. Wear OS 6+ keeps apps targeting 36 always-on, so the home screen hides the balance and stops its animations in ambient mode. - **ABIs.** Debug builds split `arm64-v8a`, `armeabi-v7a` and `x86_64` (emulator); release builds ship the two ARM @@ -46,35 +47,53 @@ 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, the NFC + tag 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. Debug builds turn on `StrictMode` (disk reads, disk writes and network on the main thread, logged to logcat under - `StrictMode`), so a regression shows while the journeys run. + `StrictMode`), so a regression shows while the journeys run. The receive tag's route (`CardEmulationTagRoute`: + registering the application id and the preferred service) does run on the main thread, each time the receive QR + resumes or its invoice changes: these are short calls to the NFC service that need the resumed activity, as on + the phone, and no disk or network read. - **Backups.** `allowBackup` is off and both backup rule files exclude every domain, so neither the seed nor the Spark state leaves the watch. - **Copied code.** The currency formatting, the colour tokens and text styles, the balance swap animations and - `clickableAlpha` are copies of the phone's, each naming its source file. Keep them in sync until a shared module - replaces them. + `clickableAlpha` are copies of the phone's, each naming its source file. So is the NFC code in the `nfc` package + (see NFC). Keep them in sync until a shared module replaces them. ### Packages - `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), `SelfSendGuard` and + `PhoneBackupReader`, the read-only way to the phone's backups on VSS. - `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), `CurrencyRepo` (Blocktank rates and the unit shown first), `SettingsSyncRepo` (the import of the + phone's settings), `QuickPayRepo` (whether a send may skip the hold to pay) and `SendOutcomeRepo` (how a + payment reported as pending or unknown ended; see Pending payments). +- `data`: `SettingsStore` (display settings, what was imported from the phone and the wipe's notes, with + `WipeMarker` for the note itself), `OwnInvoiceStore` (the invoices this wallet created, in the settings file), + `QuickPaySpendStore` (the day's QuickPay spend, 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). + `NfcMonitor` (the NFC adapter's state and whether the watch has host card emulation), `ForegroundMonitor` (the process lifecycle: whether the app is on + screen), `SendMonitor` (whether a send is under way anywhere in the process), `AmbientMonitor` (whether the activity is in ambient mode) and `ElapsedClock` (the time since boot, + sleep included, for ages). +- `nfc`: the NDEF codec, the Type 4 tag emulator with its service (`NdefTagService`), `NfcTagOffer` (the tag's + offer, from start to stop), the rewrite of a request read from a tag, `NfcTapFilter` and `NfcRepeatGuard` (one + tap, one request; `ui/LaunchGate` asks the filter and `SendMonitor` for the whole process). See NFC below. +- `tile`: `BalanceTileService` (the balance tile), `TileState` (what it shows) and `TileUpdates` (asks the system + to draw it again). See Tile below. +- `models`: among others `PhoneSettingsParser`, the reader of the phone's settings backup. - `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, a tapped NFC tag 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. @@ -86,9 +105,9 @@ 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). + There is no Send page or button: a send starts from outside the app (a tapped NFC tag 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. @@ -116,7 +135,7 @@ On-screen copy stays short: a title or one line of at most about six words per s the hint appears, and the icon is still until then. - NFC off: the same icon, still, dimmed to white-32 and slashed like the phone's `ic_eye_slash` (`ic_broadcast_off`), as `NfcHintDisabled` ("NFC off"). A tap opens the NFC settings, or the settings home on - a watch without an NFC settings screen. + a watch without an NFC settings screen; a screen reader names that action "Open NFC settings". - No NFC adapter: hidden. Only the emulators get here; a store install always has NFC (see NFC required). The emulators have no NFC, so the two visible states are checked on a physical watch, or in the `NfcHint` and @@ -127,7 +146,10 @@ On-screen copy stays short: a title or one line of at most about six words per s start ends in the error with its retry (`WatchHomeError`, `WatchHomeRetry`). Once a sync of this session has reached Spark, losing the network, or a later sync that does not reach Spark, keeps the last balance with a small no-network icon (`WatchHomeOffline`, no text). `NetworkMonitor` counts a network as online only once the system - validated that it reaches the internet. When it reports the network back and the app is on screen, the wallet + validated that it reaches the internet. A sync that reaches Spark while `NetworkMonitor` reports no network, as + over the local stack's `adb reverse` ports, which airplane mode leaves up, ends offline too, with its balance: + the wallet is ready only with a network, whatever it was when the network went (ready, paused, locked or + starting). When it reports the network back and the app is on screen, the wallet syncs again under the loading ring. A wallet that stays offline although the watch has a network tries again by itself while the app is on screen: after 5 s, then 15 s, then every 60 s, starting over once a sync succeeds. A tap on the offline icon tries at once. The error does not retry by itself; the wearer taps retry. @@ -143,16 +165,137 @@ On-screen copy stays short: a title or one line of at most about six words per s background: not the network coming back, not an unlock, not a retry. A start asked for there is put off, and a start that the app left while it ran is disconnected and put off too. Returning to the app connects and syncs again under the loading ring, over the last balance. Returning within the 10 s only cancels the wait; a - disconnect that already began always finishes, and the wallet then connects again. When Spark cannot be + disconnect that already began always finishes, and the wallet then connects again. The wallet stops being ready + before that disconnect starts (it reads as connecting until it is paused), so an app that returns while Spark is + still disconnecting, as for a tapped tag, prices and sends nothing on it and shows the loading ring. When Spark cannot be 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. -- **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. + whatever the wallet's status says, as does a start that finds the watch locked. One thing puts the pause off: a + payment sent from this watch that is still settling keeps Spark connected for up to 3 minutes after the send, and + the 10 s count from when it settled or that time ran out (see Pending payments). A lock never waits for it. + Ambient mode is not the + background: the app stays on screen and connected. `AmbientMonitor` carries it from the activity to what runs + outside the screens: in ambient mode the phone's settings are not imported and no send goes out under QuickPay. +- **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. 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 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 + 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 + 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. While the QR shows, the watch also offers the invoice as an NFC tag, with the NFC hint below the + QR (`WatchReceiveNfc`, or `WatchReceiveNfcOff` with NFC off): see NFC › Receive by tap. +- **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, + in the unit (Modern or Classic) imported from the phone, 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, its + unit 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 tapped NFC tag with a payment link opens the same flow as the link + itself (see NFC › Pay by tap). 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 `singleTask`, as on the phone, so a + link reaches the one running activity in Bitkit's own task through `onNewIntent`, also when its sender starts it + without `FLAG_ACTIVITY_NEW_TASK`); without a wallet, during the restore, or while a send is under way anywhere in + the process (`LaunchGate`, `SendMonitor`), 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 + least 1 % of the amount, and one line naming the payee when the input names one. The fee line + (`WatchSendFee`) may wrap to 2 lines and is never cut: under Classic a long translation, as the Italian + "Commissione ₿ 0.00001234", does not fit 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. 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 once the send is priced, for a send the wearer is there for: under + the phone's QuickPay the review and the hold are skipped and the send goes out at once (see QuickPay). + - 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 + 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 a sent result are replaced by a dimmed bolt (`WatchSendHidden`), so + the always-on screen shows no amount; the hold starts over when the watch wakes. A pending or unknown result + stays readable there, its icon and word without the amount (`SendResultTest`). + - Sending: the loading ring. "Waiting for network" (`WatchSendWaiting`) shows only for a wait that is the + network's, from 3 s into the send: while the sync that comes before the send is still trying to reach Spark, + and while the wallet is offline (`WalletStatus.Offline`), as when the network drops after that sync. With the + wallet online and the payment handed to Spark the ring shows alone, also while a hold invoice settles. 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 within 10 s, as on the phone, or one that was already under way, from the watch or the phone, + shows a clock, "Pending" and the amount (`WatchSendPending`, `WatchSendResultAmount`) with a soft click; an + outcome Spark could not report shows "Check activity", never a failure; both stay for 5 s. An outcome that + arrives while they show replaces them at once: the check, "Sent" and the confirm haptic, closing 2 s later, + or the cross, "Payment failed", the reject haptic and OK. Only a result the wearer can read is switched: in + ambient mode, with the app off screen, with the watch locked or with the flow's screen gone, the outcome is + left to the outcome overlay, as a later one is (see Pending payments). The result and failure line is one + element that is a polite live region, and the switch changes its text, so it is designed to be said by a screen + reader; `SendResultTest` checks that the line stays the same element, and whether TalkBack on a watch says it is + a manual test, not tried yet. A line that only appears with its screen is not announced by this. 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"; 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 + clock for pending, a cross for failed), the amount with its sign and how long ago (`WatchActivityItem-0` onwards). + An amount too long for one line, as with eight decimals on a small screen, takes a second line. + 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 + 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, Phone settings and Remove wallet. The watch has no settings of + its own to edit: the units, the currency and QuickPay come from the phone (see Settings sync). The Phone settings + row (`WatchSettingsSync`) shows how long ago they were last imported (`WatchSettingsSyncTime`, absent until a first + import, or after the phone's backup was found missing or unreadable; it moves on every minute while the page is + open), and a tap imports them now under the loading ring. An import from the tap that fails shows one line under + the row (`WatchSettingsSyncFailed`). Tapping the balance still swaps which unit shows first, and the choice is kept across restarts until the + phone's own setting changes. 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, importing the phone's settings from the Settings page, 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 @@ -162,6 +305,530 @@ 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, 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: another request is + 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 10 s for the payment to settle (`PaymentsRepo.SETTLE_TIMEOUT`, the phone's time) and reports it as pending + after that; the payment goes on settling (see Pending payments). 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, and no note stays. A hold that finds + the wallet not ready like this does not end on an error: the flow returns to the review with the hold off under + the loading ring, the wallet is started again, and the hold comes back when it is ready (or the flow ends on + "Can't pay offline" when it is offline). "Wallet not ready" (`WatchSendError`) is left for a request that cannot + be read or priced. The send screen keeps the screen on, so the app stays on screen and connected while it waits. +- **Pending payments.** A payment can stay pending for long: a hold invoice settles when its receiver decides, + after seconds or days, and a route can be slow. Spark takes the amount and the fee out of the balance while the + payment is pending and puts them back when it fails. + - Followed after the result. A payment the watch reported as pending or unknown is remembered by its id in + `UncertainSendStore` (the settings file, so the wipe clears it; the newest 20, each for 30 days), with what + QuickPay counted for it. `SendOutcomeRepo` learns how it ended when Spark shows it completed or failed: by + the SDK's payment event while the app is open, or by Spark's list, which is compared after every sync and + whenever the wallet becomes ready. The list is what covers a reopen: the SDK's first sync after a reconnect + updates it without an event. With the outcome the wallet syncs once more and loads its balance + (`WalletRepo.syncBalance`): Spark's stored balance gives a failed payment's amount back only with its next + sync, after the event. The outcome is written beside the payment's id and stays there until the wearer + was shown it; only then is the payment forgotten. So an outcome found while the app was off screen, in + ambient mode or behind another screen is still told when Android stops the process first: the next run reads + it from the file, with no wallet connected. Its QuickPay count is taken out when the outcome is found, once. + A wallet that is being wiped or is gone has nothing remembered and nothing told. Only payments this watch + sent or reported are followed. One exception: a send that timed out before it reached Spark is followed + under its idempotency key, which the phone derives too for the same invoice, so when the phone then pays + that invoice the watch tells it as sent. That is true of the invoice the wearer tried to pay. + - A retry tells once. A send that goes out again under the id of a watched payment, as a retry of one whose + outcome was unknown, and ends sent or failed within its own 10 s shows that on its own result. The watched + payment is then forgotten untold, and QuickPay keeps one count for the one payment: the earlier attempt's, + with the retry's taken out, or none when it failed. + - Told once. The outcome shows for 2 s, with a haptic: a check in Brand orange for sent (`WatchOutcomeSent`) + or a cross for failed (`WatchOutcomeFailed`), and the amount. It is an overlay in `MainActivity` + (`SendOutcomeOverlay`), not a screen and not a button: touches and Back do nothing until it is gone (turning + the crown only scrolls the list beneath, and pressing it leaves the app as always). It shows only with the app + on screen, out of ambient mode and with the watch unlocked (the lock screen covers the app without stopping + it): until then it waits, and one that was cut short shows again in full. Only an + outcome that showed for its 2 s is forgotten. Several show one after the other. The pending result itself + takes the outcome in place of the overlay while it is on screen. There is no system notification and nothing + runs in the background, so an outcome that arrives while the app is closed is told at the next open. + - Never over a payment. The overlay does not cover a screen where it could be taken for something else + (`SendMonitor.isOutcomeHeld`): a send flow with its amount entry, review and hold, send or result, and the + receive QR with its paid check, which a payer may be scanning. It waits until that screen is left. A send + flow in turn waits at its start, under the loading ring and before it reads its request, until the wearer + was shown every outcome known by then (`SendOutcomeRepo.awaitTold`, which compares Spark's list first), and + the overlay may show over that ring. So the end of an earlier payment always comes before the next one's + review or result, also under QuickPay, which pays only after it: a cross for a payment known to have failed + by then does not follow the check of the retry that paid. A wallet that stopped being ready during that wait + is waited for again before the request is read. An outcome that arrives once the flow is past its start + waits for the flow to close, so an earlier payment that ends in those seconds is told after the new result. + - Screen readers. The overlay is one element whose description is the status and the amount, such as "Sent, + ₿ 1 000" (`send__outcome_description`), and a pane with that title, which is designed to have TalkBack say + it when it appears (a live region is announced only on an element that was already there); the haptic alone + would tell a blind wearer nothing. While it shows, the screen beneath is taken out of the accessibility + tree, so its buttons cannot be reached or run unseen. `SendOutcomeOverlayTest` checks the description and + the pane title; that TalkBack on a watch says it, and says it once, is a manual test, not tried yet. + - Connected while it settles. Spark stays connected for a payment it took from this watch until the payment + settles, for 3 minutes after the send at most (`SendOutcomeRepo.SETTLE_HOLD`), also when the wearer leaves + the app; the SDK itself checks a Lightning payment for about that long. After that the usual 10 s pause + applies. It is held only for a payment sent from this watch in this run of the app, never for one the list + merely shows pending. A lock of the watch still disconnects at once, for the wallet's safety, and the outcome + is then found at the next unlock. Android may also stop the app's process in the background before the hold + ends; the next open finds the outcome all the same, from Spark's list when the payment ended after the + process did, and from the settings file when it ended before. + - Asked before the review. Pricing reads Spark's list as it is on the watch for the invoice's payment hash: an + invoice this wallet is paying ends on "Pending" with that payment's amount, and one it paid on "Already + paid", with no review, no hold and no QuickPay count. The list is not synced for it, so a payment the phone + started moments ago is still caught where it always was, by the sync before the send. + - QuickPay. A QuickPay payment that was reported as pending or unknown stays in the day's count, and is taken + out when Spark later shows it failed (see QuickPay). + - **Known gap:** a payment whose outcome is unknown and that never reached Spark is never listed, so nothing is + told about it; it is forgotten after 30 days, and its QuickPay count stays. +- **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 + 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 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 + (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 + (a later PR). 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 review and + the hold to pay. See QuickPay below. + +### QuickPay + +The watch has no QuickPay switch. It follows the phone's: QuickPay on or off, the amount per payment in US dollars +and the daily limit, which is that amount times a multiplier, all read from the phone's settings backup (see +Settings sync). The decision follows the rules of the phone's own `QuickPayRepo`, with two differences that the +watch needs, listed below. A send skips the review and the hold, and goes from pricing straight to sending and the +usual result screens, only when every one of these holds: + +- The wallet is connected and synced (`WalletStatus.Ready`), and no wipe runs. +- The send was priced by `PaymentsRepo.prepare`, so the self-send guard, the expiry, the balance and every other + check before the hold passed. A request those checks refuse never reaches QuickPay. +- The request fixes the amount, as on the phone: a BOLT11 invoice that carries its amount, also the one inside a + `bitcoin:` URI, or an LNURL-pay link or a Lightning address whose smallest and largest amount are the same. The + link's scheme and case change nothing, since the request is what `PaymentsRepo.decoderInput` leaves of it: an + uppercase `BITCOIN:` URI with an amount counts like a lowercase one, and an `lnurlp://` link like any LNURL. An + amount the wearer typed always gets the review and the hold, and so does a Spark address, which names no amount. +- QuickPay is on in the settings last imported from the phone. They count however long ago the import was, as the + phone's own settings do on the phone. +- The amount, without the fee, is no more than the phone's QuickPay amount. As on the phone, the QuickPay amount is + turned into sats at the dollar rate, rounded half up, and the invoice's sats are compared with that. The + invoice's unrounded dollar value is compared with the QuickPay amount too, which is the phone's check when it + pays: where the sats rounded up, the last sat is worth a fraction of a cent too much and is reviewed. +- Today's QuickPay payments from this watch, with this one, stay within the daily limit. The payment counts as its + dollar value in cents, rounded half up and at least one cent, as on the phone. +- The wearer is there: the first of the two differences below. + +The rate is the last one the watch fetched, whatever its age: the phone has no age limit on its rates either. The +phone keeps its rates across restarts and the watch does not, so when QuickPay is on and no dollar rate is in yet, +as for a link that started the app, the decision first fetches the rates, for 5 s at most under the loading ring +(`QuickPayRepo.awaitRate`). Without a rate the answer is no. + +The two differences from the phone: + +- **The wearer has to be there** (`SendViewModel`, `MainActivity`). The phone turns QuickPay off for a scan it put + off across its lock, since whoever unlocks did not confirm it. The watch has the same case in more shapes, so: + - The send is priced within 30 s of its link arriving (`QUICKPAY_WINDOW`), and from the link to the decision the + app stayed on screen and out of ambient mode, the watch was never locked, and the wallet was not paused again + once it ran. A link that waited longer for the wallet, as one opened on a wallet that takes minutes to + connect, always ends on the review and the hold. The 30 s cover a wallet that connects and syncs as + the link opens the app. The wait never runs across `WalletStatus.Offline`: an offline wallet ends the flow on + the offline refusal (see Send), the request is dropped, and QuickPay is not asked for it, then or when the + network returns. + - The flow's screen is still shown (`SendViewModel.onShownChange`, from the screen's `LifecycleStartEffect`). A + flow that a new link, tap or tile request took off the back stack is stopped at once, while its view model + lives until the transition ends, and it must not pay unseen in that moment. + - It is the link's first send flow. Android keeps the Send route and its link in the saved back stack, and + builds the flow again when it restores the app, as after the process was killed in the background. The first + flow leaves a mark in that saved state (`SendViewModel.KEY_STARTED`), and a flow that finds it never asks + QuickPay, whenever it is built. + - A link that Android sends again from Recents is no request at all. A task that a link created keeps that + link as its intent, and opening the task from Recents starts the app with it again + (`FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY`), minutes or hours after the wearer saw it. `MainActivity` takes such a + launch as a plain one (`isReplayedLaunch`): the app opens on Home and nothing is priced or paid. The check is + made where a task is started, `onCreate`, and again in `onNewIntent`, where a link reaches the running app. +- **QuickPay is off until the phone's settings were imported.** The phone has its settings at hand; the watch has + none of its own. So QuickPay is off before the first import, and it is turned off by an import that finds no + backup, a backup that cannot be decrypted or read, one with a newer layout, or QuickPay values outside what the + phone's sliders offer (1 to 50 dollars, 1× to 50×). An import that fails, as without a network, changes nothing. + +Anything that cannot be read answers no, and the wearer holds to pay as without QuickPay: no rate, a settings file +or a count that cannot be read. + +- **Daily limit.** `QuickPaySpendStore` keeps one day and its spend in cents in the settings file, which the wipe + clears. A payment is counted when QuickPay lets it out, before it is sent. As on the phone, it is taken out + again when it did not go out, as when the wearer turned out to have looked away meanwhile, and when it failed + (`PaymentsRepo.send`), and when the send flow was closed while QuickPay was decided. It stays counted when it + was paid, when it is still pending, when its outcome is unknown and when the send ended in an error the watch + does not know. As on the phone, a payment reported as pending or unknown that fails later is taken out then: + its count is remembered with the payment (see Pending payments) and released when Spark shows it failed, also + when that is found at the next open. A payment the app was closed during, before any result, stays counted. The count can only run ahead + of what was paid, never behind. The day is the watch's local date; a date earlier than the one last counted + starts no new count, so setting the watch's clock back frees nothing. +- **Known gap: a change on the phone takes an import to arrive.** QuickPay turned off or lowered on the phone + applies on the watch from the first import after the phone uploaded its settings. A watch that cannot read the + backup, as without a network, and a phone that could not upload it, leave the old settings in force. The Phone + settings row shows when they were last imported. +- **Known gap: two counts.** The phone keeps its own count of the day's QuickPay payments and the watch cannot read + it, so the phone and the watch each allow the daily limit: together up to twice the limit a day. Pairing (a later PR) + is where the two can share one count. +- **Known limit: a link sent from the phone.** Being there is measured as the watch unlocked, the app on screen + and out of ambient mode. It is not measured as a look or a touch: the watch has no sensor it could ask. An app on + the paired phone can open a `lightning:` link on the watch (`RemoteActivityHelper`) while the wearer looks at the + phone. A tapped NFC tag is measured the same way: the tap itself is the wearer's act, and Android reads a tag + only with the screen on and the watch unlocked. With the watch on the wrist and unlocked, and the screen lit by the launch, that send counts as attended + and goes out under QuickPay with no touch on the watch, as a link from another app on the watch does. It is + bounded by the phone's QuickPay amount per payment and by the daily limit, and by the two counts above. Whether + a remote launch lights the screen was not tried on a device. Nothing in V1 tells such a launch from a tap on + the watch; turning QuickPay off on the phone is the wearer's way to rule it out. +- **Known gap: the phone's payment PIN.** The phone can ask for its PIN before a QuickPay limit is raised; the + watch has no PIN and adopts whatever the phone saved. + +## NFC + +The watch pays by a tap on a payment tag and is paid by a tap on its receive QR. Both follow the phone's NFC code +([nearby-payments.md](nearby-payments.md)), copied into `to.bitkit.wear.nfc` with a note naming each source file +rather than shared through a module. Bluetooth ("nearby") is not on the watch. + +| Watch (`wear/src/main/java/to/bitkit/wear/…`) | Phone (`app/src/main/java/to/bitkit/…`) | | +| --- | --- | --- | +| `nfc/NdefCodec.kt` | `nfc/NdefCodec.kt` | copy | +| `nfc/Type4TagEmulator.kt` | `nfc/Type4TagEmulator.kt` | copy | +| `nfc/NfcTagEmitter.kt` | `nfc/NfcTagEmitter.kt` | copy, with `revoke` added (see Receive by tap › Stopping) | +| `nfc/NfcPaymentUri.kt` | `nfc/NfcPaymentUri.kt` | copy | +| `nfc/NdefTagService.kt` | `androidServices/NdefTagService.kt` | the same service | +| `nfc/NfcRepeatGuard.kt` | `nfc/NfcRepeatGuard.kt` | copy, without the hand-over to a scanner screen | +| `nfc/NfcTagOffer.kt`, `nfc/CardEmulationTagRoute.kt`, `ui/components/NfcTagEffect.kt` | `NfcEmitterEffect` in `ui/shared/effects/NfcEffects.kt` | the same steps, split so the offer is tested without a screen | +| `nfc/NfcTapFilter.kt` | the repeat window of `nfc/NfcReadDispatcher.kt` | adapted, see One tap, one request | +| `res/xml/ndef_tag_service.xml` | `res/xml/ndef_tag_service.xml` | the same | + +The copied unit tests (`NdefCodecTest`, `Type4TagEmulatorTest`, `NfcTagEmitterTest`, `NfcPaymentUriTest`, with +`PosNfcFixtures`) run in the watch module too. + +### Receive by tap + +While the receive QR shows an invoice, the watch is an NFC Forum Type 4 tag that carries it, exactly as the phone's +Receive is, so the phone's Send by NFC and any wallet or terminal that reads Bitkit's tag pays it. + +- **The tag.** The NDEF tag application `D2760000850101`, served by `NdefTagService` (a `HostApduService` that only + the NFC stack may bind, `BIND_NFC_SERVICE`) through `Type4TagEmulator`: capability container `E103`, NDEF file + `E104`, read-only. The message is one well-known URI record (`U`) without an abbreviation prefix, holding + `lightning:` and the invoice in lowercase (`nfcPaymentUri`), the same bytes the phone writes for the same + invoice. `ndef_tag_service.xml` declares no application id and asks for an unlocked device + (`requireDeviceUnlock`), as on the phone: the id is registered at runtime while the tag is offered, and the + service is made the preferred one meanwhile, so no other app with the same id answers in its place. Closing the + route unsets the preference and removes the id, each by itself, so a failure of the first does not skip the + second. Android keeps a runtime registration when the app is killed while it offers the tag: the id then stays + routed to `NdefTagService` until the app runs again, and `NfcMonitor` removes it at its start, before it reports + host card emulation and so before any screen can offer a tag. Meanwhile the service holds no request and reports + the tag application as not found, so no invoice is served, but the watch may still take the id from another + tag app. +- **When it is offered.** Only while all of these hold, and it stops at the first that ends: + - the receive QR screen is the screen in front and the app is resumed (`NfcTagEffect` follows the screen's + lifecycle, so leaving the screen, the app or the activity stops it); + - the QR itself shows: not in ambient mode, not while it rests after 2 min, not once paid (`receiveTagUri`); + - the wallet is connected and synced (`WalletStatus.Ready`); + - the invoice is the one on screen and has not expired by the watch's clock (`ReceiveViewModel` keeps + `ReceiveUiState.nfcUri` only meanwhile). A replaced invoice's tag ends before the new QR shows. An invoice that + the QR still shows past its expiry, as when its replacement keeps failing or the watch's clock runs ahead, is + not offered. A paid invoice is taken off the tag before the check shows; + - Spark's list shows no payment of the invoice after the wallet was away: when the wallet is ready again, the + request returns only once `PaymentsRepo.findPaid` read the list. A payment it finds turns the QR into the + check; a list that cannot be read keeps the tag away until the wallet is ready anew; + - NFC is on and the watch has host card emulation; + - the repeat guard does not hold reader mode (`NfcRepeatGuard.isHeld`). After any tapped tag it holds reader + mode until the tag left, at least 3 s without one, which pauses card emulation, so the tag is taken back and + the hint hidden meanwhile and both return when the hold ends. +- **The wall clock.** The view model's timers count the time the watch is awake and stand still while it sleeps, + so the expiry is also read from the wall clock, `nowSecs() < expiresAtSecs`: whenever `nfcUri` is published, + each time `NfcTagEffect` starts the offer (`isTagCurrent`, also on every resume), and when the screen shows + again after a resume, ambient mode or a tap on the resting QR (`onShow`). An invoice the watch slept past loses + its request at once and is replaced: it leaves the screen for the loading ring when it has expired, and stays + until its replacement exists when it is only within a minute of its expiry. One that is not due yet has its + replacement and its tag's end set again to what the wall clock leaves of them (`awaitWallClock`), so a watch + that woke and stays awake replaces it on time. +- **Stopping.** `NfcTagOffer.stop` first clears the request in `NfcTagEmitter`, then takes the application id + away. With no request the emulator reports the tag application as not found, also to a reader in the middle of a + tap, so nothing is served from the moment the offer stops, whatever the NFC stack still routes. A process that + died holds no request at all. At the moment of a payment the view model takes whatever request `NfcTagEmitter` + holds out of it itself (`revoke`), a frame before the screen stops the offer, so a paid invoice is not readable + in between. Nor does a resume in that frame start it again: `isTagCurrent` also asks that the invoice on screen + still has a request. +- **Failing closed.** A tag that cannot be registered, or made the preferred service, is not offered and the hint + stays hidden. An invoice Spark could not remember as the wallet's own is never shown, so never offered either. +- **The hint.** Below the QR, centred in the strip between the QR's square, quiet zone included, and the bottom of + the screen, so it never covers the quiet zone: the Balance page's `NfcHint` at 20dp. While the tag is offered it + is the animated broadcast icon (`WatchReceiveNfc`, "Tap to receive" to accessibility services). With NFC off it + is the dimmed, slashed, still icon (`WatchReceiveNfcOff`, "NFC off"), and a tap opens the NFC settings ("Open NFC + settings" to accessibility services). Its touch area is 48dp wide and ends at the screen's edge below the icon; + above it reaches 14dp past the icon, into the QR's square by about its quiet zone on a 192dp screen, where a + touch does nothing else. It is hidden without NFC hardware or host card emulation, in ambient mode, while the QR + rests, while the repeat guard holds reader mode, and whenever the tag is not offered. No text shows. +- **Paid.** The payer's wallet pays the invoice over Lightning; the watch learns it as for a scanned QR, and the QR + turns into the check. + +### Pay by tap + +A tap on a tag whose first record is a payment link opens the send flow, also while Bitkit is not in front. + +- **Dispatch: the manifest, as on the phone.** `MainActivity` has an `NDEF_DISCOVERED` intent filter for the + schemes the watch pays: `bitcoin`, `lightning`, `lnurl`, `lnurlp` and `spark`. The filter also lists `BITCOIN` + and `LIGHTNING`, which no tag reaches: Android lowercases a record's scheme before it matches, so they only + match an intent another app or `adb` sends. Android's tag dispatch starts the activity for such a tag whatever + app is in front, with the screen on and the watch unlocked. It does so from an activity of its own and without + `FLAG_ACTIVITY_NEW_TASK` (AOSP's `NfcRootActivity`), so a `singleTop` activity would be created anew for every + tap, next to or in place of the running one. `MainActivity` is therefore `singleTask`, as on the phone: the tap + reaches the one running activity in `onNewIntent`. This is read from AOSP and from the phone's manifest and was + not tried on a watch; what must hold either way does not depend on it (see One tap, one request). Foreground + dispatch and reader mode were considered and left out. The phone turns reader mode on only on its scanner + screens, and the watch has none. Reader mode switches the watch's own card emulation off while it is on, so the + receive QR does not offer its tag while the repeat guard holds it. And neither works while the app is in the + background, which is the case asked for. + The cost: while Bitkit is in front, another app that registered the same scheme leads to Android's chooser, as it + does in the background. +- **Reading.** `LaunchRequest` reads the tag as the phone's reader does. When the intent carries the tag's message + (`EXTRA_NDEF_MESSAGES`), `NdefCodec` decodes its URI, Text and absolute-URI records and takes the one request they + hold; a tag with several different requests asks for nothing. Without the message, as for an intent sent with + `adb`, the intent's data is the request. Then the phone's `nfcPaymentRequest`: `bitcoin:?lightning=` + becomes `lightning:`, and a `bitcoin:` request with a required (`req-`) parameter is refused. A tag + the watch refuses, as that one, a tag with several different requests or one whose records it cannot read, ends + on one line, "Not supported" (`WatchTagRefused`), with the reject haptic and OK (`WatchSendClose`), as the send + flow's refusals: Android already brought Bitkit to the front for it. Without a wallet or during the restore it + opens nothing. `lnurlw:` and `lnurlc:` tags are not taken: the filter does not match them, so Android does not + start Bitkit for one. +- **The send flow.** The request opens the same flow as a link: it waits for the wallet, runs the self-send guard, + prices the send and ends on Review with the hold to pay. The offline refusal, the QuickPay rules and "the wearer + has to be there" apply unchanged; the tap is the arrival from which QuickPay's 30 s count, so a tap on an + unlocked watch whose wallet is ready in time is paid under QuickPay without the hold, within the phone's amount + and daily limit. A tap during a send is dropped; one during the restore or without a wallet opens nothing. +- **A send under way.** `PaymentsRepo.send` runs in the repository's own scope and tells `SendMonitor` from its + start to its end, also when the screen that started it is gone. `LaunchGate` drops every link, tap and tile + request meanwhile, before it reaches a screen, so the send's outcome is not replaced and the same tag is not + priced a second time while the first payment is out. +- **Own tag.** A tag that carries the watch's own receive invoice ends on "Can't pay own invoice": the invoice's + payment hash is in `OwnInvoiceStore`. The phone's invoices are not, until pairing shares them (see Self-send + guard). +- **One tap, one request.** Android dispatches every activation of a tag again, and a phone emulating a tag + activates again whenever the field drops. Two things keep one tap from opening the flow twice. `NfcRepeatGuard`, + the phone's, holds reader mode from the next resume until the tag left the field. `NfcTapFilter` drops a request + equal to the last one until 3 s passed without it, so it also holds where reader mode does not. The filter and + the send state are one each for the process (`LaunchGate`), not fields of the activity, so they hold whichever + activity instance Android hands a tap to. A refused tag is filtered by its first record, so its refusal shows + once. Should a repeat get through, the flow opens again and Spark's idempotency key pays the invoice once (see + Paying once). +- **A launch from Recents** is no tap: `isReplayedLaunch` takes it as a plain launch, as for a link, in `onCreate` + and in `onNewIntent`. + +### Manifest + +- `android.permission.NFC`, for reader mode in the repeat guard and for registering the tag. +- `android.hardware.nfc` stays required (see Module overview). +- `android.hardware.nfc.hce` is `required="false"`, as on the phone. Requiring it would have Play hide the app from + a watch with NFC and without host card emulation, which could still pay by tap, the app's purpose; the receive + tag is an extra there, and the app checks the feature at runtime (`NfcMonitor.hasCardEmulation`) and hides the + hint without it. + +### Checked where + +The emulators have no NFC adapter, so no tag is read or offered there and the hint is hidden. + +- **Emulator.** `nfc-pay-background.xml`: an `NDEF_DISCOVERED` intent sent with `adb`, carrying the request as its + data and no tag, reaches the manifest filter with the app in the background and opens Review. It checks the + filter, `onNewIntent`, the repeat filter and the send flow. It does not check what a real tap differs in: `adb` + always adds `FLAG_ACTIVITY_NEW_TASK` and names the package, so it shows neither the NFC stack's start without + that flag nor the chooser; and a real intent always carries the tag's message, which production reads and only + `LaunchRequestTest` covers, while the journey takes the data fallback. +- **Unit tests.** The tag's bytes and the read sequence (`Type4TagEmulatorTest`, `NdefCodecTest`, + `NfcTagOfferTest`), the offer's lifecycle (`NfcTagEffectTest`, `ReceiveTagTest`, `ReceiveViewModelTest`), the + hint's place and the disabled hint's touch area on the 227dp and 192dp screens (`ReceiveQrContentTest`), the + reading of a tag and the repeat filter (`LaunchRequestTest`, `NfcTapFilterTest`), what a tap or a link may open, + also during a send (`LaunchGateTest`, `SendMonitorTest`), the wall clock, the revoke and the check of Spark's + list (`ReceiveViewModelTest`, `NfcTagEmitterTest`), the tap's send flow with QuickPay and the own tag + (`SendViewModelTest`, `PaymentsRepoTest`). +- **Previews.** `ReceiveQrScreen`'s `PreviewNfc` and `PreviewNfcOff`, `SendScreen`'s `PreviewTagRefused` + (`TagRefusedTest` checks its line and its close). +- **Physical watch.** The manual tests in [journeys/wear/README.md](../journeys/wear/README.md#nfc). Not run yet: + no physical watch was at hand. + +### Open questions + +- **Where does a tap arrive?** `singleTask` should deliver it to the running activity (`onNewIntent`), as on the + phone; manual tests 1e to 1h check it on a watch. +- **Does the watch read tags at all?** Wear OS watches ship NFC for card emulation; whether a given watch polls for + tags and dispatches `NDEF_DISCOVERED` with the screen on is the vendor's choice and was not tried. On a watch that + does not, Pay by tap needs reader mode on a screen of the app, which reads only while Bitkit is in front. +- **`requireDeviceUnlock` on a watch.** A watch counts as unlocked while it stays on the wrist. Whether the NFC + stack of a watch without a screen lock, or one just put on, serves the tag was not tried. +- **Observe mode and the wallet app.** Whether a watch's default wallet app answers a reader before the preferred + service of the app in front was not tried; the phone relies on the same preference. + +## Settings sync + +The watch holds the same seed as the phone, so it can read what the phone backed up. It imports the phone's settings +from VSS and never writes there. + +- **What the phone stores.** The phone uploads its whole settings file as the backup category `SETTINGS`: one JSON + envelope (`SettingsBackupV1`) with `version` 1, `createdAt` and `settings` (`BackupRepo.getBackupDataBytes`, + `SettingsData` in the phone's `SettingsStore.kt`), stored on VSS under the key `SETTINGS`. The phone uploads it + about 5 s after a setting changes. The phone reads a bitkit-ios backup under the same keys, with enums in + Swift's form (`BackupJson.kt`), and the watch reads those the same way; no bitkit-ios backup was tried. +- **What the watch adopts.** Six of those keys, and nothing else: + - `primaryDisplay` (bitcoin or fiat first) and `displayUnit` (`MODERN` for sats, `CLASSIC` for bitcoin with + eight decimals). The balance, the send review and result, the paid receive and the activity list and detail + are written in that unit; the amount entry of a send stays in sats. + - `selectedCurrency`, the fiat currency. + - `isQuickPayEnabled`, `quickPayAmount` (US dollars) and `quickPayDailyLimitMultiplier`. + + The phone stores no other QuickPay value and no watch-specific limit; none is invented here. +- **Access.** `VssPhoneBackupReader` sets vss-client up exactly as the phone's `VssBackupClient` and + `VssStoreIdProvider` do: the server (`Env.vssServerUrl`), the store id derived from the recovery phrase and + passphrase with the prefix `bitkit_v1_` plus the network name, and the LNURL-auth sign-in + (`Env.lnurlAuthServerUrl`) whose key the library derives from the same seed. The library decrypts the object with + a key from the seed too. Dev and tnet builds use Blocktank's staging servers, as the phone does; the phone's + `E2E_VSS_SERVER_URL` override for local backup tests has no counterpart on the watch. +- **Kept equal to the phone.** `wear/src/test/resources/phone-backup-contract.json` holds what the watch relies on: + the backup's key, the six settings in the phone's encoding, and each network's store id prefix and two servers. + The phone's `WatchBackupContractTest` compares it with what the phone app's own serializer writes and with the + phone's `Env` for the network it is built for; the watch's `PhoneBackupContractTest` reads the same file with the + watch's parser and compares the watch's `Env` for every network. A renamed setting or a moved server fails one of + them. The phone's values for mainnet and testnet are compared only when its tests run in a build for that network. +- **Read-only, by structure.** `PhoneBackupReader` is the watch's only way to VSS and has one call, a read of one + key. Its implementation is the only source file that names the VSS library, and it imports four of its + functions, derive the store id, sign in, get one object, shut the client down, and its error type. + `PhoneBackupReaderTest` fails the + build when the interface gains a call, when another file names the library, or when any source names one of the + library's store, delete, put, list or LDK calls. The sign-in itself asks the LNURL-auth server for a token and + changes nothing on VSS; in the library's source the client's constructor and its get make no put or delete + request (read at the head of synonymdev/vss-rust-client-ffi on 2026-11-28; the shipped binary is 0.5.26-rc2). +- **No client kept.** The library keeps one client for the process, with keys derived from the seed. Each import + builds it, reads and shuts it down, so nothing of the wallet stays in it once the read is over. The library runs + each of its calls to the end on the calling thread (`block_on`), so a read cannot be interrupted: one that was + given up is abandoned, ends with the HTTP call it is in and only then shuts its client down. Until then, a + moment after a lock or a pause, the client is still alive. +- **The library's timeouts** (read in synonymdev/vss-rust-client-ffi at `v0.5.26-rc2` and its `vss-client-ng` + 0.4.0). Each request to the VSS server ends after 10 s, for the connection, for a read and in all, and a failed + one is tried again up to 10 times with at most 15 s of pauses in total, so a read of the backup ends by itself. + The sign-in before it does not: the LNURL-auth requests go through an HTTP client built without a timeout. A + sign-in server that accepts the connection and never answers would hold the read, and the reader behind it, + until the connection drops, and every later import would wait its 30 s behind it and import nothing until the + app's process ends. The watch then goes on with the settings last imported, and a tap on the Phone settings row + shows the failure. A timeout there has to come from the library. +- **Who waits.** `SettingsSyncRepo` runs each import in a scope of its own, and the read apart from the import. + A caller only waits: one that is cancelled returns at once, and the import goes on and lands. The import stops waiting for its read after 30 s or when the wallet stops being + ready, at once in both cases, and then writes nothing. +- **When.** While Home is open, each time the wallet is ready with the app on screen and out of ambient mode, so at + every start, every return to the app and every wake from ambient mode, and every 5 minutes from then; and on a tap on the Phone settings row. An import + within a minute of the last read of this wallet's backup is skipped (`MIN_READ_GAP`), so a wallet that keeps + losing and finding its network does not sign in each time; the tap is never skipped. None is started in the + background or in ambient mode, and none for a wallet that is not connected and synced: a read under way is given + up the moment the wallet stops being ready, as on a lock or a pause, whoever started it, and its client is shut + down when its HTTP call returns. An import under way when the watch goes ambient or its caller leaves still + lands. Reading takes about 2 s; it is given up after 30 s. +- **Outcomes.** A backup that was read replaces the six values. The phone's `primaryDisplay` is adopted when it + differs from the one last imported, so the wearer's own swap on the balance lasts until the phone's setting + changes. A display value the backup lacks, or holds in a form the watch cannot read, keeps the watch's. A backup + that is missing, cannot be decrypted or decoded, is not the envelope, or has a `version` above 1 keeps the display + values and turns QuickPay off at once. The library reports an object it fetched and cannot decrypt or decode as + its get error and every failure to reach the server or sign in as another error (read in + synonymdev/vss-rust-client-ffi), so `VssPhoneBackupReader` takes a get error for an unreadable backup. QuickPay + values that are missing, mistyped or out of the phone's range turn QuickPay off. A read that fails, as without a + network, changes nothing, and QuickPay goes on with the settings last imported. Failures are + logged and never thrown. Only the wearer's own tap shows one, as one line under the row + (`WatchSettingsSyncFailed`, "Couldn't import"), until the next tap. +- **Parsing.** `PhoneSettingsParser` reads the JSON tree key by key rather than into the phone's settings class, so + unknown keys, new settings and other types never fail it. An envelope above 256 KB is refused. +- **Wipe.** Everything imported lives in the settings file, which the wallet's wipe clears: the units, the + currency, QuickPay, the import time and the day's QuickPay spend. An import that a wipe overtook is taken out + again, so a removed wallet's settings never reach the next wallet. +- **Logging.** The import logs its outcome only. The seed, the store id and the backup's content are never logged. +- **Size.** vss-client adds `libvss_rust_client_ffi.so` to the watch app: 4.3 MB for `arm64-v8a`, 2.8 MB for + `armeabi-v7a` and 4.8 MB for `x86_64`, about 2.0 MB gzipped for arm64, plus about 0.2 MB of bindings in the + debug dex. It ships its own R8 rules, and `:wear:minifyDevReleaseWithR8` passes with it. +- **Checked on the emulator.** On the API 37 emulator a dev build signed in to the staging VSS and imported the + settings backup of its restored wallet 1.8 s after the wallet synced (2026-11-28). +- **Known gap: a stale backup.** The watch sees a change only once the phone uploaded it. A phone that is offline, + or whose backup fails, leaves the old settings on VSS, and the watch keeps following them. +- **Later.** Pairing (a later PR) adds a live push from the phone over the Data Layer and the watch-specific limits. + +### 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 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 +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 (a later PR) 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. @@ -198,7 +865,11 @@ The watch holds the full recovery phrase and passphrase, because Breez needs the unlock while the app is on screen. The system does not announce every lock, so the app reads the lock state when the screen turns off, a few seconds later, whenever the app comes on screen and whenever its window regains focus. A lock that happens while the screen is already off is noticed at the next of these moments. A lock that lands while - the wallet is starting wins: the start ends locked and disconnected, never ready. + the wallet is starting wins: the start ends locked and disconnected, never ready. The wallet reads locked from + before that disconnect starts, as a pause stops it being ready before its own, so nothing is priced or sent on a + wallet that is going away while Spark takes its seconds to disconnect, and it is marked locked again once the + disconnect is over: a start that an unlock began meanwhile, which found Spark still connected, is not left + ready on a disconnected wallet, and the unlock then starts the wallet fresh. - **Plaintext in memory.** The store encodes and decrypts through byte arrays that it zeroes after use. The phrase and passphrase themselves are JVM strings, which Compose text input, bitkit-core and Breez all require; they cannot be zeroed and live until garbage collection. The restore screens keep the words only in their view model, never in @@ -367,3 +1038,9 @@ Measured on the emulator (Wear OS 7, API 37, 454×454 round, x86_64) unless note the screen off. - Re-wrapping the seed under an unlocked-device key when the wearer adds a screen lock after restoring. - bitkit-core costs the watch 47.5 MB per ABI for BIP39 alone; `Bip39` keeps a later swap to one file. +- Whether the watch's count of the day's QuickPay payments should be shared with the phone's before pairing + exists. +- Whether Wear OS watches read NFC tags and dispatch them with the screen on, which Pay by tap counts on: see NFC › + Open questions. +- Whether bitkit-ios writes all three QuickPay keys into its settings backup: the watch needs all three and leaves + QuickPay off when one is missing. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 8933ac5fdb..1d0dc2ec12 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/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index df8338121d..12061cc024 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -1075,6 +1075,14 @@ + + + + + + + + @@ -1091,6 +1099,14 @@ + + + + + + + + @@ -2702,6 +2718,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/journeys/README.md b/journeys/README.md index b65bbecef4..1d03a38d3e 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -139,6 +139,7 @@ journey PR, which is what made this file conflict on every merge. | Deep links, addresses and invoices handed to the app | `adb shell am start -a android.intent.action.VIEW -d ""`; `bitkit://` screen and sheet routes sit behind the dev-mode gate — [Running a journey](#running-a-journey), [deeplinks](deeplinks) | | A watch to run the Wear OS app on | a Wear OS watch emulator (`Wear_Large_Round_API37`, `Wear_Small_Round_API34`), or a physical watch over Wi-Fi debugging — [wear](wear/README.md) | | Watch gestures: pager swipes, swipe-to-dismiss, rotary crown, ambient mode | `adb shell input swipe`, `adb shell input rotaryencoder scroll --axis SCROLL,` and `KEYCODE_SLEEP`/`KEYCODE_WAKEUP` on the emulator; the real crown, bezel and wrist on a physical watch — [wear](wear/README.md#watch-gestures) | +| The phone's settings on the watch (units, currency, QuickPay) | a phone dev build with the same private settings wallet (the test phrase with a passphrase kept on this machine), never the public test phrase alone, writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) | | Typing on the watch keyboard | `adb shell input text` after closing the Wear OS keyboard with Back, which otherwise swallows the input — [wear](wear/README.md#typing) | ## Cross-platform 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 diff --git a/journeys/wear/README.md b/journeys/wear/README.md index f74a770e13..5c1cec7811 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 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 @@ -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 | | --- | --- | --- | @@ -107,7 +112,55 @@ the first sync of the test wallet, which the [Restored wallet](#restored-wallet) | `offline-keeps-last-balance.xml` | hosted | yes | | `background-disconnects-spark.xml` | hosted | yes | | `nfc-hint-states.xml` | hosted, physical watch only | yes | +| `nfc-pay-background.xml` | local | yes, 2 000 sats | | `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 | +| `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 | +| `send-hold-invoice-pending.xml` | local | yes, 2 000 sats | +| `send-hold-invoice-settle.xml` | local, right after `send-hold-invoice-pending.xml` | yes, with that journey's pending payment | +| `send-hold-invoice-cancel.xml` | local, right after `send-hold-invoice-pending.xml` | yes, with that journey's pending payment | +| `send-pending-reopen.xml` | local, right after `send-hold-invoice-pending.xml` | yes, with that journey's pending payment | +| `send-paid-reopen.xml` | local, right after `send-hold-invoice-pending.xml` or `send-pending-reopen.xml` | yes, with that journey's pending payment | +| `send-outcome-after-restart.xml` | local, within 2 minutes of `send-hold-invoice-pending.xml` | yes, with that journey's pending payment | +| `send-outcome-before-next-send.xml` | local, within 2 minutes of `send-hold-invoice-pending.xml` | yes, with that journey's pending payment and 2 000 sats | +| `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 | +| `settings-import-units.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, any balance above 0 | +| `settings-swap-survives-import.xml` | as `settings-import-units.xml`, after it | yes, any balance above 0 | +| `quickpay-skips-hold.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, 2 000 sats | +| `quickpay-on-app-start.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | +| `quickpay-over-limit-holds.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, 12 000 sats | +| `quickpay-off-holds.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | + +The six settings journeys read the phone's settings backup from Blocktank's hosted staging VSS, which every dev +build uses whatever its Spark network is: a watch on the local `./spark` stack reads the same backup as one on hosted +regtest. Nothing extra runs locally, no VSS and no LNURL-auth server. They need a phone app that wrote the backup +first: see [Phone settings on VSS](#phone-settings-on-vss). They never run on the public test phrase, whose backup +every other journey reads too: see [Private settings wallet](#private-settings-wallet). + +The daily QuickPay limit, a failed QuickPay payment that is taken out of the day's count, an amount the wearer +typed, and a missing, unreadable or newer backup have no journey: they depend on the exchange rate of the day, a +payment that fails on demand, an amountless invoice the local stack does not make, or a backup only a broken phone +would write. `QuickPayRepoTest.kt`, `QuickPaySpendStoreTest.kt`, `PaymentsRepoTest.kt`, `SettingsSyncRepoTest.kt` +and `PhoneSettingsParserTest.kt` cover them. + +A payment link opened again from Recents, which the watch takes as a plain launch, has no journey either: it was +not tried on a device, and `ReplayedLaunchTest.kt` covers the check. To try it by hand: with the app not running, +open a link as in `send-deeplink-bolt11.xml`, leave the review and Home with Back, open Bitkit from the watch's +Recents and check that Home shows and `WatchSendHold` does not. + +Paying an LNURL-pay link or a Lightning address has no journey, under QuickPay or with the hold: 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, the invoice the service returns and that only a link with one amount goes out under QuickPay. ### Local `./spark` stack @@ -126,8 +179,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 (and change none of its settings there, see [Private settings wallet](#private-settings-wallet)), 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. @@ -191,6 +244,146 @@ The test wallet restored with no passphrase, its balance loaded, Bitcoin as the A wallet restored by an earlier journey can stay: only [Fresh app](#fresh-app) and `remove-wallet.xml` remove it. +The watch imports the settings backup of whatever phrase it holds, so these journeys count on the public phrase's +backup holding the phone's defaults (Bitcoin first, sats, USD, QuickPay off) or not existing. If the balance shows +another currency or eight decimals, a phone app changed that backup: run the journeys with a private 12-word phrase +of your own instead, which they support (see [The test wallet](#the-test-wallet)). That phrase's phone settings must +be at their defaults too, so not the [Private settings wallet](#private-settings-wallet), whose backup holds +whatever the last settings journey set. + +### Private settings wallet + +Every journey that changes the phone's settings (`settings-*.xml`, `quickpay-*.xml`) runs on a wallet of its own, +never on the public test phrase. That phrase's settings backup is one object on the hosted staging VSS, shared by +hosted regtest and the local `./spark` stack and by everyone who restores the phrase: fiat first, euros or QuickPay +written there would reach every other watch on that phrase and break the journeys that expect the defaults. + +The private wallet is the public test phrase with a passphrase made on this machine. With a passphrase the phrase +is another wallet, with a settings backup of its own, so each machine's settings journeys stay apart from everyone +else's. + +The passphrase is not a secret. The phrase it is added to is public and the wallet holds regtest coins of no value; +the passphrase only keeps one machine's settings backup apart from another's. It may show in a layout dump or a +screenshot on your own machine. It still must not leave the machine, since anyone who has it can write to the same +backup: never commit it, never put it in a journey file, a pull request's text or media, and never paste it into an +issue. A screenshot or a recording of the phone's restore screen, or of the watch's passphrase screen, is not PR +media. + +1. Make the passphrase, once per machine, in a file outside the repository: + + ```bash + F=~/.config/bitkit-journeys/settings-passphrase + mkdir -p "${F%/*}" + [ -s "$F" ] || LC_ALL=C tr -dc a-z0-9 "$F" + ``` + + It keeps a passphrase that is already there. Twelve lowercase letters and digits are short and plain enough for + `adb shell input text`, which drops characters from long or dotted strings. +2. Restore it in the phone app, a plain dev build (see [Phone settings on VSS](#phone-settings-on-vss), step 1). From + a fresh install go through the onboarding to the Restore wallet screen (`RestoreWallet`, then + `MultipleDevices-button`). For each word, tap its field (`Word-0` to `Word-11`) and run + `adb shell input text `: eleven times `abandon`, then `about`. Tap `AdvancedButton`, tap `PassphraseInput` + and type the passphrase: + + ```bash + adb shell input text "$(cat ~/.config/bitkit-journeys/settings-passphrase)" + ``` + + [Check it](#checking-the-passphrase), then tap `RestoreButton`. +3. Set the phone's settings to where the journeys start: Default Unit Bitcoin, Denomination Modern, Local Currency + USD and QuickPay off. A new wallet has them already. On a rerun the restore brings back whatever the last run + left, as the currency first, Classic and EUR after a run that stopped at `settings-import-units.xml`: set them + back and keep the app open for 20 s, so it uploads them + ([Phone settings on VSS](#phone-settings-on-vss), steps 3 and 4). Then close the phone app + (`adb shell am force-stop to.bitkit.dev`). +4. Restore it on the watch: [Restored wallet](#restored-wallet) steps 1 to 3, then tap `RestorePassphraseAdd` + instead of `RestorePassphraseSkip`, tap `RestorePassphraseInput`, close the keyboard with Back + ([Typing](#typing)) and run the same `adb shell input text "$(cat …)"` command. [Check it](#checking-the-passphrase), + tap `RestorePassphraseConfirm` and wait for `WatchHomeBalance`. It reads `0` for a wallet that was never funded; + on a rerun against a local stack that kept its data it reads what the last run left. +5. Fund it before the phone's settings change: on the local `./spark` stack run `receive-paid.xml` on this wallet + while the phone's settings are still the ones of step 3. That journey expects "50 000", which is what a watch + on Bitcoin and Modern shows for a wallet that held nothing; after `settings-import-units.xml` set Classic, the + same payment reads "0.00050000". On a rerun with at least 12 000 sats left, skip this step. +6. Only now set what a journey asks for on the phone: [Phone settings on VSS](#phone-settings-on-vss). + +One private wallet serves all six journeys, in the order of the table: the settings journeys first, then the +QuickPay ones, whose preconditions set the units and the currency back. Remove it from the watch +(`remove-wallet.xml` or [Fresh app](#fresh-app)) before the journeys on the public phrase run again. + +To start over with an empty backup, delete `~/.config/bitkit-journeys/settings-passphrase` and begin at step 1: a +new passphrase is a new wallet with no backup and no balance. + +#### Checking the passphrase + +`adb shell input text` can drop a character, and a passphrase that differs by one names another wallet with no +backup. Check the field before you confirm: the layout dump has to hold the passphrase as typed, so this prints `1` +or more. + +```bash +android layout | grep -c -F "$(cat ~/.config/bitkit-journeys/settings-passphrase)" +``` + +On `0`, select all in the field, delete and type again, with the key events of +[Replacing a word](#replacing-a-word), then check again. The proof that phone and watch hold the same wallet comes +with the first import after step 6: the watch logs `Imported the phone's settings` once the phone wrote its backup. +It logs `Found no settings backup of the phone` when the two differ, and also before the phone ever changed a +setting. + +### Phone settings on VSS + +The watch never writes settings; it imports the ones a phone app backed up for the same recovery phrase +(Settings sync in [docs/wear.md](../../docs/wear.md)). So a phone has to write them first, once per journey that +names this precondition: + +1. Stop the watch emulator if this machine runs one emulator at a time, and start a phone emulator or connect a phone + ([journeys/README.md](../README.md) has the phone setup). Install a plain dev build of the phone app there with + `just install`: not an E2E build with `E2E_VSS_SERVER_URL` set, which would back up to a local server the watch + never reads. +2. Use the [Private settings wallet](#private-settings-wallet) in the phone app, restored there with its + passphrase. Never restore the public test phrase without that passphrase in a phone app to change its settings. + The recovery phrase and passphrase must be the same on phone and watch, since they name the backup. +3. Set what the journey asks for in the phone's Settings (`HeaderMenu`, `DrawerSettings`, `Tab-general`): + - Default Unit (`UnitSettings`): Bitcoin or the currency first, and the denomination (`DenominationModern`, + `DenominationClassic`). + - Local Currency (`CurrenciesSettings`). + - The QuickPay journeys read sats and dollars, so each of them asks for Default Unit Bitcoin, Denomination Modern + and Local Currency USD besides its QuickPay values: `settings-import-units.xml` leaves the wallet on the + currency, Classic and EUR. + - QuickPay (`QuickpaySettings`, past `QuickpayIntro-button` the first time): the switch (`QuickpayToggle`), the + amount (`QuickpayAmountSlider`, stops $1 to $50) and the daily limit (`QuickpayDailyLimitSlider`, 1× to 50×). + Tap the slider track above a stop's label, as in `settings/quickpay-payment-pin.xml`. +4. Keep the phone app open and online for 20 s: it uploads the settings about 5 s after the last change. Settings › + Security › Data Backups (`BackupSettings`) lists Settings with the time of its last backup. +5. Close the phone app (`adb shell am force-stop to.bitkit.dev` on the phone). The phone and the watch must never be + open on the same Spark network with one recovery phrase at the same time (#2152). +6. Start the watch again. It imports the settings when its wallet is ready, at every start and every 5 minutes, but + not within a minute of the last import and not in ambient mode; a tap on `WatchSettingsSync` on the Settings page + imports at once, and shows `WatchSettingsSyncFailed` when it could not. Debug builds log + `Imported the phone's settings`: + + ```bash + adb logcat -d -s BitkitWear | grep "SettingsSyncRepo" + ``` + +**Gotcha:** the public test phrase's backup belongs to everyone who restores it on a dev build, so its settings can +change without notice. That is why no settings journey reads or writes it, and why a phone app that holds the public +phrase without a passphrase, as for [Funding the test wallet](#funding-the-test-wallet), must leave its units, currency and QuickPay at +their defaults. + +**Gotcha:** QuickPay pays only a link that the wearer is there for: the send has to be priced within 30 s of the +link, with the watch unlocked, the app on screen and out of ambient mode all that time. A journey that sends its link +to a watch that is asleep, locked or still connecting for longer gets the review and the hold instead. A watch that +is offline gets neither: the flow ends on "Can't pay offline" and the link is dropped (`send-offline-error.xml`). + +**Gotcha:** the daily limit is counted per watch and per day on the watch's date, and every run of a paying QuickPay +journey adds to it. After about a dozen runs on one day the next one gets the review and the hold, and +`WatchSendSent` never shows. `remove-wallet.xml` or clearing the watch app's data clears the count; so does the next +day. + +**Never install the phone app on the watch or the watch app on the phone:** they share one application id. +`just install` and `just wear-install` each pick a device by `ANDROID_SERIAL`; set it before every install. + ### Restart The journeys restart the app with: @@ -253,6 +446,98 @@ 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 +``` + +### Hold invoices + +A hold invoice stays unpaid until its receiver claims or cancels it, which is how a journey makes a payment stay +pending for as long as it needs. Alice's node makes one for a payment hash whose preimage you keep. From the +bitkit-docker checkout that runs the local stack, the one with the `spark` script and `spark-regtest/compose.yml` +(the same directory `./spark up` ran in, so `docker compose` finds the project): + +```bash +ALICE="docker compose --profile spark exec -T spark-ldk-alice ldk-server-cli --config /local/ldk-alice.toml --base-url localhost:3536" +PREIMAGE="$(openssl rand -hex 32)" +HASH="$(printf %s "$PREIMAGE" | xxd -r -p | sha256sum | cut -d ' ' -f 1)" +$ALICE bolt11-receive-for-hash "$HASH" 1000sat | jq -r .invoice # the hold invoice of 1 000 sats +$ALICE bolt11-claim-for-hash "$PREIMAGE" -p "$HASH" # claim: the payment settles +$ALICE bolt11-fail-for-hash "$HASH" # cancel: the payment fails +``` + +The three subcommands and their arguments are those of the `ldk-server-cli` in the stack's Alice container +(image `bitkit-spark-ldk-server:7b61242`), checked against its help: `bolt11-receive-for-hash +[AMOUNT]`, `bolt11-claim-for-hash [-p ]` and `bolt11-fail-for-hash `. A +stack on another image may differ; `$ALICE --help` lists what it has. + +Claim or cancel only after the watch paid: before that there is nothing to claim. Each invoice takes one of the +two, once. Keep the three values until the journey is over: a payment that is neither claimed nor cancelled stays +pending on the watch, with its amount out of the balance, until the invoice's hold runs out. + +`send-hold-invoice-pending.xml` makes the pending payment, and each of the other hold invoice journeys starts from +the payment it leaves, so run it again before each of them and hand its values on. The one chain is +`send-pending-reopen.xml`, which leaves the payment pending: `send-paid-reopen.xml` can follow it directly. + +The watch reports such a payment as "Pending" (`WatchSendPending`) about 10 s after the hold to pay and shows it +for 5 s. How it ended shows for 2 s as one element, `WatchOutcomeSent` or `WatchOutcomeFailed`, whose content-desc +is the status and the amount, such as "Sent, ₿ 1 000"; the screen beneath is not listed meanwhile. It shows over +whatever screen is up, except a send flow past its loading ring and the receive QR, which it waits for the wearer +to leave. A pending result that is still on screen takes the outcome itself (`WatchSendSent`, or +`WatchSendError`). Both are short, so read the layout at least once a second while waiting for them; the log line +`Resolved watched payment '' as 'COMPLETED'` (or `'FAILED'`) under the `BitkitWear` tag stays as evidence. +The watch stays connected for a pending payment for up to 3 minutes after the send, also off screen; an outcome +that arrives after the app paused shows when the app is next opened and synced, and one that was found off screen +shows at the next open also when Android stopped the app's process in between. + +## 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). @@ -287,12 +572,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` @@ -354,3 +647,116 @@ build tools installed: ```bash AAPT2="$(ls -d "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}}"/build-tools/*/ | sort -V | tail -n 1)aapt2" ``` + +### Tags and taps + +The emulators read no tag and offer none, so two things stand in for a tap there: + +- **A tapped tag.** `nfc-pay-background.xml` sends the intent Android's tag dispatch would send, with the request as + its data. The real intent always carries the tag (`EXTRA_TAG`) and its message (`EXTRA_NDEF_MESSAGES`), which `adb` + cannot build; the app reads the message when it is there and the data otherwise, so the journey takes a path no + real tap takes, and only unit tests cover the message (`LaunchRequestTest`). `adb` also adds + `FLAG_ACTIVITY_NEW_TASK` and names the package; the NFC stack starts the activity without that flag and by the + filter alone, so the journey shows neither where a real tap arrives (`MainActivity` is `singleTask` for that, + manual tests 1e to 1h) nor Android's chooser. The filter's uppercase `BITCOIN` and `LIGHTNING` entries match + only such an `adb` or app intent: Android lowercases a tag record's scheme. The journey passed on the API 37 + emulator while `MainActivity` was `singleTop`. The activity is `singleTask` now, which changes how every wear + journey that starts it arrives (`onNewIntent`), so the journeys must be re-run under `singleTask`. + Re-run under `singleTask` at `7ac718aad` on the local stack: passed, along with send-deeplink-bolt11, send-own-invoice-guard, send-offline-error, receive-qr, receive-paid, tile-balance, nfc-required and restore-background-drops-words. + + ```bash + adb shell am start -a android.nfc.action.NDEF_DISCOVERED -d "lightning:" to.bitkit.dev + ``` + +- **The receive tag and its hint.** Without an NFC adapter the receive QR never offers its tag and shows no hint + (`WatchReceiveNfc` and `WatchReceiveNfcOff` are not listed). The offer's lifecycle and the hint are covered by unit + tests and by the `PreviewNfc` and `PreviewNfcOff` previews of `ReceiveQrScreen`; see docs/wear.md › NFC › Checked + where. + +### Manual tests on a physical watch + +These need a capability the journey environment lacks: an NFC radio on the watch, and a second NFC device to tap. +Run them on a physical watch with NFC on, unlocked and on the wrist, with a dev build +([On a physical watch](#on-a-physical-watch)) and a funded wallet on hosted regtest, and a phone with a dev build of +the phone app on **another** wallet: the two apps do not know each other's invoices before pairing, and with the +same wallet the phone's invoice would be the watch's own. Debug builds log the tag's offer under `BitkitWear` +(`Started the NFC tag`, `Stopped the NFC tag`). + +1. **Tap pays from the background.** On the phone open Receive with an amount of 1 000 sats, so that it offers its + NFC tag. On the watch leave Bitkit (press the crown) and keep the screen on. Hold the watch to the back of the + phone. + - Expected: Bitkit opens on the watch on the review with "1 000" and the hold to pay; nothing is paid before the + hold. Holding pays, and the phone shows the payment as received. + - 1a. Keep the watch on the phone for 10 s after the review shows: the review stays, and no second review or + chooser opens. + - 1b. With Bitkit open on the Balance page instead of in the background: the same review opens. + - 1c. With the watch's screen off, hold it to the phone for 5 s: nothing opens, as Android reads no tag with + the screen off. Wake the screen with the watch still on the phone: the review opens once, without lifting the + watch and tapping again. + - 1d. A printed or written NFC tag with one URI record `lightning:` gives the same result as 1. + - 1e. One activity, one task: after 1 and again after 1b, run + `adb shell dumpsys activity activities | grep -c 'Hist.*to.bitkit.wear.ui.MainActivity'`. Expected: it prints + 1, and the watch's Recents show Bitkit once: the tap reached the running activity and made no second one. + - 1f. Tap again during Sending: start a payment as in 1 with a second tag at hand (another invoice). Lift the + watch off the phone when the review shows and wait 3 s, so the watch reads tags again, then hold to pay and + tap the second tag while the bolt and ring show. Expected: the sending screen stays and ends on "Sent", and + no second review opens; the log lists "Dropped launch request 'Send' during a send", unless the tap came + while the watch still held off repeats of the first tag, when Android sends nothing and nothing is logged. + If "Sent" shows before the second tap, run it again. Lifting and tapping the second tag after the flow + closed opens its review. + - 1g. Tap with Bitkit open from the launcher: open Bitkit from the launcher, open a payment link from the + phone or `adb` so a review shows, then tap a tag with another invoice. Expected: the tag's review replaces + the first in the same activity; Recents shows Bitkit once, and nothing of the first link is paid. + - 1h. A link from another app's task, where the watch has an app that opens a `lightning:` link without a new + task, as a notes or browser app that shows links; skip it otherwise, since `adb` always adds a new task. + With Bitkit running, open the link from that app. Expected: the review opens in Bitkit's own task, and + Recents shows Bitkit once. + - 1i. A tag the watch refuses: write `bitcoin:
?req-foo=1` as one URI record to a tag and tap it. + Expected: "Not supported" with OK (`WatchTagRefused`), once, however long the watch stays on the tag; OK + returns to Home. +2. **QuickPay on a tap.** With QuickPay on in the phone settings the watch imported and an amount within its limit + (the private settings wallet, see [Phone settings on VSS](#phone-settings-on-vss)), repeat 1 with a tag of + another wallet. + - Expected: the send goes out without the review and ends on "Sent"; the log lists "Skipped the hold to pay + under QuickPay". +3. **Offline tap.** Turn the watch's Wi-Fi and Bluetooth off, wait for the offline icon on the Balance page, then + tap as in 1. + - Expected: "Can't pay offline" with OK; nothing is paid when the network returns. +4. **The phone pays the watch's receive QR.** On the watch open Receive and the QR. On the phone open Send and its + NFC scanner, and hold the phone to the watch. + - Expected: below the QR the NFC hint animates (`WatchReceiveNfc`); the phone reads the watch's invoice and + opens its amount entry (the invoice is amountless); after the phone pays, the watch shows the check with the + amount. + - 4a. The hint is clear of the QR's white square, and the phone's camera still scans the QR. + - 4b. `adb shell svc nfc disable`: the hint turns dimmed and slashed (`WatchReceiveNfcOff`), the phone reads + nothing, and a tap on the hint opens the NFC settings. Run `adb shell svc nfc enable` and swipe back from the + NFC settings to the QR: the hint animates again and the phone reads the invoice. + - 4c. Leave the QR showing until the watch's screen is off, and wait until the invoice expired (1 h; the log's + "Showing invoice" line dates it). Wake the watch, and open Bitkit if the watch face shows: it returns on the + receive screen. Expected: the loading ring, then a new QR, or the QR-hidden icon that shows the new QR on a + tap (a screen that went off without ambient mode keeps the QR resting); the log lists a second "Showing + invoice" with another invoice; the phone's scanner never reads the old one. +5. **The tag stops with the QR.** With the QR showing, check with the phone's scanner that each of these ends the + tag (the phone reads nothing, and the log lists "Stopped the NFC tag"): swiping back to the Receive page; + pressing the crown; covering the watch until it goes ambient; waiting 2 min until the QR rests; after a payment, + while the check shows. + - Expected: nothing is read in any of them, and tapping the resting screen, waking the watch or tapping the + check for a new invoice brings the tag back with the QR. + - 5a. A tag tapped on the QR: with the QR showing, tap the watch on a payment tag as in 1. Expected: the review + opens above Home in place of the QR, and the log lists "Stopped the NFC tag"; the phone's scanner reads + nothing from the watch while the review shows. + - 5b. Recreation: with the QR showing, change the watch's font size or language in its settings and return. + Expected: the same QR shows, the log lists "Stopped the NFC tag" and then "Started the NFC tag" once each, + and the phone reads the invoice again. +6. **The watch's own tag.** Read the invoice of the watch's receive QR from the log + ([Reading the receive invoice](#reading-the-receive-invoice)), write `lightning:` as one URI record to a + blank NFC tag with any tag-writing app on the phone, and tap the watch on that tag. + - Expected: "Can't pay own invoice" with OK, and no hold to pay. +7. **TalkBack says how a pending payment ended.** Its setup is not this section's: it needs the local `./spark` + stack, for Alice's hold invoice ([Hold invoices](#hold-invoices)), with the watch's wallet funded on it, and no + phone and no NFC, so the emulator works too. It is a manual test only because the journey environment cannot + hear TalkBack: turn TalkBack on and run `send-hold-invoice-pending.xml` by hand twice. The first time claim the + payment while "Pending" still shows, the second time after it closed, from the Balance page. + - Expected: the first time TalkBack says "Sent" as the line changes; the second time it says "Sent, ₿ 1 000" + once as the check appears, and nothing of the screen beneath can be focused meanwhile. Cancelling in place of + claiming gives "Payment failed" and "Payment failed, ₿ 1 000". Not run yet. diff --git a/journeys/wear/activity-list.xml b/journeys/wear/activity-list.xml new file mode 100644 index 0000000000..80116eaadb --- /dev/null +++ b/journeys/wear/activity-list.xml @@ -0,0 +1,24 @@ + + + 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 to Receive: `adb shell input swipe 400 227 60 227 300` + 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" + 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" + 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/nfc-pay-background.xml b/journeys/wear/nfc-pay-background.xml new file mode 100644 index 0000000000..535f2d4003 --- /dev/null +++ b/journeys/wear/nfc-pay-background.xml @@ -0,0 +1,32 @@ + + + A tapped NFC payment tag opens the send flow while Bitkit is in the background: Android's tag dispatch starts the + app with an `NDEF_DISCOVERED` intent, the review shows the tag's amount, a repeat of the same tap changes nothing, + and holding the pay button pays. The emulators have no NFC, so no tag can be tapped there; `adb` sends the intent + the dispatch would send, with the request as its data and without the tag and its message. That checks the + manifest filter, `onNewIntent`, the repeat filter and the send flow. The reading of a tag's message is + unit-tested only (`LaunchRequestTest`): a real tap always carries it, and `adb` cannot. `adb` also adds + `FLAG_ACTIVITY_NEW_TASK` and names the package, which the NFC stack does not, so this does not check where a + real tap arrives or that a watch reads a tag at all; the manual tests in journeys/wear/README.md › NFC cover + those on a physical watch. 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, and QuickPay off or never imported (a watch with QuickPay on pays 1 000 sats without the review, as + designed). 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 input keyevent KEYCODE_HOME` and wait 2 s + Run `adb shell dumpsys activity activities | grep -m1 topResumedActivity` and verify it does not name `to.bitkit.dev`: the app is in the background + Run `adb logcat -c` + Run `adb shell 'am start -a android.nfc.action.NDEF_DISCOVERED -d "lightning:<invoice>" to.bitkit.dev; sleep 1; am start -a android.nfc.action.NDEF_DISCOVERED -d "lightning:<invoice>" to.bitkit.dev'`: one command, so the repeat follows the tap by 1 s however slow the runner is, as when the watch stays on the tag + Wait up to 20 s until "WatchSendHold" is listed: the wallet may connect again first + Verify "WatchSendAmount" reads "1 000" + Run `adb logcat -d -s BitkitWear | grep -c "Dropped a repeat of an NFC tap"` and verify it prints 1: the repeat opened no second flow + 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 up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself on the Balance page + + diff --git a/journeys/wear/nfc-required.xml b/journeys/wear/nfc-required.xml index b6b712f6c3..c01aefe96f 100644 --- a/journeys/wear/nfc-required.xml +++ b/journeys/wear/nfc-required.xml @@ -1,6 +1,7 @@ - The watch app requires NFC hardware (`android.hardware.nfc`, required), so Play offers it only to watches with NFC. + The watch app requires NFC hardware (`android.hardware.nfc`, required), so Play offers it only to watches with NFC, + and does not require host card emulation (`android.hardware.nfc.hce`), so a watch without it is not filtered out. `uses-feature` is a store filter, not an install check, so the app still installs on the NFC-less emulators. `dumpsys package` does not list required features, so the check reads the installed APK with `aapt2` from the newest SDK build tools installed (journeys/wear/README.md › NFC sets `AAPT2`). Emulator and physical watch. @@ -12,6 +13,6 @@ Run `adb pull "$(adb shell pm path to.bitkit.dev | grep base.apk | sed 's/package://')" base.apk` Run `"$AAPT2" dump badging base.apk | grep uses-feature` and verify it lists `android.hardware.nfc` Verify the same output lists `android.hardware.type.watch` - Run `"$AAPT2" dump badging base.apk | grep -c nfc.hce` and verify it prints 0: host card emulation is not required yet + Run `"$AAPT2" dump badging base.apk | grep nfc.hce` and verify its one line starts with `uses-feature-not-required`: host card emulation, which the receive tag uses, is declared but not required diff --git a/journeys/wear/quickpay-off-holds.xml b/journeys/wear/quickpay-off-holds.xml new file mode 100644 index 0000000000..aa17ea6546 --- /dev/null +++ b/journeys/wear/quickpay-off-holds.xml @@ -0,0 +1,28 @@ + + + QuickPay turned off on the phone stops on the watch with the next import: the same small invoice that QuickPay + paid by itself now opens the review and waits for the hold. A watch that never imported the phone's settings + behaves the same. Emulator and physical watch. + + Precondition: run quickpay-skips-hold.xml first, on its Private settings wallet and never the public test phrase + alone. Then, on the phone with the same wallet, turn QuickPay off and leave Default Unit Bitcoin, Denomination + Modern and Local Currency USD as that journey set them, so the amount below reads in sats; wait for the backup + and close the phone app, see journeys/wear/README.md › Phone settings on VSS. Watch: the + wallet of quickpay-skips-hold.xml on the local ./spark stack with at least 2 000 sats, the app open on the Balance + page and the loading ring stopped. README › Holding to pay has the hold gesture. + + + Swipe left three times to the Settings page (README › Watch gestures) + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Swipe right three times to the Balance page + Run `../bitkit-docker/spark invoice 200` 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 "200" + Verify "WatchSendSent" does not get listed within 5 s: nothing was paid + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + + diff --git a/journeys/wear/quickpay-on-app-start.xml b/journeys/wear/quickpay-on-app-start.xml new file mode 100644 index 0000000000..e309cb8d11 --- /dev/null +++ b/journeys/wear/quickpay-on-app-start.xml @@ -0,0 +1,25 @@ + + + A payment link that starts the app is paid under QuickPay too: the watch reads the settings it last imported + from the phone, however long ago, as the phone reads its own, and fetches the rates it does not keep across a + restart before it decides. The send goes out without the review and the hold. Emulator, or a physical watch that + stays on the wrist and unlocked. + + Precondition: run quickpay-skips-hold.xml first, so the watch's last import has QuickPay on with Default Unit + Bitcoin, Denomination Modern and Local Currency USD, which the amount below counts on, and change nothing on the + phone since. Watch: the wallet of quickpay-skips-hold.xml on the local ./spark stack with at least 2 000 sats and + a network on which the balance comes back within 20 s of a start. A wallet that needs more than 30 s shows the + review and the hold instead, which is as designed and fails this journey. So does a locked watch: KEYCODE_WAKEUP + lights the screen and unlocks nothing, and QuickPay never pays on a locked watch. + + + Run `adb shell am force-stop to.bitkit.dev` + Run `adb shell input keyevent KEYCODE_WAKEUP` + Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> + Run `adb logcat -c` + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev`, which starts the app + Wait up to 40 s until "WatchSendSent" is listed, touching nothing + Verify "WatchSendResultAmount" reads "200" + Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" + + diff --git a/journeys/wear/quickpay-over-limit-holds.xml b/journeys/wear/quickpay-over-limit-holds.xml new file mode 100644 index 0000000000..3fc1dc40f8 --- /dev/null +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -0,0 +1,28 @@ + + + With QuickPay on in the phone's settings, an invoice above the phone's QuickPay amount still opens the review and + is paid only by the hold. Emulator and physical watch. + + Precondition, in this order, as quickpay-skips-hold.xml: Private settings wallet, never the public test phrase + alone, restored on the watch on the local ./spark stack and funded there with at least 12 000 sats before any + phone setting changed (journeys/wear/README.md › Private settings wallet, step 5). Then Phone settings on VSS, + see README › Phone settings on VSS, with Default Unit Bitcoin, Denomination Modern, Local Currency USD and + QuickPay on at $1 and 5×, and the phone app closed. Watch: the app open on the Balance page and the loading ring + stopped. The fiat value below is in dollars, which is what those units give. 10 000 sats are above $1 while a bitcoin costs more than $10 000. README › Holding to pay + has the hold gesture. + + + Swipe left three times to the Settings page (README › Watch gestures) + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Swipe right three times to the Balance page + Wait up to 1 minute until "WatchHomeBalanceSecondary" reads a fiat value: without the rates QuickPay holds whatever the amount + Run `../bitkit-docker/spark invoice 10000` 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 "WatchSendSent" does not get listed within 5 s: nothing was paid + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + + diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml new file mode 100644 index 0000000000..513ea02e9d --- /dev/null +++ b/journeys/wear/quickpay-skips-hold.xml @@ -0,0 +1,31 @@ + + + With QuickPay on in the phone's settings, an invoice under the phone's QuickPay amount is paid without the review + and without the hold: the link goes straight to sending and the same "Sent" check, and the flow closes by itself. + Emulator and physical watch. + + Precondition, in this order: Private settings wallet, see journeys/wear/README.md › Private settings wallet, + never the public test phrase alone, restored on the watch on the local ./spark stack (README › Local ./spark + stack) and funded there with at least 2 000 sats before any phone setting changed (README › Private settings + wallet, step 5). Then Phone settings on VSS, see README › Phone settings on VSS, with Default Unit Bitcoin, + Denomination Modern, Local Currency USD, QuickPay on at $1 and the daily limit at 5× on the phone, and the phone + app closed. Watch: the app open on the Balance page and the loading ring stopped. The amounts below are in sats + and the fiat value in dollars, which is what those units give. The watch reads the phone's settings from the + hosted staging VSS whatever Spark network it is on. 200 sats are under $1 while a bitcoin costs less than + $500 000. + + + Swipe left three times to the Settings page (README › Watch gestures) + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Swipe right three times to the Balance page + Wait up to 1 minute until "WatchHomeBalanceSecondary" reads a fiat value: QuickPay needs the rates + Run `../bitkit-docker/spark invoice 200` 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 20 s until "WatchSendSent" is listed, touching nothing + Verify "WatchSendResultAmount" reads "200" + Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" + Wait up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself + + 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-paid.xml b/journeys/wear/receive-paid.xml new file mode 100644 index 0000000000..72d42d017b --- /dev/null +++ b/journeys/wear/receive-paid.xml @@ -0,0 +1,27 @@ + + + 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: a wallet restored on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack: the + Restored wallet (README › Restored wallet), or the Private settings wallet (README › Private settings wallet) + when this funds it for the settings and QuickPay journeys. Either way the phone's settings of that wallet are + still the defaults, Bitcoin first and Denomination Modern, so the paid amount reads in sats: on the private + wallet run this before any settings journey, since under Classic the same amount reads "0.00050000". The app is + 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" + 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" + 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-rests.xml b/journeys/wear/receive-qr-rests.xml new file mode 100644 index 0000000000..d1e8efde80 --- /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 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 + 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 new file mode 100644 index 0000000000..db2b21f4d4 --- /dev/null +++ b/journeys/wear/receive-qr.xml @@ -0,0 +1,24 @@ + + + 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" + 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 + 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 a black-on-white QR code fills the middle of the screen + + 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-deeplink-bolt11.xml b/journeys/wear/send-deeplink-bolt11.xml new file mode 100644 index 0000000000..a4ffcedaf5 --- /dev/null +++ b/journeys/wear/send-deeplink-bolt11.xml @@ -0,0 +1,24 @@ + + + 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" + 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 + 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 new file mode 100644 index 0000000000..1d0e96946d --- /dev/null +++ b/journeys/wear/send-hold-cancel.xml @@ -0,0 +1,24 @@ + + + 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 + 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> + + diff --git a/journeys/wear/send-hold-invoice-cancel.xml b/journeys/wear/send-hold-invoice-cancel.xml new file mode 100644 index 0000000000..03716a8234 --- /dev/null +++ b/journeys/wear/send-hold-invoice-cancel.xml @@ -0,0 +1,26 @@ + + + A payment the watch reported as pending fails when its receiver cancels it, and the watch tells the wearer: a + cross shows over the current screen for 2 s, read by a screen reader as "Payment failed" with the amount, the + balance is back to what it was and Activity shows the payment as failed. Emulator and physical watch. + + Precondition: send-hold-invoice-pending.xml was run just before, on the same emulator or watch, and its payment + is still pending: keep its <balance> and <hash>. The app is still open on the Balance page. README › + Hold invoices has the cancel command. The outcome shows for 2 s, so read the layout at least once a second while + waiting for it. The app stays on screen for the whole journey. + + + Verify "WatchHomeBalance" does not read <balance>: the amount and its fee are held while pending + Run `adb logcat -c` + Cancel the payment as in README › Hold invoices, with <hash> + Wait up to 20 s until "WatchOutcomeFailed" is listed + Verify "WatchOutcomeFailed" has the content-desc "Payment failed, ₿ 1 000" + Wait 3 s + Verify "WatchHomeBalance" reads <balance> again + Verify `adb logcat -d -s BitkitWear | grep -c "Resolved watched payment"` prints 1 + Swipe the pager left to Settings: `adb shell input swipe 400 227 60 227 300` + Swipe the pager left again, to Activity: `adb shell input swipe 400 227 60 227 300` + Tap "WatchActivityItem-0" + Verify "WatchActivityDetailStatus" reads "Failed" + + diff --git a/journeys/wear/send-hold-invoice-pending.xml b/journeys/wear/send-hold-invoice-pending.xml new file mode 100644 index 0000000000..13d1653f64 --- /dev/null +++ b/journeys/wear/send-hold-invoice-pending.xml @@ -0,0 +1,32 @@ + + + A hold invoice is paid only when its receiver claims it. The watch shows "Pending" with the amount about 10 s + after the hold to pay, with the loading ring alone until then and never "Waiting for network", and closes by + itself after 5 s. Emulator and physical watch. + + The journey leaves the payment pending, which is the precondition of send-hold-invoice-settle.xml, + send-hold-invoice-cancel.xml, send-pending-reopen.xml, send-paid-reopen.xml, send-outcome-after-restart.xml and + send-outcome-before-next-send.xml: run one of them next and keep <balance>, <preimage>, <hash> + and <invoice> for it. Run on its own, cancel the payment at the end as in README › Hold invoices. + + 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 › Hold invoices has the commands, README › Holding to pay the hold gesture. The pending result + shows for 5 s, so read the layout at least once a second while waiting for it. The app stays on screen for the + whole journey. + + + Note the text of "WatchHomeBalance" as <balance> + Make a hold invoice of 1 000 sats as in README › Hold invoices and note <preimage>, <hash> and <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 + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait 6 s + Verify "WatchSendSending" is listed + Verify "WatchSendWaiting" is not listed + Wait up to 15 s until "WatchSendPending" is listed + Verify "WatchSendPending" reads "Pending" + Verify "WatchSendResultAmount" reads "1 000" + Wait up to 10 s until "WatchHomeBalance" is listed + + diff --git a/journeys/wear/send-hold-invoice-settle.xml b/journeys/wear/send-hold-invoice-settle.xml new file mode 100644 index 0000000000..16ca61923d --- /dev/null +++ b/journeys/wear/send-hold-invoice-settle.xml @@ -0,0 +1,26 @@ + + + A payment the watch reported as pending is told once when its receiver claims it: a check shows over the current + screen for 2 s, read by a screen reader as "Sent" with the amount, and Activity shows the payment as sent. + Emulator and physical watch. + + Precondition: send-hold-invoice-pending.xml was run just before, on the same emulator or watch, and its payment + is still pending: keep its <preimage> and <hash>. The app is still open on the Balance page. README + › Hold invoices has the claim command. The outcome shows for 2 s, so read the layout at least once a second + while waiting for it. The app stays on screen for the whole journey. + + + Run `adb logcat -c` + Claim the payment as in README › Hold invoices, with <preimage> and <hash> + Wait up to 20 s until "WatchOutcomeSent" is listed + Verify "WatchOutcomeSent" has the content-desc "Sent, ₿ 1 000" + Wait 3 s + Verify "WatchOutcomeSent" is not listed + Verify "WatchHomeBalance" is listed + Verify `adb logcat -d -s BitkitWear | grep -c "Resolved watched payment"` prints 1 + Swipe the pager left to Settings: `adb shell input swipe 400 227 60 227 300` + Swipe the pager left again, to Activity: `adb shell input swipe 400 227 60 227 300` + Verify "WatchActivityItem-0" shows "- ₿ 1 000" + Verify "WatchActivityItem-0" shows no "Pending" + + 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-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/journeys/wear/send-outcome-after-restart.xml b/journeys/wear/send-outcome-after-restart.xml new file mode 100644 index 0000000000..1e38761b89 --- /dev/null +++ b/journeys/wear/send-outcome-after-restart.xml @@ -0,0 +1,26 @@ + + + The outcome of a pending payment that is found while the app is off screen is still told when Android stops the + app's process before the wearer comes back: the next open shows the check with the amount, once. Emulator and + physical watch. + + Precondition: send-hold-invoice-pending.xml was run just before, on the same emulator or watch, and its payment + is still pending: keep its <preimage> and <hash>. The app is still open on the Balance page. Start + within 2 minutes of that journey's hold to pay: the watch stays connected off screen for 3 minutes after a send, + which is how the outcome is found there. README › Hold invoices has the claim command. + + + Run `adb logcat -c` + Run `adb shell input keyevent KEYCODE_HOME` + Claim the payment as in README › Hold invoices, with <preimage> and <hash> + Run `adb logcat -d -s BitkitWear | grep -c "Resolved watched payment"` every 5 s until it prints 1, for up to 1 minute: the outcome was found off screen + Run `adb shell am kill to.bitkit.dev` + Verify `adb shell pidof to.bitkit.dev` prints nothing: the process ended before the outcome was shown + Run `adb shell am start -n to.bitkit.dev/to.bitkit.wear.ui.MainActivity` + Wait up to 15 s until "WatchOutcomeSent" is listed, reading the layout at least once a second + Verify "WatchOutcomeSent" has the content-desc "Sent, ₿ 1 000" + Wait 3 s + Verify "WatchOutcomeSent" is not listed + Verify `adb logcat -d -s BitkitWear | grep -c "Resolved watched payment"` prints 1: it was not found a second time + + diff --git a/journeys/wear/send-outcome-before-next-send.xml b/journeys/wear/send-outcome-before-next-send.xml new file mode 100644 index 0000000000..0f42db6e65 --- /dev/null +++ b/journeys/wear/send-outcome-before-next-send.xml @@ -0,0 +1,27 @@ + + + The end of an earlier payment is told before the next send shows anything of its own, and never over it: a + payment link opened while a failed payment's cross is still to be shown first shows that cross, over the loading + ring, and only then the review with the hold to pay. Emulator and physical watch. + + Precondition: send-hold-invoice-pending.xml was run just before, on the same emulator or watch, and its payment + is still pending: keep its <hash>. The app is still open on the Balance page. Start within 2 minutes of + that journey's hold to pay, as the watch stays connected off screen for 3 minutes after a send. README › Hold + invoices has the cancel command, README › Local invoices the second invoice. The outcome shows for 2 s, so read + the layout at least once a second while waiting for it. + + + From the bitkit-docker checkout, run `./spark invoice 1000` (README › Local invoices) and note the invoice as <next invoice> + Run `adb logcat -c` + Run `adb shell input keyevent KEYCODE_HOME` + Cancel the payment as in README › Hold invoices, with <hash> + Run `adb logcat -d -s BitkitWear | grep -c "Resolved watched payment"` every 5 s until it prints 1, for up to 1 minute + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<next invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchOutcomeFailed" is listed, reading the layout at least once a second + Verify "WatchSendHold" was not listed in any layout read since the link was opened + Wait up to 10 s until "WatchSendHold" is listed + Verify "WatchOutcomeFailed" is not listed + Verify "WatchSendAmount" reads "1 000" + Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` + + diff --git a/journeys/wear/send-own-invoice-guard.xml b/journeys/wear/send-own-invoice-guard.xml new file mode 100644 index 0000000000..ab4fa92e0f --- /dev/null +++ b/journeys/wear/send-own-invoice-guard.xml @@ -0,0 +1,23 @@ + + + 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" + 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 Home is back on the Receive page it was left on: "WatchReceiveOpen" is listed + + diff --git a/journeys/wear/send-paid-reopen.xml b/journeys/wear/send-paid-reopen.xml new file mode 100644 index 0000000000..c6286a8118 --- /dev/null +++ b/journeys/wear/send-paid-reopen.xml @@ -0,0 +1,22 @@ + + + An invoice whose pending payment settled, opened again, ends on "Already paid" with no review and no hold to + pay, and nothing is paid a second time. Emulator and physical watch. + + Precondition: send-hold-invoice-pending.xml, or send-pending-reopen.xml after it, was run just before, on the + same emulator or watch, and its payment is still pending: keep its <preimage>, <hash> and + <invoice>. The app is still open on the Balance page. README › Hold invoices has the claim command. + + + Claim the payment as in README › Hold invoices, with <preimage> and <hash> + Wait up to 20 s until "WatchOutcomeSent" is listed, reading the layout at least once a second + Wait up to 5 s until "WatchHomeBalance" is listed + Note the text of "WatchHomeBalance" as <paid balance> + 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 "Already paid" + Verify "WatchSendHold" is not listed + Tap "WatchSendClose" + Verify "WatchHomeBalance" still reads <paid balance> + + diff --git a/journeys/wear/send-pending-reopen.xml b/journeys/wear/send-pending-reopen.xml new file mode 100644 index 0000000000..f2ebbb82f6 --- /dev/null +++ b/journeys/wear/send-pending-reopen.xml @@ -0,0 +1,23 @@ + + + An invoice whose payment is still pending, opened again, is not offered for a second hold to pay: the watch + shows "Pending" with the amount straight away, without the review, and closes by itself. Emulator and physical + watch. + + The payment is still pending at the end: run send-paid-reopen.xml next, or cancel the payment as in README › + Hold invoices. + + Precondition: send-hold-invoice-pending.xml was run just before, on the same emulator or watch, and its payment + is still pending: keep its <invoice>. The app is still open on the Balance page. The pending result shows + for 5 s, so read the layout at least once a second while waiting for it. + + + Note the text of "WatchHomeBalance" as <pending balance> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendPending" is listed, reading the layout at least once a second + Verify "WatchSendResultAmount" reads "1 000" + Verify "WatchSendHold" was not listed in any layout read since the link was opened + Wait up to 10 s until "WatchHomeBalance" is listed + Verify "WatchHomeBalance" still reads <pending balance>: nothing was paid a second time + + diff --git a/journeys/wear/settings-import-units.xml b/journeys/wear/settings-import-units.xml new file mode 100644 index 0000000000..2d14787e86 --- /dev/null +++ b/journeys/wear/settings-import-units.xml @@ -0,0 +1,26 @@ + + + The watch adopts the phone's units and currency from the phone's settings backup: fiat first, euros, and bitcoin + written with eight decimals. The Settings page shows when the phone's settings were last imported, and a tap on + that row imports them again. Emulator and physical watch. + + Precondition, in this order: Private settings wallet, see journeys/wear/README.md › Private settings wallet, + never the public test phrase alone, restored on the watch on the local ./spark stack (README › Local ./spark + stack) and funded there with a balance above 0 before any phone setting changed (README › Private settings + wallet, step 5: receive-paid.xml reads its amount in sats). Only then Phone settings on VSS, see README › Phone + settings on VSS, with Default Unit set to the currency, Denomination set to Classic, Local Currency set to EUR + and QuickPay off on the phone, and the phone app closed. + + + Restart the app (README › Restart) + Dump `android layout` every 5 s until "WatchHomeBalanceSymbol" reads "€", for up to 1 minute: the import follows the first sync, and the rates load after the balance + Verify "WatchHomeBalanceSecondary" reads the balance in bitcoin with eight decimals, such as "0.00050000" + Swipe left three times to the Settings page (README › Watch gestures) + Verify "WatchSettingsSync" is listed and reads "Phone settings" + Verify "WatchSettingsSyncTime" reads a time of at most a few minutes ago, such as "0 min. ago" + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Verify "WatchSettingsSyncFailed" is not listed + + diff --git a/journeys/wear/settings-swap-survives-import.xml b/journeys/wear/settings-swap-survives-import.xml new file mode 100644 index 0000000000..8b218b1ab4 --- /dev/null +++ b/journeys/wear/settings-swap-survives-import.xml @@ -0,0 +1,21 @@ + + + The wearer's own swap of the balance's unit lasts across an import of the phone's settings, as long as the phone's + setting stays the same: with fiat first on the phone, a tap puts bitcoin first on the watch, and it is still first + after a restart and the import that follows it. Emulator and physical watch. + + Precondition: run settings-import-units.xml first, and change nothing on the phone since. Watch: the wallet of + settings-import-units.xml, the app open on the Settings page, where that journey ends. + + + Swipe right three times to the Balance page (README › Watch gestures) + Verify "WatchHomeBalanceSymbol" reads "€" + Tap "WatchHomeBalanceToggle" + Verify "WatchHomeBalanceSymbol" reads "₿" + Verify "WatchHomeBalance" reads the balance with eight decimals, such as "0.00050000" + Run `adb logcat -c` + Restart the app (README › Restart) + Wait up to 1 minute until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Verify "WatchHomeBalanceSymbol" still reads "₿": the wearer's swap lasts while the phone's setting stays the same + + 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 + + diff --git a/wear/build.gradle.kts b/wear/build.gradle.kts index cc3f01ca8e..85d12e9b6c 100644 --- a/wear/build.gradle.kts +++ b/wear/build.gradle.kts @@ -228,7 +228,10 @@ 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") } + // Read-only import of the phone's settings backup; see docs/wear.md, Settings sync. + implementation(libs.vss.client) // Lifecycle implementation(libs.lifecycle.viewmodel.compose) implementation(libs.lifecycle.runtime.compose) @@ -246,6 +249,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 e3605fc509..e094432335 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -8,7 +8,13 @@ android:name="android.hardware.nfc" android:required="true" tools:ignore="UnnecessaryRequiredFeature" /> + + + + @@ -53,15 +59,91 @@ tools:ignore="MissingClass" tools:node="remove" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/data/AmbientMonitor.kt b/wear/src/main/java/to/bitkit/wear/data/AmbientMonitor.kt new file mode 100644 index 0000000000..b8d1314031 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/AmbientMonitor.kt @@ -0,0 +1,20 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Whether the watch shows the app dimmed in ambient (always-on) mode, where nobody is taken to be looking. The + * activity reports it, so what runs outside the screens can tell ambient mode from the app in use. + */ +@Singleton +class AmbientMonitor @Inject constructor() { + private val _isAmbient = MutableStateFlow(false) + val isAmbient: StateFlow = _isAmbient.asStateFlow() + + fun set(isAmbient: Boolean) = _isAmbient.update { isAmbient } +} diff --git a/wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt b/wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt new file mode 100644 index 0000000000..6f6c5d88b7 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt @@ -0,0 +1,9 @@ +package to.bitkit.wear.data + +/** + * The time since the watch booted, in milliseconds. Unlike the wall clock it cannot be set, and unlike + * `System.nanoTime` it keeps counting while the watch sleeps, so it measures how old something is. + */ +fun interface ElapsedClock { + fun nowMs(): Long +} diff --git a/wear/src/main/java/to/bitkit/wear/data/NfcMonitor.kt b/wear/src/main/java/to/bitkit/wear/data/NfcMonitor.kt index 8c69e286f5..c513f76d49 100644 --- a/wear/src/main/java/to/bitkit/wear/data/NfcMonitor.kt +++ b/wear/src/main/java/to/bitkit/wear/data/NfcMonitor.kt @@ -1,10 +1,13 @@ package to.bitkit.wear.data import android.content.BroadcastReceiver +import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.IntentFilter +import android.content.pm.PackageManager import android.nfc.NfcAdapter +import android.nfc.cardemulation.CardEmulation import androidx.core.content.ContextCompat import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher @@ -17,6 +20,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.ext.nfcAdapter +import to.bitkit.wear.nfc.NdefTagService import to.bitkit.wear.utils.Logger import javax.inject.Inject import javax.inject.Singleton @@ -30,6 +34,12 @@ enum class NfcState { Unknown, Unavailable, Off, On } /** The watch's NFC state, updated as NFC is turned on or off. */ interface NfcMonitor { val state: StateFlow + + /** + * Whether the watch can act as an NFC tag (host card emulation); false until it was read and a tag route that an + * earlier process left behind was taken away. + */ + val hasCardEmulation: StateFlow } /** @@ -51,11 +61,19 @@ class AdapterNfcMonitor @Inject constructor( override val state: StateFlow = _state.asStateFlow() + private val _hasCardEmulation = MutableStateFlow(false) + override val hasCardEmulation: StateFlow = _hasCardEmulation.asStateFlow() + init { scope.launch { runCatching { refresh() if (adapter == null) return@runCatching + val hasCardEmulation = + context.packageManager.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION) + // Before the flag lets any screen offer a tag, so this never takes away a route just opened. + if (hasCardEmulation) removeStaleTagRoute() + _hasCardEmulation.update { hasCardEmulation } val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { scope.launch { refresh() } @@ -74,6 +92,18 @@ class AdapterNfcMonitor @Inject constructor( } } + /** + * Takes the tag application id away from [NdefTagService] when an earlier process left it registered: Android + * keeps a runtime registration when the app is killed while it offers a tag. + */ + private fun removeStaleTagRoute() { + val adapter = adapter ?: return + runCatching { + CardEmulation.getInstance(adapter) + .removeAidsForService(ComponentName(context, NdefTagService::class.java), CardEmulation.CATEGORY_OTHER) + }.onFailure { Logger.warn("Failed to remove a stale NFC tag application id", it, context = TAG) } + } + private fun refresh() = _state.update { read() } private fun read(): NfcState { 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..9a85e98806 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt @@ -0,0 +1,76 @@ +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) + + /** 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 +} + +/** + * [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 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() + } + + 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/data/QuickPaySpendStore.kt b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt new file mode 100644 index 0000000000..959a3771fd --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt @@ -0,0 +1,54 @@ +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.longPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import javax.inject.Inject +import javax.inject.Singleton + +/** What the watch's QuickPay payments added up to today, in US cents, for the daily limit. */ +interface QuickPaySpendStore { + /** + * Adds [cents] to the spend of [dayKey], an ISO date, unless that takes the day above [capCents]. Returns the day + * it was added to, or null when it was not. A day earlier than the one last counted does not start a new count: + * the payment is added to the day last counted, so setting the watch's date back frees nothing. + */ + suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? + + /** Takes [cents] out of the spend of [dayKey] again, when that is still the day counted. */ + suspend fun release(dayKey: String, cents: Long) +} + +/** [QuickPaySpendStore] in the watch's settings file, so the wallet's wipe clears it with the settings. */ +@Singleton +class SettingsQuickPaySpendStore @Inject constructor( + private val dataStore: DataStore, +) : QuickPaySpendStore { + private val dayKey = stringPreferencesKey("quickpay_spend_day") + private val centsKey = longPreferencesKey("quickpay_spend_cents") + + override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? { + if (cents <= 0 || capCents <= 0) return null + var reservedDay: String? = null + dataStore.edit { prefs -> + val countedDay = prefs[this.dayKey] + val day = if (countedDay == null || dayKey > countedDay) dayKey else countedDay + val spent = if (day == countedDay) prefs[centsKey] ?: 0L else 0L + if (spent < 0 || cents > capCents - spent) return@edit + prefs[this.dayKey] = day + prefs[centsKey] = spent + cents + reservedDay = day + } + return reservedDay + } + + override suspend fun release(dayKey: String, cents: Long) { + if (cents <= 0) return + dataStore.edit { prefs -> + if (prefs[this.dayKey] != dayKey) return@edit + prefs[centsKey] = ((prefs[centsKey] ?: 0L) - cents).coerceAtLeast(0L) + } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/data/SendMonitor.kt b/wear/src/main/java/to/bitkit/wear/data/SendMonitor.kt new file mode 100644 index 0000000000..ce831bd060 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/SendMonitor.kt @@ -0,0 +1,85 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Whether a send is under way anywhere in the process. A send outlives the screen that started it, so what must not + * interrupt one, such as a payment link or a tapped tag, asks here and not the screen. + */ +@Singleton +class SendMonitor @Inject constructor() { + private var sends = 0 + private val _isSending = MutableStateFlow(false) + val isSending: StateFlow = _isSending.asStateFlow() + + private val _isSyncing = MutableStateFlow(false) + + /** Whether the running send waits for the sync with Spark that comes before it goes out. */ + val isSyncing: StateFlow = _isSyncing.asStateFlow() + + private var settling = 0 + private val _isSettling = MutableStateFlow(false) + + /** + * Whether a payment sent from this watch is still settling and within the time the connection is held for it: + * while it is, the app leaving the screen does not disconnect Spark. + */ + val isSettling: StateFlow = _isSettling.asStateFlow() + + private var outcomeHolds = 0 + private val _isOutcomeHeld = MutableStateFlow(false) + + /** + * Whether a screen is up that the outcome of an earlier payment must not cover: a send flow that is past its + * start, with its amount, review or result, or the receive QR a payer is scanning. + */ + val isOutcomeHeld: StateFlow = _isOutcomeHeld.asStateFlow() + + /** Counts a send that starts now; [end] takes it out again. */ + @Synchronized + fun begin() { + sends++ + _isSending.value = true + } + + @Synchronized + fun end() { + sends = (sends - 1).coerceAtLeast(0) + _isSending.value = sends > 0 + } + + /** Says whether the running send is still syncing with Spark before anything goes out: the wait on the network. */ + fun setSyncing(isSyncing: Boolean) { + _isSyncing.value = isSyncing + } + + /** Counts a payment Spark took from this watch that has not settled; [releaseSettling] takes it out again. */ + @Synchronized + fun holdSettling() { + settling++ + _isSettling.value = true + } + + @Synchronized + fun releaseSettling() { + settling = (settling - 1).coerceAtLeast(0) + _isSettling.value = settling > 0 + } + + /** Counts a screen an outcome must not cover, which is up now; [releaseOutcomes] takes it out again. */ + @Synchronized + fun holdOutcomes() { + outcomeHolds++ + _isOutcomeHeld.value = true + } + + @Synchronized + fun releaseOutcomes() { + outcomeHolds = (outcomeHolds - 1).coerceAtLeast(0) + _isOutcomeHeld.value = outcomeHolds > 0 + } +} diff --git a/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt b/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt index 64bd5d18fc..b14363bd5f 100644 --- a/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt @@ -2,17 +2,23 @@ package to.bitkit.wear.data import androidx.datastore.core.DataStore import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import androidx.datastore.preferences.core.MutablePreferences import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.QuickPayLimits import to.bitkit.wear.models.USD import java.io.File import javax.inject.Inject @@ -29,7 +35,10 @@ fun settingsDataStore(scope: CoroutineScope, produceFile: () -> File): DataStore produceFile = produceFile, ) -/** The watch's display preferences and the wallet wipe's progress notes. It holds nothing secret. */ +/** + * The watch's display preferences, what it imported from the phone's settings, and the wallet wipe's progress notes. + * It holds nothing secret. + */ @Singleton class SettingsStore @Inject constructor( private val dataStore: DataStore, @@ -38,6 +47,12 @@ class SettingsStore @Inject constructor( private val primaryDisplayKey = stringPreferencesKey("primary_display") private val selectedCurrencyKey = stringPreferencesKey("selected_currency") private val removedNoticeKey = booleanPreferencesKey("wallet_removed_notice") + private val displayUnitKey = stringPreferencesKey("display_unit") + private val phonePrimaryDisplayKey = stringPreferencesKey("phone_primary_display") + private val quickPayEnabledKey = booleanPreferencesKey("quickpay_enabled") + private val quickPayAmountKey = intPreferencesKey("quickpay_amount_usd") + private val quickPayMultiplierKey = intPreferencesKey("quickpay_daily_multiplier") + private val phoneSyncedAtKey = longPreferencesKey("phone_settings_synced_at") val data: Flow = dataStore.data.map { prefs -> WatchSettings( @@ -45,9 +60,72 @@ class SettingsStore @Inject constructor( ?.let { runCatching { PrimaryDisplay.valueOf(it) }.getOrNull() } ?: PrimaryDisplay.BITCOIN, selectedCurrency = prefs[selectedCurrencyKey] ?: USD, + displayUnit = prefs[displayUnitKey] + ?.let { runCatching { BitcoinDisplayUnit.valueOf(it) }.getOrNull() } + ?: BitcoinDisplayUnit.MODERN, + quickPay = quickPay(prefs), + phoneSyncedAtMs = prefs[phoneSyncedAtKey], ) } + private fun quickPay(prefs: Preferences): QuickPayLimits? { + val amountUsd = prefs[quickPayAmountKey] ?: return null + val multiplier = prefs[quickPayMultiplierKey] ?: return null + return QuickPayLimits(prefs[quickPayEnabledKey] == true, amountUsd, multiplier) + } + + /** + * Adopts [settings], read from the phone's backup at [syncedAtMs]. A display value the backup does not hold + * keeps the watch's. The phone's primary display is adopted when it differs from the one last imported, so the + * wearer's own swap on the balance lasts until the phone's setting changes. QuickPay is replaced as a whole and + * is off when the backup's values cannot be read. + */ + suspend fun applyPhoneSettings(settings: PhoneSettings, syncedAtMs: Long) { + dataStore.edit { prefs -> + settings.primaryDisplay?.let { + if (prefs[phonePrimaryDisplayKey] != it.name) prefs[primaryDisplayKey] = it.name + prefs[phonePrimaryDisplayKey] = it.name + } + settings.displayUnit?.let { prefs[displayUnitKey] = it.name } + settings.selectedCurrency?.let { prefs[selectedCurrencyKey] = it } + val quickPay = settings.quickPay + if (quickPay == null) { + prefs.clearQuickPay() + } else { + prefs[quickPayEnabledKey] = quickPay.isEnabled + prefs[quickPayAmountKey] = quickPay.amountUsd + prefs[quickPayMultiplierKey] = quickPay.dailyMultiplier + } + prefs[phoneSyncedAtKey] = syncedAtMs + } + } + + /** + * Turns QuickPay off and forgets when the phone's settings were last read, as when the phone's backup is missing + * or cannot be read. The display values stay. + */ + suspend fun clearQuickPay() { + dataStore.edit { prefs -> + prefs.clearQuickPay() + prefs.remove(phoneSyncedAtKey) + } + } + + private fun MutablePreferences.clearQuickPay() { + remove(quickPayEnabledKey) + remove(quickPayAmountKey) + remove(quickPayMultiplierKey) + } + + /** Forgets everything imported from the phone, back to the watch's defaults: an import that a wipe overtook. */ + suspend fun clearPhoneSettings() { + dataStore.edit { prefs -> + prefs.clearQuickPay() + listOf(phoneSyncedAtKey, phonePrimaryDisplayKey, primaryDisplayKey, displayUnitKey, selectedCurrencyKey) + .forEach { prefs.remove(it) } + } + } + suspend fun setPrimaryDisplay(display: PrimaryDisplay) { dataStore.edit { it[primaryDisplayKey] = display.name } } @@ -82,7 +160,14 @@ class SettingsStore @Inject constructor( } } +/** + * [quickPay] is the phone's QuickPay as last imported, or null when none was. [phoneSyncedAtMs] is when the phone's + * settings were last read, in epoch milliseconds, or null when they never were or the last read found none. + */ data class WatchSettings( val primaryDisplay: PrimaryDisplay = PrimaryDisplay.BITCOIN, val selectedCurrency: String = USD, + val displayUnit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN, + val quickPay: QuickPayLimits? = null, + val phoneSyncedAtMs: Long? = null, ) 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..fe56518f6a --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt @@ -0,0 +1,236 @@ +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. [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 sparkPayee: String? = null, + val expiresAtSecs: ULong? = null, +) + +/** + * A payment this watch told the wearer was pending or of unknown outcome, under the [id] Spark lists it by, which is + * the idempotency key it went out under. [quickPayDay] and [quickPayCents] are what QuickPay counted for it against + * that day's limit, when it went out under QuickPay. [outcome] is set once Spark showed how it ended, and the send + * stays remembered with it until the wearer was shown. + */ +data class WatchedSend( + val id: String, + val quickPayDay: String? = null, + val quickPayCents: Long = 0, + val outcome: WatchedOutcome? = null, +) + +/** How a watched payment ended: sent ([isSent]) or failed, with the amount Spark lists for it. */ +data class WatchedOutcome( + val isSent: Boolean, + val amountSats: ULong, +) + +/** + * 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 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 + + /** + * Remembers [send], whose outcome the wearer was not told, so they are told once Spark lists it. A send already + * remembered under the same id is replaced. + */ + suspend fun watch(send: WatchedSend) + + /** The remembered sends whose outcome the wearer was not told yet, the newest first. */ + suspend fun watched(): List + + /** + * Notes that the send with [id] ended in [outcome], which the wearer is still to be shown. Returns whether it was + * remembered with no outcome yet, so one payment's end is acted on once. + */ + suspend fun resolve(id: String, outcome: WatchedOutcome): Boolean + + /** Forgets the send with [id], whose outcome was shown. Returns whether it was remembered. */ + suspend fun unwatch(id: String): Boolean +} + +/** + * [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. Of the sends + * whose outcome the wearer waits to be told, the newest [MAX_WATCHED] are kept, each for [WATCHED_KEPT_SECS], also + * across the time between Spark showing the outcome and the wearer being shown it. + */ +@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 + + /** How many sends whose outcome the wearer was not told are remembered. */ + const val MAX_WATCHED = 20 + + /** How long a send whose outcome the wearer was not told is remembered, in seconds: 30 days. */ + const val WATCHED_KEPT_SECS = 2_592_000uL + private const val SEPARATOR = '|' + private const val FIELDS = 4 + private const val WATCHED_FIELDS = 6 + private const val SENT = "sent" + private const val FAILED = "failed" + 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") + private val watchedKey = stringSetPreferencesKey("watched_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(sparkPayee = send.sparkPayee?.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 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 } + } + + override suspend fun watch(send: WatchedSend) { + val now = nowSecs() + dataStore.edit { prefs -> + prefs[watchedKey] = decodeWatched(prefs[watchedKey], now) + .filter { it.send.id != send.id } + .plus(WatchedEntry(send, now)) + .sortedByDescending { it.startedAtSecs } + .take(MAX_WATCHED) + .mapTo(HashSet()) { it.encode() } + } + } + + override suspend fun watched(): List = + decodeWatched(dataStore.data.first()[watchedKey], nowSecs()) + .sortedByDescending { it.startedAtSecs } + .map { it.send } + + override suspend fun resolve(id: String, outcome: WatchedOutcome): Boolean { + val now = nowSecs() + var wasUnresolved = false + dataStore.edit { prefs -> + val entries = decodeWatched(prefs[watchedKey], now) + val entry = entries.firstOrNull { it.send.id == id && it.send.outcome == null } ?: return@edit + wasUnresolved = true + prefs[watchedKey] = entries + .filter { it.send.id != id } + .plus(WatchedEntry(entry.send.copy(outcome = outcome), entry.startedAtSecs)) + .mapTo(HashSet()) { it.encode() } + } + return wasUnresolved + } + + override suspend fun unwatch(id: String): Boolean { + var wasWatched = false + dataStore.edit { prefs -> + val entries = prefs[watchedKey].orEmpty() + val kept = entries.filterTo(HashSet()) { it.substringBefore(SEPARATOR) != id } + wasWatched = kept.size != entries.size + if (wasWatched) prefs[watchedKey] = kept + } + return wasWatched + } + + private class WatchedEntry(val send: WatchedSend, val startedAtSecs: ULong) { + fun encode(): String = listOf( + send.id, + send.quickPayDay.orEmpty(), + send.quickPayCents.toString(), + startedAtSecs.toString(), + send.outcome?.let { if (it.isSent) SENT else FAILED }.orEmpty(), + send.outcome?.amountSats?.toString().orEmpty(), + ).joinToString(SEPARATOR.toString()) + } + + private fun decodeWatched(entries: Set?, nowSecs: ULong): List = + entries.orEmpty().mapNotNull { entry -> + val fields = entry.split(SEPARATOR).takeIf { it.size == WATCHED_FIELDS } ?: return@mapNotNull null + val startedAt = fields[3].toULongOrNull() ?: return@mapNotNull null + if (startedAt + WATCHED_KEPT_SECS <= nowSecs) return@mapNotNull null + val day = fields[1].takeIf { it.isNotEmpty() } + val cents = fields[2].toLongOrNull()?.takeIf { day != null } ?: 0L + val outcome = when (fields[4]) { + "" -> null + SENT, FAILED -> WatchedOutcome(fields[4] == SENT, fields[5].toULongOrNull() ?: return@mapNotNull null) + else -> return@mapNotNull null + } + WatchedEntry(WatchedSend(fields[0], day, cents, outcome), startedAt) + } + + private class Entry(val send: UncertainSend, val startedAtSecs: ULong) { + fun encode(): String = listOf( + send.key, + send.sparkPayee.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], + sparkPayee = 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 50569961da..c50325e683 100644 --- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt +++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt @@ -1,6 +1,7 @@ package to.bitkit.wear.di import android.content.Context +import android.os.SystemClock import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile @@ -15,10 +16,17 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import to.bitkit.wear.data.AdapterNfcMonitor import to.bitkit.wear.data.ConnectivityNetworkMonitor +import to.bitkit.wear.data.ElapsedClock 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.QuickPaySpendStore +import to.bitkit.wear.data.SettingsOwnInvoiceStore +import to.bitkit.wear.data.SettingsQuickPaySpendStore +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 @@ -30,6 +38,12 @@ 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.PhoneBackupReader +import to.bitkit.wear.services.SelfSendGuard +import to.bitkit.wear.services.VssPhoneBackupReader +import to.bitkit.wear.services.WalletSelfSendGuard import java.io.File import javax.inject.Singleton @@ -60,6 +74,30 @@ 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 bindUncertainSendStore(store: SettingsUncertainSendStore): UncertainSendStore + + @Binds + @Singleton + abstract fun bindSelfSendGuard(guard: WalletSelfSendGuard): SelfSendGuard + + @Binds + @Singleton + abstract fun bindQuickPaySpendStore(store: SettingsQuickPaySpendStore): QuickPaySpendStore + + @Binds + @Singleton + abstract fun bindPhoneBackupReader(reader: VssPhoneBackupReader): PhoneBackupReader + companion object { private const val SEED_DIR = "seed" private const val SETTINGS_NAME = "settings" @@ -79,6 +117,10 @@ abstract class SecurityModule { deviceLock: DeviceLock, ): SeedStore = KeystoreSeedStore(seedDirectory(context), key, deviceLock, isSoftwareKeyAllowed = Env.isDebug) + @Provides + @Singleton + fun provideElapsedClock(): ElapsedClock = ElapsedClock { SystemClock.elapsedRealtime() } + @Provides @Singleton fun provideWipeMarker(@ApplicationContext context: Context): WipeMarker = WipeMarker(seedDirectory(context)) diff --git a/wear/src/main/java/to/bitkit/wear/env/Env.kt b/wear/src/main/java/to/bitkit/wear/env/Env.kt index 726e391de9..5b85496390 100644 --- a/wear/src/main/java/to/bitkit/wear/env/Env.kt +++ b/wear/src/main/java/to/bitkit/wear/env/Env.kt @@ -47,6 +47,25 @@ internal object Env { WalletNetwork.TESTNET -> null } + /** + * The namespace of [network]'s backups on VSS, the phone's `Env.vssStoreIdPrefix`. This and the two servers + * below must equal the phone's: `phone-backup-contract.json` in the tests holds them, and a test on each side + * compares its own values with that file. + */ + fun vssStoreIdPrefix(network: WalletNetwork = this.network): String = "bitkit_v1_${network.name.lowercase()}" + + /** The phone's backup server. The watch only ever reads from it. */ + fun vssServerUrl(network: WalletNetwork = this.network): String = when (network) { + WalletNetwork.BITCOIN -> "https://api.bitkit.to/vss_rs_auth" + else -> "https://bitkit.stag0.blocktank.to/vss_rs_auth" + } + + /** The LNURL-auth server that signs the watch in to [vssServerUrl], as it does the phone. */ + fun lnurlAuthServerUrl(network: WalletNetwork = this.network): String = when (network) { + WalletNetwork.BITCOIN -> "https://bitkit.to/lnurl_auth/auth" + else -> "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" + } + val btcRatesServer: String get() = when (network) { WalletNetwork.BITCOIN -> "https://api1.blocktank.to/api/fx/rates/btc" diff --git a/wear/src/main/java/to/bitkit/wear/models/Currency.kt b/wear/src/main/java/to/bitkit/wear/models/Currency.kt index 768bf3b1cb..5a6a78b5bf 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Currency.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Currency.kt @@ -12,6 +12,7 @@ import java.util.Locale const val BITCOIN_SYMBOL = "₿" const val SATS_IN_BTC = 100_000_000 const val BTC_SCALE = 8 +const val CLASSIC_DECIMALS = 8 const val SATS_GROUPING_SEPARATOR = ' ' const val FIAT_GROUPING_SEPARATOR = ',' const val DECIMAL_SEPARATOR = '.' @@ -48,6 +49,9 @@ enum class PrimaryDisplay { } } +/** How a bitcoin amount is written: [MODERN] in sats, [CLASSIC] in bitcoin with eight decimals, as on the phone. */ +enum class BitcoinDisplayUnit { MODERN, CLASSIC } + /** [sats] in the currency of [rate], or null when the rate is unusable. */ fun fiatValue(sats: Long, rate: FxRate): BigDecimal? { if (rate.rate <= 0.0) return null @@ -66,6 +70,23 @@ fun Long.formatToModernDisplay(locale: Locale = Locale.getDefault()): String { return formatter.format(this) } +fun Long.formatToClassicDisplay(locale: Locale = Locale.getDefault()): String { + val symbols = DecimalFormatSymbols(locale).apply { + decimalSeparator = DECIMAL_SEPARATOR + } + val formatter = DecimalFormat("0.${"0".repeat(CLASSIC_DECIMALS)}", symbols).apply { + minimumFractionDigits = CLASSIC_DECIMALS + maximumFractionDigits = CLASSIC_DECIMALS + isGroupingUsed = false + } + return formatter.format(BigDecimal.valueOf(this).movePointLeft(BTC_SCALE)) +} + +fun Long.formatMoney(unit: BitcoinDisplayUnit, locale: Locale = Locale.getDefault()): String = when (unit) { + BitcoinDisplayUnit.MODERN -> formatToModernDisplay(locale) + BitcoinDisplayUnit.CLASSIC -> formatToClassicDisplay(locale) +} + /** Whether [currencyCode]'s symbol follows the amount, as the phone shows it. */ fun isSymbolSuffix(currencyCode: String): Boolean = currencyCode in SUFFIX_SYMBOL_CURRENCIES 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..a7b7c7ac96 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -0,0 +1,163 @@ +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?, + /** When the invoice expires, in epoch seconds, or null for a Spark address. */ + internal val expiresAtSecs: ULong?, + /** + * 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, + /** + * Whether the request fixes the amount, the only kind of send QuickPay covers: a BOLT11 invoice that carries its + * amount, or an LNURL or a Lightning address whose smallest and largest amount are the same, as on the phone. An + * amount the wearer typed is never fixed, and neither is a Spark address payment. + */ + internal val isAmountFixed: Boolean = false, +) { + 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], [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. */ + 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, 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, or Spark + * has not returned the watch's own call of it yet. [paymentId] and [amountSats] are those of the payment Spark + * lists, when it lists one. + */ + class InFlight(val paymentId: String? = null, val amountSats: ULong? = null) : + SendError("A payment of this request is under way") + + /** + * 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") + + /** Spark refused or failed the payment. [paymentId] is the id Spark lists the failed payment under, if any. */ + class Failed(cause: Throwable? = null, val paymentId: String? = 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. 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. [paymentId] is the id Spark lists the payment under if it + * went out. + */ + class Unknown(cause: Throwable? = null, val paymentId: String? = 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/models/PhoneSettings.kt b/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt new file mode 100644 index 0000000000..1f24a57271 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt @@ -0,0 +1,115 @@ +package to.bitkit.wear.models + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.intOrNull +import to.bitkit.wear.utils.AppError + +/** + * The phone's QuickPay settings: payments of up to [amountUsd] US dollars skip the confirmation, up to + * [amountUsd] times [dailyMultiplier] dollars a day. + */ +data class QuickPayLimits( + val isEnabled: Boolean, + val amountUsd: Int, + val dailyMultiplier: Int, +) { + val thresholdCents: Long get() = amountUsd * CENTS_PER_USD + val dailyCapCents: Long get() = thresholdCents * dailyMultiplier + + companion object { + private const val CENTS_PER_USD = 100L + + /** The largest values the phone's QuickPay sliders offer; a backup with more is not the phone's. */ + const val MAX_AMOUNT_USD = 50 + const val MAX_DAILY_MULTIPLIER = 50 + } +} + +/** + * What the watch adopts from the phone's settings backup. A display value is null when the backup does not hold a + * readable one, and the watch then keeps its own. [quickPay] is null when its values cannot all be read, which turns + * QuickPay off on the watch. + */ +data class PhoneSettings( + val primaryDisplay: PrimaryDisplay?, + val displayUnit: BitcoinDisplayUnit?, + val selectedCurrency: String?, + val quickPay: QuickPayLimits?, +) + +sealed class PhoneSettingsError(message: String, cause: Throwable? = null) : AppError(message, cause) { + /** The backup is not the JSON envelope the phone writes. */ + class Unreadable(cause: Throwable? = null) : PhoneSettingsError("The settings backup cannot be read", cause) + + /** The backup was written in a layout newer than this app knows. */ + class NewerSchema(version: Int) : PhoneSettingsError("The settings backup has version '$version'") +} + +/** + * Reads the phone's `BackupCategory.SETTINGS` envelope (`SettingsBackupV1`: `version`, `createdAt`, `settings`), as + * bitkit-android and bitkit-ios write it. Only the keys the watch adopts are read; every other key is ignored. + */ +object PhoneSettingsParser { + /** The newest envelope version this reader knows. */ + const val SCHEMA_VERSION = 1 + + /** A settings envelope is a few kilobytes; anything larger than this is not one. */ + const val MAX_BYTES = 256 * 1024 + + private val json = Json { isLenient = true } + + /** Fails with a [PhoneSettingsError]. */ + fun parse(bytes: ByteArray): PhoneSettings { + if (bytes.size > MAX_BYTES) throw PhoneSettingsError.Unreadable() + val root = runCatching { json.parseToJsonElement(bytes.decodeToString()) as JsonObject } + .getOrElse { throw PhoneSettingsError.Unreadable(it) } + val version = when (val element = root["version"]) { + null -> SCHEMA_VERSION + else -> (element as? JsonPrimitive)?.intOrNull ?: throw PhoneSettingsError.Unreadable() + } + if (version > SCHEMA_VERSION) throw PhoneSettingsError.NewerSchema(version) + if (version < 1) throw PhoneSettingsError.Unreadable() + val settings = root["settings"] as? JsonObject ?: throw PhoneSettingsError.Unreadable() + return PhoneSettings( + primaryDisplay = settings["primaryDisplay"].enumOrNull(), + displayUnit = settings["displayUnit"].enumOrNull(), + selectedCurrency = settings["selectedCurrency"].stringOrNull()?.takeIf { CURRENCY_CODE.matches(it) }, + quickPay = quickPay(settings), + ) + } + + private fun quickPay(settings: JsonObject): QuickPayLimits? { + val isEnabled = (settings["isQuickPayEnabled"] as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull + val amountUsd = settings["quickPayAmount"].intOrNull() + val multiplier = settings["quickPayDailyLimitMultiplier"].intOrNull() + if (isEnabled == null || amountUsd == null || multiplier == null) return null + if (amountUsd !in 1..QuickPayLimits.MAX_AMOUNT_USD) return null + if (multiplier !in 1..QuickPayLimits.MAX_DAILY_MULTIPLIER) return null + return QuickPayLimits(isEnabled, amountUsd, multiplier) + } + + private fun JsonElement?.intOrNull(): Int? = (this as? JsonPrimitive)?.takeIf { !it.isString }?.intOrNull + + private fun JsonElement?.stringOrNull(): String? = (this as? JsonPrimitive)?.takeIf { it.isString }?.content + + /** + * An enum as kotlinx writes it, a string, or as Swift's `Codable` does, an object with the case as its one key. + * Names match without their case and underscores, as in the phone's reader. + */ + private inline fun > JsonElement?.enumOrNull(): T? { + val name = when (this) { + is JsonPrimitive -> stringOrNull() + is JsonObject -> keys.singleOrNull() + else -> null + } ?: return null + return enumValues().firstOrNull { it.name.normalized() == name.normalized() } + } + + private fun String.normalized() = filter { it != '_' }.lowercase() + + private val CURRENCY_CODE = Regex("^[A-Z]{3}$") +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/CardEmulationTagRoute.kt b/wear/src/main/java/to/bitkit/wear/nfc/CardEmulationTagRoute.kt new file mode 100644 index 0000000000..95c2bc32d8 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/CardEmulationTagRoute.kt @@ -0,0 +1,49 @@ +package to.bitkit.wear.nfc + +import android.app.Activity +import android.content.ComponentName +import android.nfc.NfcAdapter +import android.nfc.cardemulation.CardEmulation +import to.bitkit.wear.utils.Logger + +/** + * Routes the NDEF tag application to [NdefTagService] while [activity] is resumed, as the phone's `NfcEmitterEffect` + * does: the application id is registered for the service only meanwhile, and the service is made the preferred + * one, so Bitkit answers no reader elsewhere and another app with the same application id does not answer instead. + */ +internal class CardEmulationTagRoute(private val activity: Activity) : TagRoute { + companion object { + private const val TAG = "CardEmulationTagRoute" + private val NDEF_AIDS = listOf(Type4TagEmulator.NDEF_AID_HEX) + } + + private val service = ComponentName(activity, NdefTagService::class.java) + private val cardEmulation: CardEmulation? by lazy { + runCatching { NfcAdapter.getDefaultAdapter(activity)?.let(CardEmulation::getInstance) } + .onFailure { Logger.warn("Failed to reach card emulation", it, context = TAG) } + .getOrNull() + } + + /** Whether both the route and the preference were set: without the preference the route is taken back. */ + override fun open(): Boolean { + val cardEmulation = cardEmulation ?: return false + return runCatching { + val isRegistered = cardEmulation.registerAidsForService(service, CardEmulation.CATEGORY_OTHER, NDEF_AIDS) + if (!isRegistered) return@runCatching false + if (cardEmulation.setPreferredService(activity, service)) return@runCatching true + cardEmulation.removeAidsForService(service, CardEmulation.CATEGORY_OTHER) + false + }.onFailure { Logger.warn("Failed to register NFC tag service", it, context = TAG) } + .onSuccess { if (!it) Logger.warn("NFC tag service registration was refused", context = TAG) } + .getOrDefault(false) + } + + /** Each step by itself: the preference can only be unset while resumed, and the id must go either way. */ + override fun close() { + val cardEmulation = cardEmulation ?: return + runCatching { cardEmulation.unsetPreferredService(activity) } + .onFailure { Logger.warn("Failed to unset the preferred NFC tag service", it, context = TAG) } + runCatching { cardEmulation.removeAidsForService(service, CardEmulation.CATEGORY_OTHER) } + .onFailure { Logger.warn("Failed to remove the NFC tag application id", it, context = TAG) } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NdefCodec.kt b/wear/src/main/java/to/bitkit/wear/nfc/NdefCodec.kt new file mode 100644 index 0000000000..4da05ba0ce --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NdefCodec.kt @@ -0,0 +1,117 @@ +// Copied from app/src/main/java/to/bitkit/nfc/NdefCodec.kt; keep both in sync. +package to.bitkit.wear.nfc + +import java.nio.ByteBuffer + +/** + * Encodes and decodes the NDEF records used for NFC payments. + * + * Bitkit writes one NFC Forum well-known URI record ("U") holding the payment request. + * When reading, it accepts URI records, Text records ("T", used by Numo and some POS apps) + * and absolute-URI records, so a tag from any payment terminal or wallet lands in the same + * scan flow as a QR code. + */ +object NdefCodec { + private const val FLAG_MB = 0x80 + private const val FLAG_ME = 0x40 + private const val FLAG_CF = 0x20 + private const val FLAG_SR = 0x10 + private const val FLAG_IL = 0x08 + private const val TNF_MASK = 0x07 + private const val TNF_WELL_KNOWN = 0x01 + private const val TNF_ABSOLUTE_URI = 0x03 + private const val TEXT_UTF16 = 0x80 + private const val TEXT_LANG_LENGTH_MASK = 0x3F + private const val SHORT_RECORD_MAX = 255 + private val TYPE_URI = byteArrayOf('U'.code.toByte()) + private val TYPE_TEXT = byteArrayOf('T'.code.toByte()) + + /** URI identifier codes, NFC Forum URI Record Type Definition, table 3. */ + private val URI_PREFIXES = listOf( + "", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", + "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", + "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", + "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", + "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:", + ) + + /** One NDEF message with a single URI record, written without an abbreviation prefix. */ + fun encodeUriMessage(uri: String): ByteArray { + val payload = byteArrayOf(0x00) + uri.toByteArray(Charsets.UTF_8) + val isShort = payload.size <= SHORT_RECORD_MAX + val header = FLAG_MB or FLAG_ME or TNF_WELL_KNOWN or (if (isShort) FLAG_SR else 0) + val lengthBytes = if (isShort) { + byteArrayOf(payload.size.toByte()) + } else { + ByteBuffer.allocate(Int.SIZE_BYTES).putInt(payload.size).array() + } + return byteArrayOf(header.toByte(), TYPE_URI.size.toByte()) + lengthBytes + TYPE_URI + payload + } + + /** + * Returns the text of every URI, Text or absolute-URI record in [message]. + * Other record types are skipped. A malformed or chunked message yields an empty list. + */ + fun decodeTexts(message: ByteArray): List = runCatching { parse(message) }.getOrDefault(emptyList()) + + /** + * Picks the payment request from the decoded record texts: the single distinct non-blank + * value, or null when the tag holds nothing or several different requests. + */ + fun payableText(texts: List): String? { + val distinct = texts.map { it.trim() }.filter { it.isNotEmpty() }.distinct() + return distinct.singleOrNull() + } + + private fun parse(message: ByteArray): List { + val texts = mutableListOf() + var offset = 0 + while (offset < message.size) { + val header = message[offset].toInt() and 0xFF + require(header and FLAG_CF == 0) { "Chunked records are not supported" } + val typeLength = message[offset + 1].toInt() and 0xFF + offset += 2 + val payloadLength: Int + if (header and FLAG_SR != 0) { + payloadLength = message[offset].toInt() and 0xFF + offset += 1 + } else { + payloadLength = ByteBuffer.wrap(message, offset, Int.SIZE_BYTES).int + offset += Int.SIZE_BYTES + } + require(payloadLength >= 0) { "Invalid payload length" } + val idLength = if (header and FLAG_IL != 0) (message[offset++].toInt() and 0xFF) else 0 + val type = message.copyOfRange(offset, offset + typeLength) + offset += typeLength + idLength + require(offset + payloadLength <= message.size) { "Truncated record" } + val payload = message.copyOfRange(offset, offset + payloadLength) + offset += payloadLength + + recordText(header and TNF_MASK, type, payload)?.let(texts::add) + if (header and FLAG_ME != 0) break + } + return texts + } + + private fun recordText(tnf: Int, type: ByteArray, payload: ByteArray): String? = when { + tnf == TNF_WELL_KNOWN && type.contentEquals(TYPE_URI) -> decodeUri(payload) + tnf == TNF_WELL_KNOWN && type.contentEquals(TYPE_TEXT) -> decodeText(payload) + tnf == TNF_ABSOLUTE_URI -> type.toString(Charsets.UTF_8) + else -> null + } + + private fun decodeUri(payload: ByteArray): String? { + if (payload.isEmpty()) return null + val prefix = URI_PREFIXES.getOrNull(payload[0].toInt() and 0xFF) ?: return null + return prefix + payload.copyOfRange(1, payload.size).toString(Charsets.UTF_8) + } + + private fun decodeText(payload: ByteArray): String? { + if (payload.isEmpty()) return null + val status = payload[0].toInt() and 0xFF + val textStart = 1 + (status and TEXT_LANG_LENGTH_MASK) + if (textStart > payload.size) return null + val charset = if (status and TEXT_UTF16 != 0) Charsets.UTF_16 else Charsets.UTF_8 + return payload.copyOfRange(textStart, payload.size).toString(charset) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NdefTagService.kt b/wear/src/main/java/to/bitkit/wear/nfc/NdefTagService.kt new file mode 100644 index 0000000000..9bfef3c2a7 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NdefTagService.kt @@ -0,0 +1,23 @@ +package to.bitkit.wear.nfc + +import android.nfc.cardemulation.HostApduService +import android.os.Bundle + +/** + * Presents the receive QR's invoice as an NFC Forum Type 4 tag, so a phone or a point of sale reads it like any NDEF + * tag. It answers only while [NfcTagEmitter] holds a request, which the receive QR screen publishes while it shows + * the invoice (see [NfcTagOffer]). The watch's counterpart of the phone's `to.bitkit.androidServices.NdefTagService`, + * with the same tag application and record; keep the two in sync. + */ +class NdefTagService : HostApduService() { + private val emulator = Type4TagEmulator(NfcTagEmitter::currentMessage) + + override fun processCommandApdu(commandApdu: ByteArray?, extras: Bundle?): ByteArray { + val apdu = commandApdu ?: return Type4TagEmulator.SW_WRONG_LENGTH + return emulator.process(apdu) + } + + override fun onDeactivated(reason: Int) { + emulator.reset() + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcPaymentUri.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcPaymentUri.kt new file mode 100644 index 0000000000..d49043cd44 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcPaymentUri.kt @@ -0,0 +1,128 @@ +// Copied from app/src/main/java/to/bitkit/nfc/NfcPaymentUri.kt; keep both in sync. +package to.bitkit.wear.nfc + +import java.math.BigDecimal + +private val URI_SCHEMES = listOf("bitcoin:", "lightning:", "ethereum:", "lnurlp:", "lnurlw:", "lnurlc:") +private val LIGHTNING_PREFIXES = listOf("lnbc", "lntb", "lntbs", "lnbcrt", "lnsb", "lno1", "lnurl") + +/** + * Turns a receive request into the URI written to an NFC tag. + * + * A tag needs a scheme for other wallets (and Android's tag dispatch) to recognise the request, + * so a bare BOLT11 invoice, offer or LNURL gets `lightning:` and a bare address gets `bitcoin:`. + * Requests that already carry a payment scheme are returned unchanged. + */ +fun nfcPaymentUri(request: String?): String? { + val trimmed = request?.trim().orEmpty() + if (trimmed.isEmpty()) return null + val lowercase = trimmed.lowercase() + return when { + URI_SCHEMES.any { lowercase.startsWith(it) } -> trimmed + LIGHTNING_PREFIXES.any { lowercase.startsWith(it) } -> "lightning:$trimmed" + else -> "bitcoin:$trimmed" + } +} + +private const val BITCOIN_WITHOUT_ADDRESS = "bitcoin:?" +private const val REQUIRED_PARAM_PREFIX = "req-" +private const val BITCOIN_SCHEME = "bitcoin:" +private const val DEEPLINK_SCHEME = "bitkit://" +private val DECODER_WRAPPERS = listOf("lightning:", "lnurl:", "lnurlw:", "lnurlc:", "lnurlp:") + +/** + * Keys BIP 321 ("Query Keys", "Invalid URIs") forbids repeating; `pop` and `req-pop` count as the same key. + * Unknown optional keys and payment instructions may repeat. + */ +private val SINGLETON_KEYS = setOf("amount", "label", "message", "pop") + +/** + * Turns a payment request read from a tag or a nearby device into one the scanner decodes. + * + * A BIP 321 URI may leave the address out and carry only a Lightning request + * (`bitcoin:?lightning=`, used by Numo and planned by Square). The scanner rejects a + * `bitcoin:` URI without an address, so that form becomes `lightning:`. A URI with a + * required (`req-`) parameter is kept, since BIP 321 forbids paying it without handling that + * parameter and the rewrite would drop it. So is a URI that repeats one of [SINGLETON_KEYS], which BIP 321 + * makes invalid; one with more than one `lightning` value, which Bitkit does not support, since the rewrite would + * have to pick one; and one whose `amount` the invoice does not carry: the invoice alone could not ask for it. + * Anything else is returned trimmed and unchanged. + */ +fun scannedPaymentRequest(text: String): String { + val trimmed = text.trim() + if (!trimmed.startsWith(BITCOIN_WITHOUT_ADDRESS, ignoreCase = true)) return trimmed + val pairs = trimmed.substring(BITCOIN_WITHOUT_ADDRESS.length).split('&') + // Checked on every key, since BIP 321 allows a required key with an empty or no value. + if (pairs.any { it.substringBefore('=').lowercase().startsWith(REQUIRED_PARAM_PREFIX) }) return trimmed + val keys = pairs.map { it.substringBefore('=').lowercase().removePrefix(REQUIRED_PARAM_PREFIX) } + val singletons = keys.filter { it in SINGLETON_KEYS } + if (singletons.size != singletons.toSet().size) return trimmed + if (keys.count { it == "lightning" } > 1) return trimmed + // An `amount` key with no value is a malformed amount, not a missing one. + val hasEmptyAmount = pairs.any { + it.substringBefore('=').equals("amount", ignoreCase = true) && it.substringAfter('=', "").isEmpty() + } + if (hasEmptyAmount) return trimmed + val params = pairs.mapNotNull { + val key = it.substringBefore('=', missingDelimiterValue = "") + val value = it.substringAfter('=', missingDelimiterValue = "") + if (key.isEmpty() || value.isEmpty()) null else key.lowercase() to value + }.toMap() + // A BOLT12 offer (`lno`) is left as is: the scanner cannot pay one yet. + val request = params["lightning"] ?: return trimmed + val amount = params["amount"] + if (amount != null && !isBolt11Amount(request, amount)) return trimmed + return "lightning:$request" +} + +/** + * Whether [uri] is a `bitcoin:` URI with a required (`req-`) BIP 321 parameter. No Bitkit flow fulfils one, and the + * shipped scanner ignores it on a URI with an address, so a request read from a nearby device or a tag with one is + * refused. Other schemes, such as an LNURL-pay URL, keep their own query untouched. + */ +fun hasRequiredParam(uri: String): Boolean { + // The app and the decoder strip the Lightning wrappers from the front. While the text starts with `bitkit://`, the + // decoder deletes every `bitkit://` in it, which can turn a key into `req-`, and decodes again. Follow the same + // steps and check the `bitcoin:` request the decoder would receive. + var decoded = uri.coreTrim() + while (true) { + val wrapper = DECODER_WRAPPERS.firstOrNull { decoded.startsWith(it, ignoreCase = true) } + decoded = when { + wrapper != null -> decoded.substring(wrapper.length).coreTrim() + decoded.startsWith(DEEPLINK_SCHEME) -> decoded.replace(DEEPLINK_SCHEME, "").coreTrim() + else -> break + } + } + if (!decoded.startsWith(BITCOIN_SCHEME, ignoreCase = true)) return false + return decoded.substringAfter('?', missingDelimiterValue = "") + .split('&') + .any { it.substringBefore('=').lowercase().startsWith(REQUIRED_PARAM_PREFIX) } +} + +/** Trims like the decoder's Rust `trim()`, which also removes U+0085 (NEL) that Kotlin's `trim()` keeps. */ +private fun String.coreTrim() = trim { it.isWhitespace() || it == '\u0085' } + +/** The request to hand to the scanner for [text] read from an NFC tag, or null when it is refused. */ +fun nfcPaymentRequest(text: String): String? = scannedPaymentRequest(text).takeUnless(::hasRequiredParam) + +/** BIP 321 amount syntax: decimal BTC, with no sign, exponent or unit. */ +private val BIP321_AMOUNT = Regex("^(\\d+(\\.\\d*)?|\\.\\d+)$") +private val BOLT11_HRP = Regex("^ln[a-z]+?(\\d+)([munp]?)$") +private val BTC_PER_UNIT = mapOf( + "" to BigDecimal.ONE, + "m" to BigDecimal("0.001"), + "u" to BigDecimal("0.000001"), + "n" to BigDecimal("0.000000001"), + "p" to BigDecimal("0.000000000001"), +) + +/** Whether [invoice] is a BOLT11 invoice for exactly [amountBtc], read from its human-readable part. */ +private fun isBolt11Amount(invoice: String, amountBtc: String): Boolean { + val hrp = invoice.lowercase().substringBeforeLast('1', missingDelimiterValue = "") + val match = BOLT11_HRP.matchEntire(hrp) ?: return false + val (digits, unit) = match.destructured + val invoiceBtc = BigDecimal(digits).multiply(BTC_PER_UNIT.getValue(unit)) + if (!BIP321_AMOUNT.matches(amountBtc)) return false + val requested = amountBtc.toBigDecimal() + return invoiceBtc.compareTo(requested) == 0 +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcRepeatGuard.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcRepeatGuard.kt new file mode 100644 index 0000000000..8aed5fa9cb --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcRepeatGuard.kt @@ -0,0 +1,105 @@ +package to.bitkit.wear.nfc + +import android.app.Activity +import android.nfc.NfcAdapter +import android.nfc.Tag +import android.os.Handler +import android.os.Looper +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import to.bitkit.wear.utils.Logger +import java.lang.ref.WeakReference +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds + +private const val READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A or + NfcAdapter.FLAG_READER_NFC_B or + NfcAdapter.FLAG_READER_NFC_F or + NfcAdapter.FLAG_READER_NFC_V + +/** + * Stops Android from delivering a payment tag again while the watch stays on it after a tap. + * + * Android dispatches every activation of a tag as a new NDEF_DISCOVERED intent, and a phone emulating a tag activates + * again whenever the field drops. The guard holds reader mode with a callback that reads nothing until the tag has + * left the field, then switches reader mode off. Reader mode pauses the watch's own card emulation meanwhile. + * + * A copy of the phone's `to.bitkit.nfc.NfcRepeatGuard` without its hand-over to a scanning screen, which the watch + * does not have, and with [isHeld], which the receive QR reads so it never shows a tag no reader reaches; keep the + * two in sync. + */ +internal object NfcRepeatGuard { + private const val TAG = "NfcRepeatGuard" + + /** How long the guard holds when no tag answers, e.g. after a launch from a tag already removed. */ + private val HOLD_WITHOUT_TAG: Duration = 3.seconds + + /** How long a tag must stay out of range before Android may deliver it again. */ + private val REMOVAL_DEBOUNCE: Duration = 1.seconds + + /** Covers the gap while an emulating phone re-activates its tag after a removal is reported. */ + private val RELEASE_AFTER_REMOVAL: Duration = 500.milliseconds + + private val handler by lazy { Handler(Looper.getMainLooper()) } + private val release = Runnable { release() } + private var activity = WeakReference(null) + + private val _isHeld = MutableStateFlow(false) + + /** Whether reader mode is held right now, which pauses the watch's own card emulation: no reader reaches it. */ + val isHeld: StateFlow = _isHeld.asStateFlow() + + /** Holds reader mode on [activity], which must be resumed. Pass the [tag] just read so its removal ends it. */ + fun engage(activity: Activity, tag: Tag? = null) { + if (Looper.myLooper() != Looper.getMainLooper()) { + handler.post { engage(activity, tag) } + return + } + val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return + val enabled = runCatching { + adapter.enableReaderMode(activity, { onTag(adapter, it) }, READER_FLAGS, null) + }.onFailure { Logger.warn("Failed to hold NFC reader mode", it, context = TAG) }.isSuccess + if (!enabled) return + this.activity = WeakReference(activity) + _isHeld.value = true + schedule(HOLD_WITHOUT_TAG) + tag?.let { onTag(adapter, it) } + } + + private fun onTag(adapter: NfcAdapter, tag: Tag) { + handler.post { handler.removeCallbacks(release) } + val ignored = runCatching { + adapter.ignore( + tag, + REMOVAL_DEBOUNCE.inWholeMilliseconds.toInt(), + { schedule(RELEASE_AFTER_REMOVAL) }, + handler, + ) + }.getOrDefault(false) + if (!ignored) schedule(HOLD_WITHOUT_TAG) + } + + private fun schedule(delay: Duration) { + handler.post { + handler.removeCallbacks(release) + handler.postDelayed(release, delay.inWholeMilliseconds) + } + } + + /** Ends the hold of [activity] as it goes away, so a hold never outlives the activity that reader mode ran on. */ + fun disengage(activity: Activity) { + if (this.activity.get() !== activity) return + handler.removeCallbacks(release) + release() + } + + private fun release() { + _isHeld.value = false + val activity = activity.get() ?: return + this.activity = WeakReference(null) + runCatching { NfcAdapter.getDefaultAdapter(activity)?.disableReaderMode(activity) } + .onFailure { Logger.warn("Failed to release NFC reader mode", it, context = TAG) } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcTagEmitter.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagEmitter.kt new file mode 100644 index 0000000000..ede0dad302 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagEmitter.kt @@ -0,0 +1,40 @@ +// Copied from app/src/main/java/to/bitkit/nfc/NfcTagEmitter.kt, with [NfcTagEmitter.revoke] added; keep both in sync. +package to.bitkit.wear.nfc + +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference + +/** + * The payment request this device currently offers over NFC. + * + * The Receive screen publishes its request while it is in the foreground and clears it when it + * leaves, so [NdefTagService] answers a reader only while that request is on screen. + * The service and the UI run in the same process, so a process-wide holder is enough. + */ +object NfcTagEmitter { + private class Published(val token: Long, val message: ByteArray) + + private val tokens = AtomicLong(0) + private val published = AtomicReference(null) + + /** Publishes [uri] and returns the token that [clear] needs, so a later publisher is not cleared. */ + fun publish(uri: String): Long { + val token = tokens.incrementAndGet() + published.set(Published(token, NdefCodec.encodeUriMessage(uri))) + return token + } + + /** Clears the request published with [token]; returns false when another one replaced it. */ + fun clear(token: Long): Boolean { + val current = published.get() ?: return false + return current.token == token && published.compareAndSet(current, null) + } + + /** + * Takes the published request back at once, whoever published it: the moment an invoice of the Receive screen is + * paid, without waiting for the screen to stop the offer. A reader is served nothing more of it. + */ + fun revoke() = published.set(null) + + fun currentMessage(): ByteArray? = published.get()?.message +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcTagOffer.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagOffer.kt new file mode 100644 index 0000000000..f498aac102 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagOffer.kt @@ -0,0 +1,46 @@ +package to.bitkit.wear.nfc + +/** Routes the NDEF tag application to [NdefTagService] and takes the route away again. */ +internal interface TagRoute { + /** Whether readers now reach the service, and no other app's service under the same application id. */ + fun open(): Boolean + + fun close() +} + +/** + * Offers one payment request to NFC readers through [NdefTagService], from [start] until [stop]. The logic of the + * phone's `NfcEmitterEffect` (`to.bitkit.ui.shared.effects.NfcEffects`), apart from the screen so it can be tested: + * the request is published first, and taken back when the route to the service cannot be opened, so the screen + * never says it can be tapped when no reader would reach it. + */ +internal class NfcTagOffer( + private val route: TagRoute, + private val emitter: NfcTagEmitter = NfcTagEmitter, +) { + private var token: Long? = null + + val isOffered: Boolean get() = token != null + + /** Offers [uri], instead of what was offered before. Returns whether a reader can now read it. */ + fun start(uri: String): Boolean { + stop() + val published = emitter.publish(uri) + if (route.open()) { + token = published + return true + } + emitter.clear(published) + return false + } + + /** Stops offering. The request is cleared before the route closes, so a reader mid-tap is served nothing more. */ + fun stop() { + val published = token ?: return + token = null + // Another offer may have published since; it then owns the route too. A request that was revoked left + // nothing published, and its route still closes here. + if (!emitter.clear(published) && emitter.currentMessage() != null) return + route.close() + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcTapFilter.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcTapFilter.kt new file mode 100644 index 0000000000..36d2344efb --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcTapFilter.kt @@ -0,0 +1,39 @@ +package to.bitkit.wear.nfc + +import android.os.SystemClock +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +/** + * Drops the repeats of one tap. Android dispatches every activation of a tag as a new intent, and a phone emulating + * a tag activates again whenever the field drops, so a watch held on it gets the same request again and again. + * [NfcRepeatGuard] stops that where the watch supports reader mode; this filter holds either way: a request equal to + * the last one is dropped until [REPEAT_WINDOW] passed without it. Modelled on the phone's + * `to.bitkit.nfc.NfcReadDispatcher`, whose window counts from the first read; here every repeat extends it, since no + * reader mode callback tells the watch that the tag left. + * + * One filter serves the whole process, so it holds whichever activity instance Android hands a repeat to. + */ +@Singleton +class NfcTapFilter internal constructor(private val nowMs: () -> Long) { + @Inject + constructor() : this(SystemClock::elapsedRealtime) + + private var last: Pair? = null + + /** Whether [request], just read from a tag, is a new tap and not a repeat of the last one. */ + @Synchronized + fun isNew(request: String): Boolean { + val time = nowMs() + val previous = last + last = request to time + if (previous == null || previous.first != request) return true + return time - previous.second >= REPEAT_WINDOW.inWholeMilliseconds + } + + companion object { + val REPEAT_WINDOW: Duration = 3.seconds + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/Type4TagEmulator.kt b/wear/src/main/java/to/bitkit/wear/nfc/Type4TagEmulator.kt new file mode 100644 index 0000000000..9510b75af2 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/Type4TagEmulator.kt @@ -0,0 +1,129 @@ +// Copied from app/src/main/java/to/bitkit/nfc/Type4TagEmulator.kt; keep both in sync. +package to.bitkit.wear.nfc + +/** + * Read-only NFC Forum Type 4 tag, served over host card emulation. + * + * A reader selects the NDEF tag application, reads the capability container (file E103) + * and then the NDEF file (E104), which holds a 2-byte length followed by the message. + * [ndefMessage] is read when the NDEF file is selected, so one tap always sees one + * consistent request. While it returns null the application itself is reported as not found, + * so a reader sees no tag. + */ +class Type4TagEmulator( + private val ndefMessage: () -> ByteArray?, +) { + private var isApplicationSelected = false + private var selectedFile: ByteArray? = null + + fun process(apdu: ByteArray): ByteArray { + if (apdu.size < HEADER_SIZE) return SW_WRONG_LENGTH + if (apdu[0] != CLA) return SW_CLA_NOT_SUPPORTED + return when (apdu[1]) { + INS_SELECT -> select(apdu) + INS_READ_BINARY -> readBinary(apdu) + INS_UPDATE_BINARY -> SW_SECURITY_NOT_SATISFIED + else -> SW_INS_NOT_SUPPORTED + } + } + + fun reset() { + isApplicationSelected = false + selectedFile = null + } + + private fun select(apdu: ByteArray): ByteArray { + val p1 = apdu[2] + val data = commandData(apdu) ?: return SW_WRONG_LENGTH + return when (p1) { + // With nothing published Bitkit does not present a tag at all, so readers cannot detect it. + P1_SELECT_BY_NAME -> if (data.contentEquals(NDEF_AID) && ndefMessage() != null) { + isApplicationSelected = true + selectedFile = null + SW_OK + } else { + reset() + SW_FILE_NOT_FOUND + } + + P1_SELECT_BY_ID -> selectFile(data) + else -> SW_FILE_NOT_FOUND + } + } + + private fun selectFile(fileId: ByteArray): ByteArray { + if (!isApplicationSelected) return SW_FILE_NOT_FOUND + selectedFile = when { + fileId.contentEquals(CC_FILE_ID) -> CAPABILITY_CONTAINER + fileId.contentEquals(NDEF_FILE_ID) -> ndefFile() + else -> null + } + return if (selectedFile != null) SW_OK else SW_FILE_NOT_FOUND + } + + private fun ndefFile(): ByteArray? { + val message = ndefMessage() ?: return null + if (message.size > MAX_NDEF_SIZE) return null + val length = byteArrayOf((message.size shr 8).toByte(), message.size.toByte()) + return length + message + } + + private fun readBinary(apdu: ByteArray): ByteArray { + val file = selectedFile ?: return SW_FILE_NOT_FOUND + // The selected copy keeps one tap consistent, but once Receive stops offering, nothing more is served. + if (ndefMessage() == null) { + reset() + return SW_FILE_NOT_FOUND + } + val offset = ((apdu[2].toInt() and 0xFF) shl 8) or (apdu[3].toInt() and 0xFF) + if (offset > file.size) return SW_WRONG_OFFSET + val requested = if (apdu.size > HEADER_SIZE) apdu[HEADER_SIZE].toInt() and 0xFF else 0 + val length = if (requested == 0) SHORT_LE_MAX else requested + val end = minOf(file.size, offset + length) + return file.copyOfRange(offset, end) + SW_OK + } + + private fun commandData(apdu: ByteArray): ByteArray? { + if (apdu.size <= HEADER_SIZE) return null + val lc = apdu[HEADER_SIZE].toInt() and 0xFF + val start = HEADER_SIZE + 1 + if (apdu.size < start + lc) return null + return apdu.copyOfRange(start, start + lc) + } + + companion object { + /** NDEF Tag Application, NFC Forum Type 4 Tag specification. */ + val NDEF_AID = byteArrayOf(0xD2.toByte(), 0x76, 0x00, 0x00, 0x85.toByte(), 0x01, 0x01) + const val NDEF_AID_HEX = "D2760000850101" + const val MAX_NDEF_SIZE = 0x0FFE + + private const val HEADER_SIZE = 4 + private const val SHORT_LE_MAX = 256 + private const val CLA: Byte = 0x00 + private const val INS_SELECT: Byte = 0xA4.toByte() + private const val INS_READ_BINARY: Byte = 0xB0.toByte() + private const val INS_UPDATE_BINARY: Byte = 0xD6.toByte() + private const val P1_SELECT_BY_NAME: Byte = 0x04 + private const val P1_SELECT_BY_ID: Byte = 0x00 + + private val CC_FILE_ID = byteArrayOf(0xE1.toByte(), 0x03) + private val NDEF_FILE_ID = byteArrayOf(0xE1.toByte(), 0x04) + + /** + * Mapping version 2.0, MLe 0x003B, MLc 0x0034, then the NDEF file control TLV: + * file E104, maximum size [MAX_NDEF_SIZE] + 2, read access granted, write access denied. + */ + private val CAPABILITY_CONTAINER = byteArrayOf( + 0x00, 0x0F, 0x20, 0x00, 0x3B, 0x00, 0x34, + 0x04, 0x06, 0xE1.toByte(), 0x04, 0x10, 0x00, 0x00, 0xFF.toByte(), + ) + + val SW_OK = byteArrayOf(0x90.toByte(), 0x00) + val SW_FILE_NOT_FOUND = byteArrayOf(0x6A, 0x82.toByte()) + val SW_WRONG_LENGTH = byteArrayOf(0x67, 0x00) + val SW_WRONG_OFFSET = byteArrayOf(0x6B, 0x00) + val SW_SECURITY_NOT_SATISFIED = byteArrayOf(0x69, 0x82.toByte()) + val SW_INS_NOT_SUPPORTED = byteArrayOf(0x6D, 0x00) + val SW_CLA_NOT_SUPPORTED = byteArrayOf(0x6E, 0x00) + } +} 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..d77c4064f1 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -0,0 +1,749 @@ +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.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.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +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.data.SendMonitor +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 +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.SparkError +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.utils.Logger +import java.net.URI +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +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, + private val uncertainSendStore: UncertainSendStore, + private val quickPayRepo: QuickPayRepo, + private val sendMonitor: SendMonitor, + private val sendOutcomeRepo: SendOutcomeRepo, +) { + 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, as the + * phone does. The payment goes on settling after that: [SendOutcomeRepo] follows it. + */ + val SETTLE_TIMEOUT = 10.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 + + 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 + return text.takeIf { SPARK_ADDRESS.matches(it) } + } + } + + private val sendMutex = Mutex() + + /** 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 + + /** 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 { } + + /** What [skipConfirmation] counted against the QuickPay limit, by [PreparedSend.transferKey], until [send] ends. */ + private val quickPayReservations = ConcurrentHashMap() + + /** + * Whether [prepared] goes out without the hold to pay (QuickPay), by the phone's rules. This is the one place + * that decides it. It does only when all of these hold: + * - the wallet is ready; + * - [prepared] came from [prepare], so the self-send guard and every check before the hold passed; + * - its request fixes the amount, as a BOLT11 invoice with an amount, also inside a `bitcoin:` URI, or an LNURL + * or a Lightning address that takes one amount only; an amount the wearer typed is always reviewed, and so is + * a Spark address; + * - [QuickPayRepo.reserve] takes the payment's amount, without its fee, under the phone's QuickPay settings; + * - [canSend] still says yes after all of that, which is where the caller answers for the wearer being there: + * see `SendViewModel`. + * + * A yes counts the payment against today's QuickPay limit, so ask once per send and only when about to [send], + * which takes it out again when nothing was paid. A no counts nothing, and neither does a caller that is + * cancelled before it hears the yes. Anything that cannot be told answers no, and the wearer holds to pay. + */ + suspend fun skipConfirmation(prepared: PreparedSend, canSend: () -> Boolean): Boolean = try { + withContext(ioDispatcher) { + if (!isReady() || sparkService.isWiping) return@withContext false + if (!prepared.isAmountFixed) return@withContext false + quickPayRepo.awaitRate() + // A caller that goes away meanwhile does not stop this halfway, with a count that nothing takes out. + withContext(NonCancellable) { + val reservation = quickPayRepo.reserve(prepared.amountSats) ?: return@withContext false + // The wallet may have locked, paused or been wiped, or the wearer left, while the limit was read. + if (!isReady() || sparkService.isWiping || !canSend()) { + quickPayRepo.release(reservation) + return@withContext false + } + quickPayReservations[prepared.transferKey] = reservation + true + } + } + } catch (e: CancellationException) { + // The caller went away and never hears the yes, so it sends nothing. + withContext(NonCancellable) { + quickPayReservations.remove(prepared.transferKey)?.let { quickPayRepo.release(it) } + } + throw e + } + + /** + * 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) + // 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) + } + } + + /** + * 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() + } + + /** + * The payment of [invoice] as Spark lists it now, or null when it lists none. Fails when the list cannot be + * read, so a caller never takes an unread list for an unpaid invoice. + */ + suspend fun findPaid(invoice: ReceiveInvoice): Result = withContext(ioDispatcher) { + runSuspendCatching { + sparkService.listPayments().firstOrNull { it.isReceiptOf(invoice) }?.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, 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 = decoderInput(input) + 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?.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() + } + 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, [SendError.AlreadyPaid] and [SendError.InFlight] for an invoice that Spark's + * list, as it is on the watch, shows this wallet paid or is paying, and 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) { + runSuspendCatching { + if (!isReady()) throw SendError.NotReady() + val amount = request.fixedAmountSats ?: amountSats ?: throw SendError.AmountRequired() + when (request) { + is SendRequest.Invoice -> { + ensureAmount(amount, 1uL, MAX_SATS) + val isAmountInRequest = request.amountSats != null + prepare( + paymentRequest = request.bolt11, + amountSats = amount, + isAmountInRequest = isAmountInRequest, + payee = request.payee, + isAmountFixed = isAmountInRequest, + ) + } + is SendRequest.Lnurl -> { + ensureAmount(amount, request.minSats, request.maxSats) + prepare( + paymentRequest = lnurlInvoice(request, amount), + amountSats = amount, + isAmountInRequest = true, + payee = request.payee, + exactMsats = amount * MSATS_PER_SAT, + isAmountFixed = request.data.minSendable == request.data.maxSendable, + ) + } + 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(sparkPayee) + prepare( + paymentRequest = request.address, + amountSats = amount, + isAmountInRequest = false, + payee = request.payee, + sparkPayee = sparkPayee, + ) + } + } + }.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?, + exactMsats: ULong? = null, + sparkPayee: String? = null, + isAmountFixed: Boolean = false, + ): PreparedSend { + val input = ensureNotOwn(paymentRequest) + // Told before the review, so the wearer never holds to pay an invoice whose payment is under way or done. + // The list is the one on the watch: [send] syncs before it asks again, for what the phone sent meanwhile. + if (input is InputType.Bolt11Invoice) { + val listed = runSuspendCatching { sparkService.listPayments() }.getOrElse { throw SendError.NotReady() } + ensureUnpaid(listed, input.v1.paymentHash) + } + val response = runSuspendCatching { + sparkService.prepareSend(paymentRequest, amountSats.takeIf { !isAmountInRequest }) + }.getOrElse { throw it.toSendError() } + val method = response.paymentMethod + val (feeSats, invoice) = when (method) { + is SendPaymentMethod.Bolt11Invoice -> method.feeSats() to method.invoiceDetails + 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. + 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) + return PreparedSend( + amountSats = amountSats, + feeSats = feeSats, + payee = payee, + response = response, + paymentHash = invoice?.paymentHash, + expiresAtSecs = invoice?.expiresAt, + sparkPayee = sparkPayee.takeIf { invoice == null }, + transferKey = UUID.randomUUID().toString(), + isAmountFixed = isAmountFixed, + ) + } + + /** + * 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): InputType { + 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() + return input + } + + private fun ensureUnpaid(listed: List, paymentHash: String) { + val sends = listed.filter { it.sendHash().equals(paymentHash, ignoreCase = true) } + if (sends.any { it.status == PaymentStatus.COMPLETED }) throw SendError.AlreadyPaid() + sends.firstOrNull { it.status == PaymentStatus.PENDING } + ?.let { throw SendError.InFlight(it.id, it.amount.toLong().toULong()) } + } + + /** + * 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 + + /** + * 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]. A pending payment, and one whose outcome is + * unknown, is handed to [SendOutcomeRepo], which tells the wearer how it ended, and Spark stays connected for a + * pending one while it settles ([SendOutcomeRepo.holdConnection]). 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 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 + * 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. + * + * A send that [skipConfirmation] counted against the QuickPay limit is taken out of the count again when it + * fails with a [SendError] other than [SendError.Unknown]. One that is pending or unknown stays counted, and + * [SendOutcomeRepo] takes it out when Spark later shows it failed. + * + * While it runs, [SendMonitor.isSending] says so to the whole process, and [SendMonitor.isSyncing] while it + * still waits for the sync that comes before anything goes out. + */ + suspend fun send(prepared: PreparedSend): Result { + // Counted before the send leaves the caller, and until it ends, also when the caller went away meanwhile. + sendMonitor.begin() + val send = sendScope.async { sendCounted(prepared) } + send.invokeOnCompletion { sendMonitor.end() } + return send.await() + } + + private suspend fun sendCounted(prepared: PreparedSend): Result = + runSuspendCatching { + // 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) { + // 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() + sendWatched(prepared, sendKey(prepared)).toWatchPayment() + } finally { + sendMutex.unlock() + } + }.onFailure { + Logger.error("Failed to send a payment", it, context = TAG) + }.also { followUp(it, quickPayReservations.remove(prepared.transferKey)) } + + /** + * What follows a send that ended in [result], with what QuickPay counted for it ([reservation]). As on the + * phone, a QuickPay payment that did not go out or failed is not counted. One whose outcome is unknown may have + * been paid, so it stays counted, and so does one that failed in a way not foreseen. A payment the wearer is + * told is pending or unknown is watched, so its outcome is told too, and its count goes along. One that Spark + * shows sent or failed is told by the caller, so a payment watched under the same id, as an earlier attempt of + * unknown outcome, is forgotten untold, and the count that attempt kept stands for the payment. + */ + private suspend fun followUp(result: Result, reservation: QuickPayReservation?) { + val payment = result.getOrNull() + val error = result.exceptionOrNull() + val unsettled = payment?.takeIf { it.state == PaymentState.Pending }?.id + ?: (error as? SendError.Unknown)?.paymentId + if (unsettled != null) { + sendOutcomeRepo.watch(unsettled, reservation) + return + } + val settled = payment?.id ?: (error as? SendError.Failed)?.paymentId + val wasCounted = settled != null && sendOutcomeRepo.forget(settled, isSent = payment != null) + val isRefused = error is SendError && error !is SendError.Unknown + if (reservation != null && (isRefused || wasCounted)) quickPayRepo.release(reservation) + } + + private suspend fun sendKey(prepared: PreparedSend): String { + sendMonitor.setSyncing(true) + try { + val sparkPayee = prepared.sparkPayee + if (sparkPayee != null) return earlierTransferKey(sparkPayee) ?: prepared.transferKey + syncForSend() + return invoiceKey(checkNotNull(prepared.paymentHash)) + } finally { + sendMonitor.setSyncing(false) + } + } + + /** + * 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, 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() } + ensureUnpaid(listed, paymentHash) + 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 (key(attempt) in failed) attempt++ + return key(attempt) + } + + /** + * 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(sparkPayee: String): String? { + val earlier = runSuspendCatching { uncertainSendStore.transferKeys(sparkPayee) } + .getOrElse { throw SendError.Failed(it) } + if (earlier.isEmpty()) return null + syncForSend() + val listed = runSuspendCatching { sparkService.listPayments().filter { it.id in earlier } } + .getOrElse { throw SendError.NotReady() } + .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() + } + earlier.firstOrNull { listed[it] == PaymentStatus.PENDING }?.let { throw SendError.InFlight(it) } + return earlier.firstOrNull { it !in listed } + } + + /** Sends under [key] while already listening for the payment's outcome, which can arrive before the call ends. */ + 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() } + .filter { it.status != PaymentStatus.PENDING } + .collect { payment -> settled.update { it + (payment.id to payment) } } + } + 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) { + // Spark stays connected while the payment settles, also once this wait is over. + sendOutcomeRepo.holdConnection(sent.id) + withTimeoutOrNull(SETTLE_TIMEOUT) { settled.first { sent.id in it }.getValue(sent.id) } ?: sent + } else { + sent + } + if (payment.status != PaymentStatus.PENDING) sendOutcomeRepo.releaseConnection(sent.id) + if (payment.status == PaymentStatus.FAILED) throw SendError.Failed(paymentId = payment.id) + 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 { + watcher.cancel() + } + } + + /** + * 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 + sendCallRequest = prepared.requestId() + val result = withTimeoutOrNull(SEND_TIMEOUT) { call.await() } + ?: Result.failure(SendError.Unknown(paymentId = key)) + 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. 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 } + val isRefusal = error.isInvoiceExpired() || error is SdkException.InsufficientFunds + if (isRefusal && !wasUncertain) { + 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 if (error is SendError.Unknown) error else SendError.Unknown(error, key) + } + + 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) } + .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. */ + 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) + +/** 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) + this is SdkException.InsufficientFunds -> SendError.InsufficientBalance(null) + else -> SendError.Failed(this) +} diff --git a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt new file mode 100644 index 0000000000..419668aca6 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -0,0 +1,128 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.QuickPaySpendStore +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BTC_SCALE +import to.bitkit.wear.models.FxRate +import to.bitkit.wear.models.QuickPayLimits +import to.bitkit.wear.models.SATS_IN_BTC +import to.bitkit.wear.models.USD +import to.bitkit.wear.models.fiatValue +import to.bitkit.wear.utils.Logger +import java.math.BigDecimal +import java.math.RoundingMode +import java.time.Instant +import java.time.ZoneId +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.seconds + +/** + * Decides whether a payment goes out under the phone's QuickPay settings, which the watch imports and never sets, by + * the rules of the phone's own `QuickPayRepo`: the same amount, rate, rounding and daily count. It reads the settings + * as last imported, however long ago. Everything that is missing or unreadable answers no. + */ +@Singleton +class QuickPayRepo internal constructor( + private val ioDispatcher: CoroutineDispatcher, + private val settingsStore: SettingsStore, + private val currencyRepo: CurrencyRepo, + private val spendStore: QuickPaySpendStore, + private val nowMs: () -> Long, + private val zone: () -> ZoneId, +) { + companion object { + private const val TAG = "QuickPayRepo" + private const val CENTS_SCALE = 2 + + /** How long [awaitRate] holds a payment back for the dollar rate before it goes on without. */ + val RATE_TIMEOUT = 5.seconds + } + + @Inject + constructor( + @IoDispatcher ioDispatcher: CoroutineDispatcher, + settingsStore: SettingsStore, + currencyRepo: CurrencyRepo, + spendStore: QuickPaySpendStore, + ) : this( + ioDispatcher, + settingsStore, + currencyRepo, + spendStore, + System::currentTimeMillis, + ZoneId::systemDefault, + ) + + private val mutex = Mutex() + + /** + * Fetches the rates when QuickPay is on and no dollar rate is in yet, as for a payment whose link started the + * app: the watch keeps no rates across restarts, where the phone has its cached ones. It waits at most + * [RATE_TIMEOUT] and decides nothing: without a rate [reserve] answers no. + */ + suspend fun awaitRate(): Unit = withContext(ioDispatcher) { + runSuspendCatching { + if (settingsStore.data.first().quickPay?.isEnabled != true) return@runSuspendCatching + if (currencyRepo.rates.value.rateFor(USD) != null) return@runSuspendCatching + withTimeoutOrNull(RATE_TIMEOUT) { currencyRepo.refresh() } + }.onFailure { Logger.warn("Failed to fetch the rate QuickPay reads", it, context = TAG) } + } + + /** + * Whether a payment of [amountSats], its fee not counted, may skip the hold to pay; if so it is counted against + * today's limit and returned as what [release] takes back. It may when QuickPay is on in the last import, the + * amount is no more than the phone's QuickPay amount, in sats and in unrounded dollars at the dollar rate (the + * phone checks the one when it offers QuickPay and the other when it pays), and today's QuickPay payments + * from this watch stay within the phone's daily limit with it. Any failure to read or count answers null. + */ + suspend fun reserve(amountSats: ULong): QuickPayReservation? = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { reserveLocked(amountSats) } } + .onFailure { Logger.warn("Failed to check QuickPay", it, context = TAG) } + .getOrNull() + } + + /** + * Takes [reservation] out of its day's count again, for a payment that did not go out or that failed, as the + * phone does. A count that cannot be written stays, which only makes the day's limit tighter. + */ + suspend fun release(reservation: QuickPayReservation): Unit = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { spendStore.release(reservation.dayKey, reservation.cents) } } + .onFailure { Logger.warn("Failed to release a QuickPay payment", it, context = TAG) } + } + + private suspend fun reserveLocked(amountSats: ULong): QuickPayReservation? { + val quickPay = settingsStore.data.first().quickPay?.takeIf { it.isEnabled } ?: return null + if (amountSats == 0uL || amountSats > Long.MAX_VALUE.toULong()) return null + val rate = currencyRepo.rates.value.rateFor(USD) ?: return null + val thresholdSats = thresholdSats(quickPay, rate) ?: return null + if (thresholdSats == 0uL || amountSats > thresholdSats) return null + val fiatCents = fiatValue(amountSats.toLong(), rate)?.movePointRight(CENTS_SCALE) ?: return null + // The threshold in sats may have rounded up, so its last sat can be worth a fraction of a cent too much. + if (fiatCents > BigDecimal.valueOf(quickPay.thresholdCents)) return null + val cents = fiatCents.setScale(0, RoundingMode.HALF_UP).toLong().coerceAtLeast(1L) + val today = Instant.ofEpochMilli(nowMs()).atZone(zone()).toLocalDate().toString() + val dayKey = spendStore.reserve(today, cents, quickPay.dailyCapCents) ?: return null + return QuickPayReservation(dayKey, cents) + } + + private fun thresholdSats(quickPay: QuickPayLimits, rate: FxRate): ULong? { + if (rate.rate <= 0.0) return null + val sats = BigDecimal.valueOf(quickPay.amountUsd.toDouble()) + .divide(BigDecimal.valueOf(rate.rate), BTC_SCALE, RoundingMode.HALF_UP) + .multiply(BigDecimal(SATS_IN_BTC)) + .setScale(0, RoundingMode.HALF_UP) + return runCatching { sats.longValueExact().toULong() }.getOrNull() + } +} + +/** A payment counted against the QuickPay limit of [dayKey], an ISO date, as [cents] US cents. */ +data class QuickPayReservation(val dayKey: String, val cents: Long) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/SendOutcomeRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/SendOutcomeRepo.kt new file mode 100644 index 0000000000..b2f5d4a7ba --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/SendOutcomeRepo.kt @@ -0,0 +1,308 @@ +package to.bitkit.wear.repositories + +import breez_sdk_spark.Payment +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.SdkEvent +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.UncertainSendStore +import to.bitkit.wear.data.WatchedOutcome +import to.bitkit.wear.data.WatchedSend +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.utils.Logger +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.minutes + +/** + * Tells the wearer how a payment ended that the watch reported as pending or of unknown outcome. Such a payment is + * remembered in [UncertainSendStore], across restarts, until Spark shows it completed or failed: by a payment event + * while the app is open, or by Spark's list, which is compared after every sync and whenever the wallet becomes + * ready, since the first sync after a reconnect updates the list without an event. Its outcome then goes to the + * screen that waits for it ([awaitLive]) or else into [outcomes], which the app shows once no screen is up that it + * must not cover. The outcome stays remembered with the payment until it was shown ([consume]), so one that was + * found while the app was off screen is still told after Android stopped the process. + * A QuickPay payment that failed after all is taken out of its day's count, and the balance is synced again + * ([WalletRepo.syncBalance]), so what a failed payment gives back shows at once. + * + * It also keeps Spark connected for a payment that is settling: see [holdConnection]. + */ +@Singleton +class SendOutcomeRepo @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val sparkService: WatchSparkService, + private val walletRepo: WalletRepo, + private val store: UncertainSendStore, + private val quickPayRepo: QuickPayRepo, + private val sendMonitor: SendMonitor, +) { + companion object { + private const val TAG = "SendOutcomeRepo" + + /** + * How long after Spark took a payment the connection is held for it to settle: the time the SDK itself keeps + * checking a Lightning payment for, about three minutes. + */ + val SETTLE_HOLD = 3.minutes + } + + private val scope = CoroutineScope(SupervisorJob() + ioDispatcher) + + private val mutex = Mutex() + + private val holds = HashMap() + + private val claims = ConcurrentHashMap>() + + private val _outcomes = MutableStateFlow>(emptyList()) + + /** + * The outcomes the wearer was not shown yet, the oldest first, also those an earlier run of the app found. + * [consume] takes one out once it was shown. + */ + val outcomes: StateFlow> = _outcomes.asStateFlow() + + private val restored = scope.launch { restore() } + + init { + scope.launch { + sparkService.events.collect { event -> + runSuspendCatching { onEvent(event) } + .onFailure { Logger.warn("Failed to follow a watched payment", it, context = TAG) } + } + } + scope.launch { + walletRepo.walletState.map { it.status }.distinctUntilChanged().collect { status -> + when (status) { + WalletStatus.Ready -> check() + WalletStatus.Missing, WalletStatus.Removed -> clear() + else -> Unit + } + } + } + } + + /** + * Remembers the payment Spark lists under [id], which the wearer is told is pending or of unknown outcome, with + * what QuickPay counted for it ([reservation]). A payment already remembered keeps what was counted for it, and + * a second count for it is taken out again; one whose outcome is known and still to be shown is left as it is. + * Spark's list is compared at once, for an outcome that arrived meanwhile. A payment that cannot be remembered + * is only not announced: Activity still shows how it ended. Nothing is remembered for a wallet that is being + * wiped or is gone, whose settings the wipe already cleared. + */ + suspend fun watch(id: String, reservation: QuickPayReservation?): Unit = withContext(ioDispatcher) { + runSuspendCatching { + mutex.withLock { + val known = store.watched().firstOrNull { it.id == id } + if (known?.outcome != null) return@withLock + if (known?.quickPayDay != null) { + reservation?.let { quickPayRepo.release(it) } + return@withLock + } + store.watch(WatchedSend(id, reservation?.dayKey, reservation?.cents ?: 0L)) + if (isWalletGone()) store.unwatch(id) + } + }.onFailure { Logger.warn("Failed to watch the payment '$id'", it, context = TAG) } + check() + } + + /** + * Forgets the payment [id] untold, since the send that just ended told the wearer itself how it ended: sent + * ([isSent]) or failed. A retry under the id of a watched payment ends like this. What QuickPay counted for the + * watched payment is taken out when it failed. Returns whether the payment was watched with a QuickPay count, + * which then stands for the payment, so the caller takes the retry's own count out. + */ + suspend fun forget(id: String, isSent: Boolean): Boolean = withContext(ioDispatcher) { + runSuspendCatching { + mutex.withLock { + val watched = store.watched().firstOrNull { it.id == id } ?: return@withLock false + if (!store.unwatch(id)) return@withLock false + _outcomes.update { queue -> queue.filter { it.id != id } } + releaseConnection(id) + val day = watched.quickPayDay + // A payment whose outcome was already found had its count taken out then. + if (!isSent && day != null && watched.outcome == null) { + quickPayRepo.release(QuickPayReservation(day, watched.quickPayCents)) + } + Logger.info("Forgot watched payment '$id' that its send told", context = TAG) + day != null + } + }.onFailure { Logger.warn("Failed to forget the payment '$id'", it, context = TAG) }.getOrDefault(false) + } + + /** + * Keeps Spark connected for the payment [id], which Spark took from this watch and has not settled, also after + * the app left the screen: until [releaseConnection], which follows its outcome, or for [SETTLE_HOLD] at most. + * A lock of the watch still disconnects at once. + */ + fun holdConnection(id: String) = synchronized(holds) { + if (id in holds) return@synchronized + sendMonitor.holdSettling() + holds[id] = scope.launch { + delay(SETTLE_HOLD) + releaseConnection(id) + } + } + + fun releaseConnection(id: String) = synchronized(holds) { + val hold = holds.remove(id) ?: return@synchronized + sendMonitor.releaseSettling() + hold.cancel() + } + + /** + * Waits for the outcome of the watched payment [id] for as long as the caller shows it as pending, and returns + * it in place of [outcomes], also one that was found just before the caller waited. The caller shows it and + * then calls [consume], or leaves it to [outcomes] with [enqueue]. A caller that stops waiting leaves the + * outcome to [outcomes]: none is lost between the two. + */ + suspend fun awaitLive(id: String): SendOutcome { + val claim = CompletableDeferred() + claims[id] = claim + takeQueued(id)?.let { if (!claim.complete(it)) enqueue(it) } + return try { + claim.await().also { claims.remove(id, claim) } + } catch (e: CancellationException) { + claims.remove(id, claim) + claim.cancel() + // An outcome that arrived just as the caller stopped waiting is told by the overlay instead. + if (!claim.isCancelled) withContext(NonCancellable) { enqueue(claim.await()) } + throw e + } + } + + /** + * Waits until the wearer was shown every outcome known by now: Spark's list is compared first, for a payment + * that ended while the app was closed, and then [outcomes] has to empty. A send flow waits here before it shows + * anything of its own, so the end of an earlier payment is always told before the next one's result. + */ + suspend fun awaitTold() { + restored.join() + withContext(ioDispatcher) { check() } + outcomes.first { it.isEmpty() } + } + + /** Leaves [outcome] to [outcomes] after all, as when the screen that awaited it cannot show it now. */ + fun enqueue(outcome: SendOutcome) = _outcomes.update { queue -> + if (queue.any { it.id == outcome.id }) queue else queue + outcome + } + + /** + * Forgets the outcome of the payment [id] once it was shown: it leaves [outcomes] and is not told again, also + * after a restart. The caller cannot cancel it half way. An outcome that cannot be forgotten is at worst told + * once more by the next run of the app. + */ + suspend fun consume(id: String): Unit = withContext(ioDispatcher + NonCancellable) { + mutex.withLock { + runSuspendCatching { store.unwatch(id) } + .onFailure { Logger.warn("Failed to forget the shown payment '$id'", it, context = TAG) } + _outcomes.update { queue -> queue.filter { it.id != id } } + } + } + + private fun takeQueued(id: String): SendOutcome? { + var taken: SendOutcome? = null + _outcomes.update { queue -> + taken = queue.firstOrNull { it.id == id } + queue.filter { it.id != id } + } + return taken + } + + private suspend fun restore() { + runSuspendCatching { + mutex.withLock { + val resolved = store.watched().filter { it.outcome != null } + if (isWalletGone()) return@withLock + resolved.reversed().forEach { send -> + send.outcome?.let { enqueue(SendOutcome(send.id, it.amountSats, it.isSent)) } + } + } + }.onFailure { Logger.warn("Failed to read the outcomes that were not shown", it, context = TAG) } + } + + private fun isWalletGone(): Boolean { + val status = walletRepo.walletState.value.status + return sparkService.isWiping || status == WalletStatus.Missing || status == WalletStatus.Removed + } + + private suspend fun onEvent(event: SdkEvent) = when (event) { + is SdkEvent.PaymentSucceeded -> resolve(event.payment) + is SdkEvent.PaymentFailed -> resolve(event.payment) + is SdkEvent.Synced -> check() + else -> Unit + } + + private suspend fun check() { + runSuspendCatching { + if (sparkService.isWiping) return@runSuspendCatching + val ids = store.watched().filter { it.outcome == null }.mapTo(HashSet()) { it.id } + if (ids.isEmpty()) return@runSuspendCatching + sparkService.listPayments().filter { it.id in ids }.forEach { resolve(it) } + }.onFailure { Logger.warn("Failed to compare the watched payments with the list", it, context = TAG) } + } + + private suspend fun resolve(payment: Payment) { + if (payment.status == PaymentStatus.PENDING || sparkService.isWiping) return + val isSent = payment.status == PaymentStatus.COMPLETED + val amountSats = payment.amount.toLong().toULong() + mutex.withLock { + // A wipe that began meanwhile ends in the queue being emptied, which waits for this lock. + if (sparkService.isWiping) return + val watched = store.watched().firstOrNull { it.id == payment.id && it.outcome == null } ?: return + // Noted before it is told, so an outcome is found once and a count is never taken out twice, and kept + // until it was shown, so it is still told when the process ends before the wearer looks. + if (!store.resolve(payment.id, WatchedOutcome(isSent, amountSats))) return + releaseConnection(payment.id) + val day = watched.quickPayDay + if (!isSent && day != null) quickPayRepo.release(QuickPayReservation(day, watched.quickPayCents)) + Logger.info("Resolved watched payment '${payment.id}' as '${payment.status}'", context = TAG) + deliver(SendOutcome(payment.id, amountSats, isSent)) + } + // Off the caller, which is Spark's event stream or a wallet start: the outcome is told at once, and the + // balance follows the sync. + scope.launch { + walletRepo.syncBalance() + .onFailure { Logger.warn("Failed to refresh the balance after a watched payment", it, context = TAG) } + } + } + + private fun deliver(outcome: SendOutcome) { + val claim = claims.remove(outcome.id) + if (claim == null || !claim.complete(outcome)) enqueue(outcome) + } + + private suspend fun clear() { + mutex.withLock { _outcomes.update { emptyList() } } + val held = synchronized(holds) { holds.keys.toList() } + held.forEach { releaseConnection(it) } + } +} + +/** How the payment [id] ended that the watch reported as pending or unknown: sent ([isSent]) or failed. */ +data class SendOutcome( + val id: String, + val amountSats: ULong, + val isSent: Boolean, +) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt new file mode 100644 index 0000000000..2b1f506528 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt @@ -0,0 +1,181 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.ElapsedClock +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.PhoneSettingsParser +import to.bitkit.wear.security.SeedStore +import to.bitkit.wear.security.WalletSeed +import to.bitkit.wear.services.PhoneBackupReader +import to.bitkit.wear.services.PhoneBackupUnreadable +import to.bitkit.wear.services.SparkError +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.utils.AppError +import to.bitkit.wear.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * Imports the phone's settings from its backup on VSS, which the watch can read because it holds the same seed. It + * only reads: see [PhoneBackupReader]. The watch adopts the units, the currency and QuickPay, and sets none of them + * itself. + */ +@Singleton +class SettingsSyncRepo internal constructor( + private val ioDispatcher: CoroutineDispatcher, + private val seedStore: SeedStore, + private val backupReader: PhoneBackupReader, + private val settingsStore: SettingsStore, + private val sparkService: WatchSparkService, + private val walletRepo: WalletRepo, + private val clock: ElapsedClock, + private val nowMs: () -> Long, +) { + companion object { + private const val TAG = "SettingsSyncRepo" + + /** The key of the phone's settings backup, the name of its `BackupCategory.SETTINGS`. */ + const val SETTINGS_KEY = "SETTINGS" + + /** How long an import waits for signing in to VSS and reading the backup. */ + val READ_TIMEOUT = 30.seconds + + /** + * How soon after a read of the backup the next one is skipped, unless the wearer asked for it. Each read + * signs in to VSS anew, so a wallet that keeps losing and finding its network must not start one each time. + */ + val MIN_READ_GAP = 1.minutes + } + + @Inject + constructor( + @IoDispatcher ioDispatcher: CoroutineDispatcher, + seedStore: SeedStore, + backupReader: PhoneBackupReader, + settingsStore: SettingsStore, + sparkService: WatchSparkService, + walletRepo: WalletRepo, + clock: ElapsedClock, + ) : this( + ioDispatcher, + seedStore, + backupReader, + settingsStore, + sparkService, + walletRepo, + clock, + System::currentTimeMillis, + ) + + /** + * Where imports and their reads run. Nothing cancels it, so an import lands whoever stopped waiting for it, and + * a read that was given up ends by itself. + */ + private val scope = CoroutineScope(SupervisorJob() + ioDispatcher) + + private val mutex = Mutex() + + /** The wipe token and the [clock] time of the last read that reached the backup. Guarded by [mutex]. */ + private var lastRead: Pair? = null + + /** + * Reads the phone's settings backup and adopts it, for a wallet that is ready. A backup that is missing, cannot + * be decrypted or read, or has a newer layout keeps the watch's display values and turns QuickPay off. A read + * that fails, as without a network, changes nothing: QuickPay goes on with the settings last imported. An import + * that a wallet wipe overtook is taken out again, so nothing of a removed wallet's settings stays. + * + * The import runs in the repo's own scope and the caller only waits for it: a caller that is cancelled or + * timed out returns at once, and the import goes on and lands for the next one to find. The import itself stops + * waiting for its read after [READ_TIMEOUT], or as soon as the wallet stops being ready, as on a lock or a + * pause, and then writes nothing. The VSS library blocks its thread for each of its HTTP calls, so a read that + * was given up is not over at once: it ends with the call it is in, and only then is its client, with the keys + * derived from the seed, shut down. + * + * A call that waited for another import joins it: within [MIN_READ_GAP] of a read of this wallet's backup + * nothing is read again and the call succeeds, unless [isForced], as for the wearer's own tap. + */ + suspend fun sync(isForced: Boolean = false): Result = runSuspendCatching { + val import = scope.async { + runSuspendCatching { mutex.withLock { syncLocked(isForced) } } + .onFailure { Logger.warn("Failed to import the phone's settings", it, context = TAG) } + } + import.await().getOrThrow() + } + + private suspend fun syncLocked(isForced: Boolean) { + val wipeToken = sparkService.wipeToken() ?: throw SparkError.WipeInProgress() + if (walletRepo.walletState.value.status != WalletStatus.Ready) throw SettingsSyncError.NotReady() + if (!isForced && isReadRecently(wipeToken)) return + val seed = seedStore.load().getOrThrow() + val backup = withTimeoutOrNull(READ_TIMEOUT) { readWhileReady(seed) } ?: throw SettingsSyncError.Timeout() + val parsed = backup.fold( + onSuccess = { bytes -> runSuspendCatching { bytes?.let { PhoneSettingsParser.parse(it) } } }, + onFailure = { if (it is PhoneBackupUnreadable) Result.failure(it) else throw it }, + ) + val settings = parsed.getOrNull() + when { + parsed.isFailure -> { + Logger.warn("Failed to read the phone's settings backup", parsed.exceptionOrNull(), context = TAG) + settingsStore.clearQuickPay() + } + settings == null -> { + Logger.info("Found no settings backup of the phone", context = TAG) + settingsStore.clearQuickPay() + } + else -> { + settingsStore.applyPhoneSettings(settings, nowMs()) + Logger.info("Imported the phone's settings", context = TAG) + } + } + lastRead = wipeToken to clock.nowMs() + if (!sparkService.isCurrent(wipeToken)) { + settingsStore.clearPhoneSettings() + throw SparkError.WipeInProgress() + } + } + + private fun isReadRecently(wipeToken: Int): Boolean { + val (token, readAtMs) = lastRead ?: return false + return token == wipeToken && clock.nowMs() - readAtMs in 0 until MIN_READ_GAP.inWholeMilliseconds + } + + /** + * Reads the settings backup, or fails with [SettingsSyncError.NotReady] the moment the wallet is not ready any + * more. The read runs apart in [scope], since it blocks its thread and cannot be interrupted: this returns as + * soon as either side answers or the caller's time is up, and a read that lost is cancelled, which it follows + * at the end of its HTTP call, shutting its client down. + */ + private suspend fun readWhileReady(seed: WalletSeed): Result { + val read = scope.async { runSuspendCatching { backupReader.read(seed, SETTINGS_KEY) } } + try { + return channelFlow { + launch { send(read.await()) } + launch { + walletRepo.walletState.first { it.status != WalletStatus.Ready } + send(Result.failure(SettingsSyncError.NotReady())) + } + }.first() + } finally { + read.cancel() + } + } +} + +sealed class SettingsSyncError(message: String) : AppError(message) { + class NotReady : SettingsSyncError("The wallet is not ready") + + class Timeout : SettingsSyncError("Timed out reading the phone's settings") +} diff --git a/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt index 39561ef347..36b3857e43 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.getAndUpdate import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update @@ -22,6 +23,7 @@ import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.NetworkMonitor +import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.ext.runSuspendCatching @@ -49,6 +51,7 @@ class WalletRepo @Inject constructor( private val deviceLock: DeviceLock, private val networkMonitor: NetworkMonitor, private val foregroundMonitor: ForegroundMonitor, + private val sendMonitor: SendMonitor, ) { companion object { private const val TAG = "WalletRepo" @@ -59,7 +62,10 @@ class WalletRepo @Inject constructor( /** How long the wallet sync may take before the start counts as failed; a first sync took about 3.5 minutes. */ val SYNC_TIMEOUT = 5.minutes - /** How long the app may be off screen before Spark is disconnected, so a glance away keeps it connected. */ + /** + * How long the app may be off screen before Spark is disconnected, so a glance away keeps it connected. It + * counts from the end of [SendMonitor.isSettling] when a payment sent from this watch is still settling. + */ val BACKGROUND_GRACE = 10.seconds /** How long an offline wallet waits before each try to sync again; the last wait repeats. */ @@ -155,7 +161,9 @@ class WalletRepo @Inject constructor( * watch with a screen lock ever is. A wipe that did not complete is finished first, and nothing connects while * one runs. When the seed key is certainly lost, the wallet is wiped and [WalletStatus.Removed] reported. A sync * that does not reach Spark fails the start: [WalletStatus.Offline] once this session has synced, - * [WalletStatus.Error] before. A start that a wipe, a lock or the background overtook connects nothing and leaves + * [WalletStatus.Error] before. A sync that reaches Spark while the watch has no network ends in + * [WalletStatus.Offline] too, never ready. + * A start that a wipe, a lock or the background overtook connects nothing and leaves * the state to them. When a wipe ran or began before the start's second token check, the start puts back the * status it found; a wipe that begins later reports its own status when it ends. When the network, an * unlock or the app came back while a start that then failed was running, the start runs once more. Its caller @@ -235,10 +243,16 @@ class WalletRepo @Inject constructor( private fun markReady(wipeToken: Int) { if (!sparkService.isCurrent(wipeToken)) throw SparkError.WipeInProgress() checkStillStarting() + // A sync can reach Spark without a network, as over a local stack or a link the system does not count: the + // watch pays only online, so such a wallet is offline with its balance confirmed, never ready. + val status = if (networkMonitor.isOnline.value) WalletStatus.Ready else WalletStatus.Offline val previous = _walletState.getAndUpdate { - if (it.status == WalletStatus.Connecting) it.copy(status = WalletStatus.Ready, hasSynced = true) else it + if (it.status == WalletStatus.Connecting) it.copy(status = status, hasSynced = true) else it } if (previous.status != WalletStatus.Connecting) throw WalletError.Overtaken() + if (status == WalletStatus.Offline) Logger.info("Kept synced wallet offline without a network", context = TAG) + // The network can go between the read above and the status: its loss found nothing ready to mark. + if (!networkMonitor.isOnline.value) onNetworkLoss() } private suspend fun onStartFailure(error: Throwable) { @@ -297,11 +311,19 @@ class WalletRepo @Inject constructor( } private suspend fun lock() { + // Locked from before the disconnect on, which can take seconds, as a pause is not ready from before its + // own: nothing is priced or sent on a wallet that is going away. + val previous = _walletState.getAndUpdate { + if (it.status in disconnectedStatuses) it else it.copy(status = WalletStatus.Locked) + } // A disconnect that failed earlier left Spark connected under a disconnected status. val isDisconnected = disconnectQuietly() - if (_walletState.value.status in disconnectedStatuses) return - markLocked() - if (isDisconnected) Logger.info("Disconnected wallet because the watch locked", context = TAG) + // Locked again: a start that an unlock began while the disconnect waited, as for a send to end, found Spark + // still connected and may have reached ready. The unlock, handled after this, then starts the wallet fresh. + _walletState.update { if (it.status in disconnectedStatuses) it else it.copy(status = WalletStatus.Locked) } + if (isDisconnected && previous.status !in disconnectedStatuses) { + Logger.info("Disconnected wallet because the watch locked", context = TAG) + } } private fun markLocked() = _walletState.update { @@ -316,7 +338,12 @@ class WalletRepo @Inject constructor( return } graceJob = scope.launch { - delay(BACKGROUND_GRACE) + // A payment sent from this watch that is still settling keeps Spark connected, for as long as its hold + // lasts, so its outcome is learned. A lock does not wait for it. + do { + sendMonitor.isSettling.first { !it } + delay(BACKGROUND_GRACE) + } while (sendMonitor.isSettling.value) // Returning to the app cancels only the wait above, never a pause that began. withContext(NonCancellable) { pause() } } @@ -324,6 +351,10 @@ class WalletRepo @Inject constructor( private suspend fun pause() { if (isForeground) return + // Not ready from before the disconnect on, which can take seconds: an app that returns meanwhile must not + // price or send on a wallet that is going away. It reads as connecting, which starts nothing by itself, + // until the disconnect is over and the wallet is paused. + _walletState.update { if (it.status == WalletStatus.Ready) it.copy(status = WalletStatus.Connecting) else it } val isDisconnected = disconnectQuietly() _walletState.update { if (it.status in pausableStatuses) it.copy(status = WalletStatus.Paused) else it } if (isDisconnected) Logger.info("Disconnected wallet because the app left the screen", context = TAG) @@ -370,6 +401,19 @@ class WalletRepo @Inject constructor( .onFailure { Logger.warn("Failed to disconnect wallet", it, context = TAG) } .isSuccess + /** + * Syncs with Spark and loads the balance it then has, as after a payment ended whose amount Spark gives back: + * Spark's stored balance only follows with its next sync. A wallet that is not ready is left alone, as its + * next start syncs. + */ + suspend fun syncBalance(): Result = withContext(ioDispatcher) { + runSuspendCatching { + if (_walletState.value.status != WalletStatus.Ready) return@runSuspendCatching + withTimeoutOrNull(SYNC_TIMEOUT) { sparkService.syncWallet() } + refreshBalance().getOrThrow() + } + } + /** Loads the balance from Spark. A balance read while the wallet is wiped is dropped. */ suspend fun refreshBalance(): Result = withContext(ioDispatcher) { runSuspendCatching { @@ -455,7 +499,10 @@ enum class WalletStatus { Connecting, Ready, - /** This session synced, but the last sync did not reach Spark, so the balance shown is the last one known. */ + /** + * This session synced, but the last sync did not reach Spark, so the balance shown is the last one known, or the + * watch has no network. + */ Offline, /** The wallet could not be loaded, and no sync reached Spark this session. */ 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/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/PhoneBackupReader.kt b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt new file mode 100644 index 0000000000..6f68ef81ec --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt @@ -0,0 +1,69 @@ +package to.bitkit.wear.services + +import com.synonym.vssclient.VssException +import com.synonym.vssclient.vssDeriveStoreId +import com.synonym.vssclient.vssGet +import com.synonym.vssclient.vssNewClientWithLnurlAuth +import com.synonym.vssclient.vssShutdownClient +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import to.bitkit.wear.env.Env +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.security.WalletSeed +import to.bitkit.wear.utils.AppError +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The watch's only way to the phone's backups on VSS, and it can only read: there is no call here that stores, + * replaces or deletes anything, so the watch can never clobber what the phone backed up. + */ +fun interface PhoneBackupReader { + /** + * The backup object stored under [key] for the wallet of [seed], or null when the phone stored none. Fails with + * [PhoneBackupUnreadable] when an object is stored that this wallet's keys cannot open. + */ + suspend fun read(seed: WalletSeed, key: String): ByteArray? +} + +/** The phone's backup object is stored, but it cannot be decoded or decrypted with the wallet's keys. */ +class PhoneBackupUnreadable : AppError("The phone's backup cannot be decrypted") + +/** + * [PhoneBackupReader] over vss-client, set up as the phone's `VssBackupClient` is: the same server, store id and + * LNURL-auth sign-in, all derived from the seed. This file is the only one that may name the VSS library, and of it + * only the four calls and the error type imported above; `PhoneBackupReaderTest` checks both. The library reports + * an object it fetched and cannot decode or decrypt as a get error, and every failure to reach the server or to + * sign in as another type, so a get error is an unreadable backup. The library keeps one client for the + * process, holding keys derived from the seed, so each read builds it and shuts it down again: nothing of a wallet + * stays behind for a lock, a pause or a wipe to clean up. + * + * The library runs each call to its end on the calling thread, so a read cannot be interrupted: one that is + * cancelled goes on until its HTTP call returns and only then shuts the client down. A caller that must not wait + * that long runs the read apart and stops waiting for it, as `SettingsSyncRepo` does. + */ +@Singleton +class VssPhoneBackupReader @Inject constructor() : PhoneBackupReader { + private val mutex = Mutex() + + override suspend fun read(seed: WalletSeed, key: String): ByteArray? = mutex.withLock { + try { + vssNewClientWithLnurlAuth( + baseUrl = Env.vssServerUrl(), + storeId = vssDeriveStoreId(Env.vssStoreIdPrefix(), seed.mnemonic, seed.passphrase), + mnemonic = seed.mnemonic, + passphrase = seed.passphrase, + lnurlAuthServerUrl = Env.lnurlAuthServerUrl(), + ) + try { + vssGet(key)?.value + } catch (_: VssException.GetException) { + throw PhoneBackupUnreadable() + } + } finally { + withContext(NonCancellable) { runSuspendCatching { vssShutdownClient() } } + } + } +} 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/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..efc378b6f5 100644 --- a/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt +++ b/wear/src/main/java/to/bitkit/wear/services/WatchSparkService.kt @@ -7,33 +7,51 @@ 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 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 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 +import kotlin.time.Duration.Companion.seconds import breez_sdk_spark.Network as SparkNetwork /** @@ -44,6 +62,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" @@ -54,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. @@ -93,6 +115,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 +130,13 @@ 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 + + /** 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) val events: SharedFlow = _events.asSharedFlow() @@ -112,6 +148,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 +191,21 @@ 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 = bip39.toSeed(seed.mnemonic, seed.passphrase).let { bytes -> + SparkSendKey.secret(bytes).also { bytes.fill(0) } + } + 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 @@ -198,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 + * 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 } } mutex.withLock { val current = sdk ?: return@withLock listenerId?.let { id -> @@ -213,6 +268,7 @@ class WatchSparkService @Inject constructor( current.disconnect() sdk = null listenerId = null + sendKeySecret = null Logger.info("Disconnected Spark wallet", context = TAG) } } @@ -242,6 +298,78 @@ 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) + } + + /** + * 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. + */ + 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) { + runningSends.update { it + 1 } + try { + current.sendPayment(SendPaymentRequest(prepared, options, idempotencyKey)).payment + } finally { + runningSends.update { it - 1 } + } + } + } + + /** 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/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..64d06d07f5 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt @@ -0,0 +1,165 @@ +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 kotlinx.coroutines.flow.first +import to.bitkit.wear.R +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BitcoinDisplayUnit +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 + + @Inject + lateinit var settingsStore: SettingsStore + + override fun onTileRequest(requestParams: RequestBuilders.TileRequest): ListenableFuture = + SuspendToFutureAdapter.launchFuture { + val unit = runSuspendCatching { settingsStore.data.first().displayUnit } + .getOrDefault(BitcoinDisplayUnit.MODERN) + val state = tileState(walletRepo.hasWallet(), walletRepo.walletState.value, unit) + 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..cbcb2c3ac2 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt @@ -0,0 +1,35 @@ +package to.bitkit.wear.tile + +import to.bitkit.wear.models.BitcoinDisplayUnit +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, with the balance in bitcoin written in [unit]. + * 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, + unit: BitcoinDisplayUnit, + 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, unit, 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..74bee90795 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt @@ -0,0 +1,43 @@ +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.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import to.bitkit.wear.data.SettingsStore +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, the bitcoin unit imported + * from the phone, 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 settingsStore: SettingsStore, +) { + private val scope = CoroutineScope(ioDispatcher + SupervisorJob()) + + /** Follows the wallet for the life of the process. */ + fun start() { + scope.launch { + val units = settingsStore.data.map { it.displayUnit }.distinctUntilChanged() + walletRepo.walletState + .combine(units) { wallet, unit -> tileState(hasWallet = true, wallet, unit) to wallet.status } + .distinctUntilChanged() + .collect { TileService.getUpdater(context).requestUpdate(BalanceTileService::class.java) } + } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchGate.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchGate.kt new file mode 100644 index 0000000000..053de54e73 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchGate.kt @@ -0,0 +1,51 @@ +package to.bitkit.wear.ui + +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.nfc.NfcTapFilter +import to.bitkit.wear.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Decides what an intent's request may open, for the whole process: the repeat of a tap and anything that arrives + * while a send is under way open nothing. It is asked before a request reaches a screen and holds no activity's + * state, so it decides the same whichever activity instance Android handed the intent to. + */ +@Singleton +class LaunchGate @Inject constructor( + private val tapFilter: NfcTapFilter, + private val sendMonitor: SendMonitor, +) { + companion object { + private const val TAG = "LaunchGate" + } + + /** Whether a send is under way anywhere in the process. */ + val isSending: Boolean get() = sendMonitor.isSending.value + + /** + * What to show for [request], read from an intent, or null for nothing. For a tapped tag, [isTap], a request + * that is no [LaunchRequest.Send] becomes the tag's refusal, and a repeat of the last tap, told by the request + * or else by [tapData], the tag's first record, is dropped. + */ + fun admit(request: LaunchRequest?, isTap: Boolean = false, tapData: String? = null): LaunchRequest? { + val asked = if (isTap) request as? LaunchRequest.Send ?: LaunchRequest.TagRefused else request + if (isTap) { + val tapped = (asked as? LaunchRequest.Send)?.input ?: tapData.orEmpty() + // The filter hears of every tap, also one dropped below, so its repeats stay dropped afterwards. + if (!tapFilter.isNew(tapped)) { + Logger.debug("Dropped a repeat of an NFC tap", context = TAG) + return null + } + if (asked is LaunchRequest.TagRefused) { + Logger.info("Refused an NFC tag without a payment request the watch takes", context = TAG) + } + } + if (asked == null) return null + if (isSending) { + Logger.info("Dropped launch request '${asked::class.simpleName}' during a send", context = TAG) + return null + } + return asked + } +} 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..d7b73a2b26 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -0,0 +1,79 @@ +package to.bitkit.wear.ui + +import android.content.Intent +import android.nfc.NdefMessage +import android.nfc.NfcAdapter +import androidx.core.content.IntentCompat +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentRequest + +/** What an intent that opened the app asks for, beyond showing it. */ +sealed interface LaunchRequest { + /** + * Pay the payment input of a `bitcoin:`, `lightning:`, `lnurl:`, `lnurlp:` or `spark:` link, in any case, or + * the one read from an NFC tag. + */ + data class Send(val input: String) : LaunchRequest + + /** Show the receive QR, as from the tile. */ + data object Receive : LaunchRequest + + /** Say that the tapped NFC tag holds no payment request the watch takes; never made from a link. */ + data object TagRefused : 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" + + /** 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. For a + * tapped NFC tag, [tagTexts] holds the texts of the tag's records when the intent carries the tag's + * message: see [tagInput]. + */ + fun from(action: String?, data: String?, open: String?, tagTexts: List? = null): LaunchRequest? { + if (open == OPEN_RECEIVE) return Receive + val input = when (action) { + Intent.ACTION_VIEW -> data + NfcAdapter.ACTION_NDEF_DISCOVERED -> tagInput(data, tagTexts) + else -> null + } + if (input.isNullOrBlank()) return null + val scheme = input.substringBefore(':', missingDelimiterValue = "").lowercase() + return if (scheme in SEND_SCHEMES) Send(input) else null + } + + /** + * The payment request of a tapped tag, read as the phone reads one: the one request its records hold, + * [NdefCodec.payableText], or [data], the first record as Android hands it over, when the intent came + * without the tag's message; then the phone's rewrite and refusal, [nfcPaymentRequest]. Null, so nothing + * opens, for a tag with several different requests or with a required parameter no flow fulfils. + */ + internal fun tagInput(data: String?, tagTexts: List?): String? { + val text = if (tagTexts != null) NdefCodec.payableText(tagTexts) else data + return text?.takeIf { it.isNotBlank() }?.let(::nfcPaymentRequest) + } + + fun from(intent: Intent?): LaunchRequest? = + intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN), it.tagTexts()) } + + /** The texts of the records of the tag that sent this intent, or null when it carries no tag message. */ + private fun Intent.tagTexts(): List? { + if (action != NfcAdapter.ACTION_NDEF_DISCOVERED) return null + val messages = runCatching { + IntentCompat.getParcelableArrayExtra(this, NfcAdapter.EXTRA_NDEF_MESSAGES, NdefMessage::class.java) + }.getOrNull() + if (messages.isNullOrEmpty()) return null + return messages.filterIsInstance().flatMap { NdefCodec.decodeTexts(it.toByteArray()) } + } + } +} + +/** + * Whether an intent with [flags] is one Android replays from Recents: the link or the tile's request that once + * opened the app, sent again long after the wearer saw it. Such an intent is a plain launch, whatever it asks for. + */ +fun isReplayedLaunch(flags: Int): Boolean = flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 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..bbbb4a3df1 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt @@ -1,23 +1,37 @@ package to.bitkit.wear.ui +import android.content.Intent +import android.nfc.NfcAdapter +import android.nfc.Tag 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.SideEffect 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.clearAndSetSemantics import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.core.content.IntentCompat import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.foundation.LocalAmbientModeManager import androidx.wear.compose.foundation.rememberAmbientModeManager import androidx.wear.compose.material3.AppScaffold import dagger.hilt.android.AndroidEntryPoint +import to.bitkit.wear.data.AmbientMonitor +import to.bitkit.wear.nfc.NfcRepeatGuard import to.bitkit.wear.ui.components.BezelLoading +import to.bitkit.wear.ui.components.SendOutcomeOverlay +import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.screens.start.StartErrorScreen import to.bitkit.wear.ui.theme.BitkitWearTheme +import javax.inject.Inject import kotlin.time.Duration.Companion.seconds import kotlin.time.TimeSource @@ -28,11 +42,27 @@ class MainActivity : ComponentActivity() { private val SPLASH_LIMIT = 1.seconds } + @Inject + lateinit var ambientMonitor: AmbientMonitor + + /** Decides what a link or a tap may open; one for the process, so it never depends on this instance. */ + @Inject + lateinit var launchGate: LaunchGate + 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) + + /** Whether a tag opened or reached the app, so the next resume holds the reader against its repeats. */ + private var guardNfcOnResume = false + private var nfcTagToGuard: Tag? = null + override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) + // A recreated activity has shown its intent's request already, and so has one opened again from Recents. + if (savedInstanceState == null && !isReplayedLaunch(intent.flags)) handleLaunch(intent) val splashStart = TimeSource.Monotonic.markNow() splashScreen.setKeepOnScreenCondition { startViewModel.uiState.value.isStarting && splashStart.elapsedNow() < SPLASH_LIMIT @@ -40,13 +70,31 @@ class MainActivity : ComponentActivity() { setContent { BitkitWearTheme { CompositionLocalProvider(LocalAmbientModeManager provides rememberAmbientModeManager()) { + val isAmbient = isAmbient() + SideEffect { ambientMonitor.set(isAmbient) } AppScaffold( modifier = Modifier.semantics { testTagsAsResourceId = true // see https://github.com/appium/appium/issues/15138 } ) { val uiState by startViewModel.uiState.collectAsStateWithLifecycle() - uiState.startRoute?.let { WearNavHost(startRoute = it) } + // The overlay comes with the start screen, whichever it is: without a wallet it has + // nothing to show, as the repository empties its queue for a wallet that is gone. + uiState.startRoute?.let { + val outcomeViewModel = hiltViewModel() + val outcomeState by outcomeViewModel.uiState.collectAsStateWithLifecycle() + val isOutcomeShown = outcomeState.outcome != null && !isAmbient + WearNavHost( + startRoute = it, + launchRequest = launchRequest, + onLaunchRequestHandle = { launchRequest = null }, + isSendUnderWay = { launchGate.isSending }, + // A screen reader gets only the outcome while it covers the screen beneath, whose + // actions it could otherwise still run unseen. + modifier = if (isOutcomeShown) Modifier.clearAndSetSemantics {} else Modifier + ) + SendOutcomeOverlay(viewModel = outcomeViewModel) + } if (uiState.isStarting) BezelLoading() if (uiState.isRecoveryFailed) { StartErrorScreen( @@ -60,6 +108,40 @@ class MainActivity : ComponentActivity() { } } + /** Where a link or a tap reaches the running app: `singleTask` keeps one activity in one task. */ + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + if (isReplayedLaunch(intent.flags)) return + handleLaunch(intent) + } + + override fun onDestroy() { + NfcRepeatGuard.disengage(this) + super.onDestroy() + } + + override fun onResume() { + super.onResume() + if (!guardNfcOnResume) return + guardNfcOnResume = false + NfcRepeatGuard.engage(this, nfcTagToGuard) + nfcTagToGuard = null + } + + /** + * Takes what [intent] asks for, as far as [LaunchGate] lets it through. A tapped tag's intent also arms the + * repeat guard for the next resume, as on the phone. + */ + private fun handleLaunch(intent: Intent) { + val isTap = intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED + if (isTap) { + guardNfcOnResume = true + nfcTagToGuard = IntentCompat.getParcelableExtra(intent, NfcAdapter.EXTRA_TAG, Tag::class.java) + } + launchGate.admit(LaunchRequest.from(intent), isTap = isTap, tapData = intent.dataString) + ?.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..b94f317772 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,28 @@ 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}" + + /** The one-line refusal of a tapped NFC tag without a payment request the watch takes. */ + const val TAG_REFUSED = "tag_refused" + + /** 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/SendOutcomeViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/SendOutcomeViewModel.kt new file mode 100644 index 0000000000..b88c2e0957 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/SendOutcomeViewModel.kt @@ -0,0 +1,96 @@ +package to.bitkit.wear.ui + +import androidx.compose.runtime.Immutable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import to.bitkit.wear.data.AmbientMonitor +import to.bitkit.wear.data.ForegroundMonitor +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.repositories.SendOutcomeRepo +import to.bitkit.wear.security.DeviceLock +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.screens.home.bitcoinAmount +import javax.inject.Inject +import kotlin.time.Duration.Companion.seconds + +/** + * Shows, one at a time and for [SHOWN_FOR] each, how the payments ended that the watch reported as pending or + * unknown ([SendOutcomeRepo.outcomes]). An outcome shows only to a wearer who can see it: with the app on screen, + * out of ambient mode and with the watch unlocked, as the lock screen covers the app without stopping it. It never + * shows over a send that is under way, nor over a screen it must not cover ([SendMonitor.isOutcomeHeld]): a send + * flow past its start, or the receive QR. Until then it waits, and one that was cut short shows again in full. + * Only an outcome that showed for its whole time is forgotten. + */ +@HiltViewModel +class SendOutcomeViewModel @Inject constructor( + private val sendOutcomeRepo: SendOutcomeRepo, + private val settingsStore: SettingsStore, + foregroundMonitor: ForegroundMonitor, + ambientMonitor: AmbientMonitor, + deviceLock: DeviceLock, + sendMonitor: SendMonitor, +) : ViewModel() { + companion object { + /** How long an outcome shows. */ + val SHOWN_FOR = 2.seconds + } + + private val _uiState = MutableStateFlow(SendOutcomeUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + init { + viewModelScope.launch { + val isSeen = combine( + foregroundMonitor.isForeground, + ambientMonitor.isAmbient, + deviceLock.isLocked, + ) { isForeground, isAmbient, isLocked -> isForeground && !isAmbient && !isLocked } + combine( + sendOutcomeRepo.outcomes, + isSeen, + sendMonitor.isSending, + sendMonitor.isOutcomeHeld, + ) { outcomes, isSeen, isSending, isHeld -> + outcomes.firstOrNull().takeIf { isSeen && !isSending && !isHeld } + }.distinctUntilChanged().collectLatest { outcome -> + if (outcome == null) { + _uiState.update { it.copy(outcome = null) } + return@collectLatest + } + val unit = runSuspendCatching { settingsStore.data.first().displayUnit } + .getOrDefault(BitcoinDisplayUnit.MODERN) + val amount = bitcoinAmount(outcome.amountSats.toLong(), unit) + _uiState.update { it.copy(outcome = ShownOutcome(outcome.id, outcome.isSent, amount)) } + delay(SHOWN_FOR) + sendOutcomeRepo.consume(outcome.id) + } + } + } +} + +/** The outcome of the payment [id] as the overlay shows it: sent ([isSent]) or failed, with its [amount]. */ +@Immutable +data class ShownOutcome( + val id: String, + val isSent: Boolean, + val amount: DisplayAmount, +) + +@Immutable +data class SendOutcomeUiState( + val outcome: ShownOutcome? = null, +) 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..97a5983857 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,40 @@ 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.send.TagRefusedScreen 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, + isSendUnderWay: () -> Boolean = { false }, ) { val navController = rememberSwipeDismissableNavController() var isRestoreSaving by remember { mutableStateOf(false) } + var isSending by remember { mutableStateOf(false) } + val currentOnLaunchRequestHandle by rememberUpdatedState(onLaunchRequestHandle) + val currentIsSendUnderWay by rememberUpdatedState(isSendUnderWay) + 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. + // The process is asked too, as the screen's own state follows a send that just started by a frame. + if (isSending || currentIsSendUnderWay()) { + Logger.info("Dropped launch request '${request::class.simpleName}' during a send", context = TAG) + return@LaunchedEffect + } + navController.showLaunchRequest(request) + } SwipeDismissableNavHost( navController = navController, startDestination = startRoute, - userSwipeEnabled = !isRestoreSaving, + userSwipeEnabled = !isRestoreSaving && !isSending, modifier = modifier ) { composable(Routes.ONBOARDING) { @@ -55,6 +79,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 +89,31 @@ 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(Routes.TAG_REFUSED) { + TagRefusedScreen(onClose = { navController.popBackStack(Routes.TAG_REFUSED, inclusive = true) }) + } + 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 +180,28 @@ private fun NavController.showRestoreWord(index: Int) { } } +/** + * Opens what [request] asks for above Home: the send flow of a deeplink or a tapped tag, the tile's receive QR, or + * the refusal of a tag the watch does not take. 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 + 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) + LaunchRequest.TagRefused -> navigateTo(Routes.TAG_REFUSED) + } +} + +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/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/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/NfcHint.kt b/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt index fc7811f125..da7141eb77 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt @@ -26,6 +26,9 @@ 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.unit.Dp +import androidx.compose.ui.unit.coerceAtLeast +import androidx.compose.ui.unit.coerceIn import androidx.compose.ui.unit.dp import androidx.wear.compose.material3.Icon import kotlinx.coroutines.Dispatchers @@ -39,8 +42,8 @@ import to.bitkit.wear.ui.theme.Colors /** The hint's icon size. */ private val HINT_SIZE = 24.dp -/** The extra touch area around the disabled hint, which makes it a 48dp target without moving the icon. */ -private val DISABLED_TOUCH_PADDING = 12.dp +/** The touch target of the disabled hint; the area around the icon is added without moving the icon. */ +private val DISABLED_TOUCH_SIZE = 48.dp /** The side of the viewport of `ic_broadcast`, whose path data [BroadcastPaths] holds. */ private const val VIEWPORT = 16f @@ -91,46 +94,76 @@ fun nfcHintState(nfc: NfcState, isWalletReady: Boolean, isAmbient: Boolean): Nfc * loop; only their alpha animates. When animations are off it is the still icon; that setting is read off the main * thread each time the hint appears, and the icon is still until then. With NFC off it is the still icon, * dimmed and slashed, and a tap on it opens the NFC settings through [onDisabledClick]. + * + * The Balance page shows it for paying by tap; the receive QR shows it at another [size], with its own + * [activeDescription] and test tags, while the watch offers the invoice as a tag. The disabled icon sits where the + * active one does when both are aligned by their bottom edge: its touch area reaches below it, by + * [disabledTouchBelow] when given, for a hint so near the screen's edge that the full area would leave the screen. */ @Composable fun NfcHint( state: NfcHintState, onDisabledClick: () -> Unit, modifier: Modifier = Modifier, + size: Dp = HINT_SIZE, + activeDescription: String = stringResource(R.string.home__nfc_hint), + activeTag: String = "NfcHint", + disabledTag: String = "NfcHintDisabled", + disabledTouchBelow: Dp? = null, ) { when (state) { NfcHintState.Hidden -> Unit - NfcHintState.Active -> ActiveHint(modifier = modifier) - NfcHintState.Disabled -> DisabledHint(onClick = onDisabledClick, modifier = modifier) + NfcHintState.Active -> ActiveHint( + description = activeDescription, + hintSize = size, + tag = activeTag, + modifier = modifier + ) + NfcHintState.Disabled -> DisabledHint( + size = size, + tag = disabledTag, + touchBelow = disabledTouchBelow, + onClick = onDisabledClick, + modifier = modifier + ) } } @Composable private fun DisabledHint( + size: Dp, + tag: String, + touchBelow: Dp?, onClick: () -> Unit, modifier: Modifier = Modifier, ) { - val description = stringResource(R.string.home__nfc_off) + val touchPadding = ((DISABLED_TOUCH_SIZE - size) / 2).coerceAtLeast(0.dp) + val paddingBelow = touchBelow?.coerceIn(0.dp, touchPadding) ?: touchPadding Icon( painter = painterResource(R.drawable.ic_broadcast_off), - contentDescription = description, + contentDescription = stringResource(R.string.home__nfc_off), tint = Colors.White32, modifier = modifier - .offset(y = DISABLED_TOUCH_PADDING) - .clickableAlpha(onClickLabel = description, onClick = onClick) - .padding(DISABLED_TOUCH_PADDING) - .size(HINT_SIZE) - .testTag("NfcHintDisabled") + .offset(y = paddingBelow) + // The label says what the tap does: the description alone would read as turning NFC off. + .clickableAlpha(onClickLabel = stringResource(R.string.nfc__open_settings), onClick = onClick) + .padding(start = touchPadding, top = touchPadding, end = touchPadding, bottom = paddingBelow) + .size(size) + .testTag(tag) ) } @Composable -private fun ActiveHint(modifier: Modifier = Modifier) { - val description = stringResource(R.string.home__nfc_hint) +private fun ActiveHint( + description: String, + hintSize: Dp, + tag: String, + modifier: Modifier = Modifier, +) { val hintModifier = modifier - .size(HINT_SIZE) + .size(hintSize) .semantics { contentDescription = description } - .testTag("NfcHint") + .testTag(tag) val context = LocalContext.current val isStill by produceState(initialValue = true) { value = withContext(Dispatchers.IO) { context.areAnimationsDisabled } diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/NfcTagEffect.kt b/wear/src/main/java/to/bitkit/wear/ui/components/NfcTagEffect.kt new file mode 100644 index 0000000000..ea27b1ec71 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/NfcTagEffect.kt @@ -0,0 +1,85 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.compose.LocalActivity +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import to.bitkit.wear.nfc.CardEmulationTagRoute +import to.bitkit.wear.nfc.NfcTagOffer +import to.bitkit.wear.nfc.TagRoute +import to.bitkit.wear.utils.Logger + +private const val TAG = "NfcTagEffect" + +/** + * Offers [uri] to NFC readers as a tag while the calling screen is resumed, so only while it is the screen in front + * of an app in the foreground, and stops when it pauses, leaves or [uri] changes or turns null. [onOfferChange] + * tells whether a reader can read the tag right now. [isCurrent] is asked each time the offer starts, also on a + * return to the screen, and a request that is no longer current, as an invoice that expired while the watch slept, + * is not offered. The watch's counterpart of the phone's `NfcEmitterEffect`. + */ +@Composable +fun NfcTagEffect( + uri: String?, + onOfferChange: (Boolean) -> Unit, + isCurrent: () -> Boolean = { true }, +) { + val activity = LocalActivity.current ?: return + val route = remember(activity) { CardEmulationTagRoute(activity) } + NfcTagEffect(uri = uri, route = route, onOfferChange = onOfferChange, isCurrent = isCurrent) +} + +@Composable +internal fun NfcTagEffect( + uri: String?, + route: TagRoute, + onOfferChange: (Boolean) -> Unit, + isCurrent: () -> Boolean = { true }, +) { + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnOfferChange by rememberUpdatedState(onOfferChange) + val currentIsCurrent by rememberUpdatedState(isCurrent) + + DisposableEffect(route, lifecycleOwner, uri) { + if (uri.isNullOrBlank()) return@DisposableEffect onDispose {} + val offer = NfcTagOffer(route) + + fun start() { + if (!currentIsCurrent()) { + Logger.debug("Kept back an NFC tag whose request is no longer current", context = TAG) + offer.stop() + currentOnOfferChange(false) + return + } + val isOffered = offer.start(uri) + Logger.debug("Started the NFC tag, offered '$isOffered'", context = TAG) + currentOnOfferChange(isOffered) + } + + fun stop() { + if (offer.isOffered) Logger.debug("Stopped the NFC tag", context = TAG) + offer.stop() + currentOnOfferChange(false) + } + + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> start() + Lifecycle.Event.ON_PAUSE -> stop() + else -> Unit + } + } + // A new observer is sent the events up to the current state, so a resumed screen starts here. + lifecycleOwner.lifecycle.addObserver(observer) + + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + stop() + } + } +} 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/java/to/bitkit/wear/ui/components/SendOutcomeOverlay.kt b/wear/src/main/java/to/bitkit/wear/ui/components/SendOutcomeOverlay.kt new file mode 100644 index 0000000000..3740739472 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/SendOutcomeOverlay.kt @@ -0,0 +1,116 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +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.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.paneTitle +import androidx.compose.ui.semantics.testTag +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.MaterialTheme +import to.bitkit.wear.R +import to.bitkit.wear.ui.SendOutcomeViewModel +import to.bitkit.wear.ui.ShownOutcome +import to.bitkit.wear.ui.screens.home.DisplayAmount +import to.bitkit.wear.ui.theme.Colors + +private val OUTCOME_ICON_SIZE = 48.dp + +/** + * Tells, over whatever screen is up, how a payment ended that the watch had reported as pending or unknown: a check + * for one that was sent or a cross for one that failed, with its amount and a haptic, for a moment. It is no screen + * and takes no action: touches and Back do nothing until it is gone. To a screen reader it is one line, such + * as "Sent, ₿ 1 000", and a pane with that title, so that it is said when it appears (not tried with TalkBack on a + * watch yet); the caller hides the screen beneath from it meanwhile. Nothing shows in ambient + * mode, where the outcome waits for the watch to wake. + */ +@Composable +fun SendOutcomeOverlay( + modifier: Modifier = Modifier, + viewModel: SendOutcomeViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val outcome = uiState.outcome ?: return + if (isAmbient()) return + val haptic = LocalHapticFeedback.current + LaunchedEffect(outcome.id) { + haptic.performHapticFeedback(if (outcome.isSent) HapticFeedbackType.Confirm else HapticFeedbackType.Reject) + } + BackHandler {} + OutcomeContent(outcome = outcome, modifier = modifier) +} + +@Composable +internal fun OutcomeContent( + outcome: ShownOutcome, + modifier: Modifier = Modifier, +) { + val description = stringResource( + R.string.send__outcome_description, + stringResource(if (outcome.isSent) R.string.send__sent else R.string.send__error_failed), + "${outcome.amount.symbol} ${outcome.amount.text}", + ) + val tag = if (outcome.isSent) "WatchOutcomeSent" else "WatchOutcomeFailed" + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), + modifier = modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) awaitPointerEvent().changes.forEach { it.consume() } + } + } + // One node with the status and the amount, which the icon alone would not say. It is a pane with that + // title, as a screen reader is told of a pane that appears and of its title changing, while a live + // region is announced only on a node that was already there. The tag sits here too, as the children's + // own semantics are dropped. + .clearAndSetSemantics { + testTag = tag + contentDescription = description + paneTitle = description + } + ) { + Icon( + painter = painterResource(if (outcome.isSent) R.drawable.ic_check else R.drawable.ic_close), + contentDescription = null, + tint = if (outcome.isSent) Colors.Brand else MaterialTheme.colorScheme.error, + modifier = Modifier.size(OUTCOME_ICON_SIZE) + ) + SmallAmountRow(amount = outcome.amount, amountTag = "WatchOutcomeAmount") + } +} + +@WearPreviewDevices +@Composable +private fun PreviewSent() { + WearPreview { + OutcomeContent(outcome = ShownOutcome("id", isSent = true, DisplayAmount(symbol = "₿", text = "21 000"))) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewFailed() { + WearPreview { + OutcomeContent(outcome = ShownOutcome("id", isSent = false, DisplayAmount(symbol = "₿", text = "21 000"))) + } +} 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..366b3e8d12 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt @@ -0,0 +1,145 @@ +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.BitcoinDisplayUnit +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 +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) + if (payment == null) { + Missing(isLoading = !uiState.isLoaded, modifier = modifier) + return + } + Content(payment = payment, unit = uiState.unit, 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, + unit: BitcoinDisplayUnit, + isAmbient: Boolean, + modifier: Modifier = Modifier, +) { + CenteredScreen(modifier = modifier) { + if (!isAmbient) { + BoxWithConstraints(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) { + LargeAmountRow( + amount = bitcoinAmount(payment.amountSats.toLong(), unit), + maxWidth = maxWidth, + amountTag = "WatchActivityDetailAmount", + symbolTag = "WatchActivityDetailSymbol", + ) + } + } + if (payment.isSent && payment.feeSats > 0uL && !isAmbient) { + val fee = bitcoinAmount(payment.feeSats.toLong(), unit) + 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, unit = BitcoinDisplayUnit.MODERN, 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..7c6a2b5ec1 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt @@ -0,0 +1,229 @@ +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.runtime.produceState +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 kotlinx.coroutines.delay +import to.bitkit.wear.R +import to.bitkit.wear.models.BITCOIN_SYMBOL +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PaymentState +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.models.formatMoney +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 +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 + +/** 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. + */ +@Composable +fun ActivityScreen( + onPaymentClick: (String) -> Unit, + modifier: Modifier = Modifier, + viewModel: ActivityViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + Content( + 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, + 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(uiState.unit), maxLines = 2) }, + 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(unit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN): String { + val sign = if (isSent) "-" else "+" + return "$sign $BITCOIN_SYMBOL ${amountSats.toLong().formatMoney(unit)}" +} + +/** 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 +internal 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..153dc1c507 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt @@ -0,0 +1,89 @@ +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.data.SettingsStore +import to.bitkit.wear.models.BitcoinDisplayUnit +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 settingsStore: SettingsStore, + private val nowSecs: () -> Long, +) : ViewModel() { + @Inject + constructor( + paymentsRepo: PaymentsRepo, + walletRepo: WalletRepo, + settingsStore: SettingsStore, + ) : this(paymentsRepo, walletRepo, settingsStore, { Instant.now().epochSecond }) + + private val _uiState = MutableStateFlow(ActivityUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + init { + viewModelScope.launch { + settingsStore.data.map { it.displayUnit }.distinctUntilChanged().collect { unit -> + _uiState.update { it.copy(unit = unit) } + } + } + 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, + /** How bitcoin amounts are written, as on the phone. */ + val unit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN, +) { + fun payment(id: String): WatchPayment? = payments.firstOrNull { it.id == id } +} 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/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/home/HomeViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt index 309c86280e..718438ce48 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 @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import to.bitkit.wear.data.AmbientMonitor import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.NetworkMonitor import to.bitkit.wear.data.NfcMonitor @@ -22,13 +23,15 @@ import to.bitkit.wear.data.NfcState import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings import to.bitkit.wear.models.BITCOIN_SYMBOL +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.FxRate import to.bitkit.wear.models.PrimaryDisplay import to.bitkit.wear.models.fiatValue import to.bitkit.wear.models.formatCurrency -import to.bitkit.wear.models.formatToModernDisplay +import to.bitkit.wear.models.formatMoney import to.bitkit.wear.models.isSymbolSuffix import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus @@ -42,7 +45,9 @@ import kotlin.time.Duration.Companion.seconds /** * The home screen's state, and what keeps it fresh while Home is open: it starts the wallet and fetches the exchange * rates when the app comes on screen and every [RATES_REFRESH_INTERVAL] from then, when the wallet becomes ready, - * and when the network returns while there are no rates yet. + * and when the network returns while there are no rates yet. It imports the phone's settings each time the wallet + * is ready with the app on screen and not in ambient mode, so at every start and return, and every + * [SETTINGS_SYNC_INTERVAL] from then; [SettingsSyncRepo.sync] skips an import that follows another too closely. */ @HiltViewModel class HomeViewModel @Inject constructor( @@ -52,6 +57,8 @@ class HomeViewModel @Inject constructor( nfcMonitor: NfcMonitor, networkMonitor: NetworkMonitor, foregroundMonitor: ForegroundMonitor, + private val settingsSyncRepo: SettingsSyncRepo, + ambientMonitor: AmbientMonitor, ) : ViewModel() { companion object { private const val TAG = "HomeViewModel" @@ -61,6 +68,9 @@ class HomeViewModel @Inject constructor( /** How often the exchange rates are fetched again while the app is on screen. */ val RATES_REFRESH_INTERVAL = 5.minutes + + /** How often the phone's settings are imported again while the wallet is ready and the app in use. */ + val SETTINGS_SYNC_INTERVAL = 5.minutes } val uiState: StateFlow = combine( @@ -90,6 +100,20 @@ class HomeViewModel @Inject constructor( .drop(1) .collect { isReady -> if (isReady) fetchRates() } } + viewModelScope.launch { + combine( + foregroundMonitor.isForeground, + walletRepo.walletState.map { it.status == WalletStatus.Ready }, + ambientMonitor.isAmbient, + ) { isForeground, isReady, isAmbient -> isForeground && isReady && !isAmbient } + .distinctUntilChanged() + .collectLatest { canSync -> + while (canSync) { + settingsSyncRepo.sync() + delay(SETTINGS_SYNC_INTERVAL) + } + } + } viewModelScope.launch { // Only a change counts as the network returning, so the value at the start is skipped. networkMonitor.isOnline.drop(1).collect { isOnline -> @@ -133,14 +157,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, settings.displayUnit, 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 +174,25 @@ internal fun homeUiState( ) } +/** [sats] in bitcoin, written in [unit], as the balance shows it. */ +fun bitcoinAmount( + sats: Long, + unit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN, + locale: Locale = Locale.getDefault(), +): DisplayAmount = DisplayAmount(BITCOIN_SYMBOL, sats.formatMoney(unit, 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, 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..91bff85e26 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt @@ -0,0 +1,464 @@ +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 +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +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.LocalContext +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.LifecycleResumeEffect +import androidx.lifecycle.compose.LifecycleStartEffect +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 kotlinx.coroutines.delay +import to.bitkit.wear.R +import to.bitkit.wear.data.NfcState +import to.bitkit.wear.ext.openNfcSettings +import to.bitkit.wear.ui.components.BezelLoading +import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.NfcHint +import to.bitkit.wear.ui.components.NfcHintState +import to.bitkit.wear.ui.components.NfcTagEffect +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 +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 + +/** 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 + +/** 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 NFC hint's size below the QR: it fits the strip the QR leaves free on the smallest round screen. */ +private val NFC_HINT_SIZE = 20.dp + +/** + * The request the watch offers as an NFC tag, or null when it offers none: the invoice the QR shows right now, so + * not in ambient mode, not while the QR rests and not once paid, with NFC on and on a watch that can act as a tag. + * Nor while the repeat guard holds reader mode after a tap, [isReaderHeld], since no reader reaches the watch's tag + * meanwhile. [ReceiveUiState.nfcUri] is already null unless the wallet is ready and the invoice is current. + */ +internal fun receiveTagUri( + uiState: ReceiveUiState, + nfc: NfcState, + hasCardEmulation: Boolean, + isAmbient: Boolean, + isResting: Boolean, + isReaderHeld: Boolean = false, +): String? { + val isQrShown = uiState.qrContent != null && uiState.paidAmount == null && !isAmbient && !isResting + val canOffer = isQrShown && hasCardEmulation && nfc == NfcState.On && !isReaderHeld + return uiState.nfcUri?.takeIf { canOffer && it.isNotBlank() } +} + +/** + * The NFC hint below the QR: animated while the tag is offered, [isOffered]; dimmed and slashed when only NFC being + * off keeps the invoice on screen from being offered; hidden otherwise, as without NFC hardware, in ambient mode, + * while the QR rests, while the repeat guard holds reader mode, or when the tag could not be registered. + */ +internal fun receiveNfcHintState( + uiState: ReceiveUiState, + nfc: NfcState, + hasCardEmulation: Boolean, + isAmbient: Boolean, + isResting: Boolean, + isOffered: Boolean, + isReaderHeld: Boolean = false, +): NfcHintState { + fun tagUri(nfc: NfcState) = receiveTagUri(uiState, nfc, hasCardEmulation, isAmbient, isResting, isReaderHeld) + return when { + nfc == NfcState.Off && tagUri(NfcState.On) != null -> NfcHintState.Disabled + isOffered && tagUri(nfc) != null -> NfcHintState.Active + else -> NfcHintState.Hidden + } +} + +/** + * 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, 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. + * + * While the QR shows, the watch also offers the invoice as an NFC tag, as the phone's Receive does, with the NFC + * hint below the QR: see [receiveTagUri]. + */ +@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) + } + 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 } + val nfc by viewModel.nfcState.collectAsStateWithLifecycle() + val hasCardEmulation by viewModel.hasCardEmulation.collectAsStateWithLifecycle() + val isReaderHeld by viewModel.isReaderHeld.collectAsStateWithLifecycle() + // The watch may have slept past the invoice's expiry: the view model reads the clock when the screen is back. + LifecycleResumeEffect(viewModel) { + viewModel.onShow() + onPauseOrDispose {} + } + LaunchedEffect(isAmbient) { if (!isAmbient) viewModel.onShow() } + // The outcome of an earlier payment waits until this screen is left, so it never covers the QR. + LifecycleStartEffect(viewModel) { + viewModel.onShownChange(true) + onStopOrDispose { viewModel.onShownChange(false) } + } + var isTagOffered by remember { mutableStateOf(false) } + NfcTagEffect( + uri = receiveTagUri(uiState, nfc, hasCardEmulation, isAmbient, isResting, isReaderHeld), + isCurrent = viewModel::isTagCurrent, + onOfferChange = { isTagOffered = it }, + ) + val context = LocalContext.current + ReceiveQrContent( + uiState = uiState, + isAmbient = isAmbient, + isResting = isResting, + nfcHint = receiveNfcHintState( + uiState = uiState, + nfc = nfc, + hasCardEmulation = hasCardEmulation, + isAmbient = isAmbient, + isResting = isResting, + isOffered = isTagOffered, + isReaderHeld = isReaderHeld, + ), + onNfcSettingsClick = context::openNfcSettings, + onQrTouch = { touches++ }, + onShowClick = { + isResting = false + viewModel.onShow() + }, + onRefreshClick = viewModel::onRefreshClick, + modifier = modifier + ) +} + +@Composable +internal fun ReceiveQrContent( + uiState: ReceiveUiState, + isAmbient: Boolean, + onRefreshClick: () -> Unit, + modifier: Modifier = Modifier, + isResting: Boolean = false, + nfcHint: NfcHintState = NfcHintState.Hidden, + onQrTouch: () -> Unit = {}, + onShowClick: () -> Unit = {}, + onNfcSettingsClick: () -> Unit = {}, +) { + val qrContent = uiState.qrContent + val paidAmount = uiState.paidAmount + when { + 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, + nfcHint = nfcHint, + onTouch = onQrTouch, + onNfcSettingsClick = onNfcSettingsClick, + 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, + nfcHint: NfcHintState, + onTouch: () -> Unit, + onNfcSettingsClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val currentOnTouch by rememberUpdatedState(onTouch) + ScreenAwake(isBright = true) + BoxWithConstraints( + contentAlignment = Alignment.Center, + 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() + } + } + ) { + val screenSize = minOf(maxWidth, maxHeight) + val qrSize = screenSize * QR_SIZE_FRACTION + QrCode( + content = content, + contentDescription = stringResource(R.string.receive__title), + modifier = Modifier + .size(qrSize) + .testTag("WatchReceiveQr") + ) + // Centred in the strip between the QR's square, quiet zone included, and the bottom of the screen. The + // disabled hint's touch area ends at the screen's edge below it; above it reaches into the QR's square, by + // about its quiet zone on the smallest screen, where a touch does nothing else. + val strip = (screenSize - qrSize) / 2 + NfcHint( + state = nfcHint, + onDisabledClick = onNfcSettingsClick, + size = NFC_HINT_SIZE, + disabledTouchBelow = (strip - NFC_HINT_SIZE) / 2, + activeDescription = stringResource(R.string.receive__nfc_hint), + activeTag = "WatchReceiveNfc", + disabledTag = "WatchReceiveNfcOff", + modifier = Modifier + .align(Alignment.BottomCenter) + .offset(y = -(strip - NFC_HINT_SIZE) / 2) + ) + } +} + +@Composable +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 + .clickableAlpha(onClickLabel = showLabel, enabled = onClick != null, onClick = { onClick?.invoke() }) + .semantics { contentDescription = description } + .testTag("WatchReceiveHidden") + ) { + QrIcon() + } +} + +@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, +) { + val isDimmed = amount == null + 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 = if (isDimmed) Colors.White.copy(alpha = HIDDEN_ALPHA) else Colors.Brand, + modifier = Modifier.size(MARK_SIZE) + ) + amount?.let { SmallAmountRow(amount = it, 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 { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewNfc() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + nfcHint = NfcHintState.Active, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewNfcOff() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + nfcHint = NfcHintState.Disabled, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewPaid() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "21 000")), + isAmbient = false, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewPaidAmbient() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "21 000")), + isAmbient = true, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewAmbient() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = true, + onRefreshClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewResting() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + isResting = true, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewError() { + WearPreview { + ReceiveQrContent( + 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..512f15cb9d --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveScreen.kt @@ -0,0 +1,62 @@ +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.semantics.clearAndSetSemantics +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 = 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 {} + ) + } +} + +@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..35fddf99d2 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt @@ -0,0 +1,308 @@ +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.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +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.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.NfcMonitor +import to.bitkit.wear.data.NfcState +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.env.Env +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.ReceiveInvoice +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.nfc.NfcRepeatGuard +import to.bitkit.wear.nfc.NfcTagEmitter +import to.bitkit.wear.nfc.nfcPaymentUri +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 +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 and still watched until it expires; a paid one, shown or + * replaced, turns into a check until the wearer asks for a new invoice. + * + * The invoice on screen is also what the watch may offer as an NFC tag, [ReceiveUiState.nfcUri]: only while the + * wallet is ready and only until the invoice expires by the watch's clock, so a tag never carries a stale or a paid + * invoice. The screen decides whether it is offered at all (see `receiveTagUri`). + * + * The timers here count the time the watch is awake, which stands still while it sleeps, so the expiry is also read + * from the wall clock, [nowSecs]: whenever the tag's request is published, when the screen starts to offer it + * ([isTagCurrent]), and when the screen shows again ([onShow]), which replaces an invoice that expired meanwhile + * and sets the timers of one that did not to what the wall clock leaves of them. + */ +@HiltViewModel +class ReceiveViewModel internal constructor( + private val paymentsRepo: PaymentsRepo, + private val walletRepo: WalletRepo, + private val settingsStore: SettingsStore, + nfcMonitor: NfcMonitor, + private val sendMonitor: SendMonitor, + private val nowSecs: () -> Long, + private val revokeTag: () -> Unit = NfcTagEmitter::revoke, +) : 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 + + /** + * 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 + + /** How long after a failure the replacement of an invoice that is still valid is tried again. */ + val RETRY_DELAY = 5.seconds + } + + @Inject + constructor( + paymentsRepo: PaymentsRepo, + walletRepo: WalletRepo, + settingsStore: SettingsStore, + nfcMonitor: NfcMonitor, + sendMonitor: SendMonitor, + ) : this(paymentsRepo, walletRepo, settingsStore, nfcMonitor, sendMonitor, { Instant.now().epochSecond }) + + private val _uiState = MutableStateFlow(ReceiveUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + /** Whether NFC is on, for the hint beside the QR. */ + val nfcState: StateFlow = nfcMonitor.state + + /** Whether the watch can act as an NFC tag at all. */ + val hasCardEmulation: StateFlow = nfcMonitor.hasCardEmulation + + /** Whether the repeat guard holds reader mode after a tap, which keeps every reader from the watch's tag. */ + val isReaderHeld: StateFlow = NfcRepeatGuard.isHeld + + private var job: Job? = null + + /** Asks the rotation and the tag to read the wall clock again: see [onShow]. */ + private val clockChecks = MutableSharedFlow(extraBufferCapacity = 1) + + init { + refresh() + } + + private var holdsOutcomes = false + + /** + * The screen's back stack entry started or stopped. While it shows, the outcome of an earlier payment waits + * ([SendMonitor.isOutcomeHeld]): it would cover the QR a payer is scanning, or read as this invoice's own check. + */ + fun onShownChange(isShown: Boolean) { + if (isShown == holdsOutcomes) return + holdsOutcomes = isShown + if (isShown) sendMonitor.holdOutcomes() else sendMonitor.releaseOutcomes() + } + + override fun onCleared() = onShownChange(false) + + /** Makes a new invoice: after an error, and after the last one was paid. */ + fun onRefreshClick() = refresh() + + /** + * The screen shows again, after the app returned, ambient mode ended or the wearer asked for the QR: the watch + * may have slept past the invoice's expiry, so its tag request goes at once and the rotation replaces the + * invoice now. An invoice that is not due yet has its timers set again from the wall clock. + */ + fun onShow() { + _uiState.update { if (it.nfcUri != null && !isCurrent(it.expiresAtSecs)) it.copy(nfcUri = null) else it } + clockChecks.tryEmit(Unit) + } + + /** + * Whether the invoice on screen still has a tag request and has not expired by the watch's clock; asked + * whenever its tag starts, so a request that was taken away a frame ago, as a paid one, is not started again. + */ + fun isTagCurrent(): Boolean = _uiState.value.let { it.nfcUri != null && isCurrent(it.expiresAtSecs) } + + private fun isCurrent(expiresAtSecs: Long?): Boolean = expiresAtSecs != null && nowSecs() < expiresAtSecs + + private fun refresh() { + job?.cancel() + job = viewModelScope.launch { + _uiState.update { ReceiveUiState(isLoading = true) } + val paid = CompletableDeferred() + val watcherScope = this + val rotation = launch { rotate(watcherScope, paid) } + val payment = paid.await() + // Paid: the tag goes first, before anything here suspends, so a paid invoice is never offered. It is + // also taken from the NFC service here, a frame before the screen stops the offer: whatever it holds, + // since only this screen publishes, and it may still hold the request of an invoice just replaced. + coroutineContext.cancelChildren() + revokeTag() + _uiState.update { it.copy(nfcUri = null) } + rotation.join() + Logger.info("Received payment '${payment.id}'", context = TAG) + val unit = runSuspendCatching { settingsStore.data.first().displayUnit } + .getOrDefault(BitcoinDisplayUnit.MODERN) + _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(payment.amountSats.toLong(), unit)) } + } + } + + /** + * 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) { + var tag: Job? = null + 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) + // The replaced invoice's tag ends before the new invoice shows, so the tag is never behind the QR. + tag?.cancelAndJoin() + val expiresAtSecs = invoice.expiresAtSecs.toLong() + _uiState.update { ReceiveUiState(qrContent = invoice.bolt11.uppercase(), expiresAtSecs = expiresAtSecs) } + val expiresIn = (expiresAtSecs - nowSecs()).seconds + tag = watcherScope.launch { offerTag(invoice, expiresIn, paid) } + val lifetime = (expiresIn - EXPIRY_MARGIN).coerceAtLeast(MIN_LIFETIME) + watcherScope.launch { + withTimeoutOrNull(expiresIn.coerceAtLeast(lifetime + EXPIRY_MARGIN)) { paymentsRepo.awaitPaid(invoice) } + ?.let { paid.complete(it) } + } + awaitWallClock(untilSecs = nowSecs() + lifetime.inWholeSeconds, timeout = lifetime) + Logger.debug("Replacing invoice '${invoice.paymentHash}' before it expires", context = TAG) + // An invoice the watch slept past is not shown while its replacement is made. + val isExpired = nowSecs() >= expiresAtSecs && expiresIn > Duration.ZERO + _uiState.update { if (isExpired) ReceiveUiState(isLoading = true) else it.copy(isLoading = true) } + } + } + + /** + * Waits [timeout], which ends at [untilSecs] on the wall clock. The timeout stands still while the watch sleeps, + * so at every [clockChecks] it is set again to what the wall clock leaves of it, and a watch that woke before + * [untilSecs] and stays awake still returns on time. + */ + private suspend fun awaitWallClock(untilSecs: Long, timeout: Duration) { + var left = timeout + while (left > Duration.ZERO) { + withTimeoutOrNull(left) { clockChecks.first() } ?: return + left = (untilSecs - nowSecs()).seconds + } + } + + /** + * Keeps [ReceiveUiState.nfcUri] at [invoice]'s request while that invoice is the one on screen, the wallet is + * ready and the invoice has not expired, by [expiresIn] set again from the wall clock (see [awaitWallClock]) + * and by the wall clock at every publish, and takes it away at the first of them that ends. A wallet that was + * not ready may have been paid meanwhile, so the request returns only after Spark's list was read and shows no + * payment; one it shows completes [paid]. + */ + private suspend fun offerTag( + invoice: ReceiveInvoice, + expiresIn: Duration, + paid: CompletableDeferred, + ) { + val uri = nfcPaymentUri(invoice.bolt11) ?: return + val qrContent = invoice.bolt11.uppercase() + fun set(value: String?) = _uiState.update { if (it.qrContent == qrContent) it.copy(nfcUri = value) else it } + var wasAway = false + try { + coroutineScope { + val offer = launch { + walletRepo.walletState.map { it.status == WalletStatus.Ready } + .distinctUntilChanged() + .collectLatest { isReady -> + if (!isReady) { + wasAway = true + set(null) + return@collectLatest + } + if (wasAway) { + // A list that cannot be read keeps the tag away until the wallet is ready anew. + val receipt = paymentsRepo.findPaid(invoice).getOrElse { return@collectLatest } + if (receipt != null) { + paid.complete(receipt) + return@collectLatest + } + wasAway = false + } + set(uri.takeIf { isCurrent(invoice.expiresAtSecs.toLong()) }) + } + } + awaitWallClock(untilSecs = invoice.expiresAtSecs.toLong(), timeout = expiresIn) + offer.cancel() + } + } finally { + set(null) + } + } + + /** + * 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. */ + private suspend fun create(): Result { + walletRepo.walletState.first { it.status == WalletStatus.Ready } + return paymentsRepo.createInvoice() + } +} + +@Immutable +data class ReceiveUiState( + /** The uppercased invoice the QR shows, or null while there is none to show. */ + val qrContent: String? = null, + /** + * The request of the invoice in [qrContent] as the watch's NFC tag offers it, `lightning:` and the invoice, or + * null while it must not be offered: the wallet is not ready, or the invoice expired. + */ + val nfcUri: String? = null, + /** When the invoice in [qrContent] expires, in epoch seconds. */ + val expiresAtSecs: Long? = 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..9980b663f7 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -0,0 +1,669 @@ +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.DisposableEffect +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.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.onLongClick +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +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.LifecycleStartEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.EdgeButton +import androidx.wear.compose.material3.EdgeButtonSize +import androidx.wear.compose.material3.Icon +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.isAmbient +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, 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. */ +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. 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; a pending or unknown result stays readable there, without + * its amount. + */ +@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() + } + } + } + // A flow that left the back stack, as for a new link or tap, is stopped at once and pays nothing under QuickPay. + LifecycleStartEffect(viewModel) { + viewModel.onShownChange(true) + onStopOrDispose { viewModel.onShownChange(false) } + } + 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 + // Keyed by the result too, so a pending payment that turns sent or failed while it shows is felt again. + LaunchedEffect((step as? SendStep.Done)?.result, step is SendStep.Failed, step is SendStep.Offline) { + when (step) { + is SendStep.Done if step.result == SendResult.Sent -> + haptic.performHapticFeedback(HapticFeedbackType.Confirm) + // Softer than the other two: the payment is under way, neither done nor refused. + is SendStep.Done -> haptic.performHapticFeedback(HapticFeedbackType.ContextClick) + is SendStep.Failed, SendStep.Offline -> haptic.performHapticFeedback(HapticFeedbackType.Reject) + else -> Unit + } + } + BackHandler(enabled = uiState.isBusy) {} + Content( + uiState = uiState, + isAmbient = isAmbient(), + onAmountChange = viewModel::onAmountChange, + onAmountConfirm = viewModel::onAmountConfirm, + onHoldComplete = viewModel::onHoldComplete, + onCloseClick = viewModel::onCloseClick, + modifier = modifier + ) +} + +/** + * What a tapped NFC tag without a payment request the watch takes ends on: one line and its close, as the send + * flow's own refusals, since Android already brought the app to the front for the tag. + */ +@Composable +fun TagRefusedScreen( + onClose: () -> Unit, + modifier: Modifier = Modifier, +) { + val haptic = LocalHapticFeedback.current + LaunchedEffect(Unit) { haptic.performHapticFeedback(HapticFeedbackType.Reject) } + StatusScreen( + icon = R.drawable.ic_close, + tint = MaterialTheme.colorScheme.error, + text = stringResource(R.string.send__error_unsupported), + textTag = "WatchTagRefused", + textStyle = MaterialTheme.typography.titleSmall, + amount = null, + onCloseClick = onClose, + modifier = modifier + ) +} + +@Composable +internal fun Content( + uiState: SendUiState, + isAmbient: Boolean, + onAmountChange: (String) -> Unit, + onAmountConfirm: () -> Unit, + onHoldComplete: () -> Unit, + onCloseClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val step = uiState.step + // The always-on screen shows no amount, typed, reviewed or sent, and nothing to hold. + val isSent = step is SendStep.Done && step.result == SendResult.Sent + if (isAmbient && (step is SendStep.Amount || step is SendStep.Review || isSent)) { + Hidden(modifier = modifier) + return + } + when (step) { + SendStep.Loading -> Loading(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, + isConnecting = !uiState.isWalletReady, + onHoldComplete = onHoldComplete, + modifier = modifier + ) + is SendStep.Sending -> Sending(isWaiting = step.isWaiting, modifier = modifier) + is SendStep.Done, is SendStep.Failed, SendStep.Offline -> Ended( + step = step, + isAmountShown = !isAmbient, + onCloseClick = onCloseClick, + modifier = modifier + ) + } +} + +@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(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") + ) + } +} + +@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 +internal fun Review( + step: SendStep.Review, + isHoldEnabled: 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( + // A tap never pays: only the hold that rememberHoldToPayState follows does. + onClick = {}, + enabled = isHoldEnabled, + buttonSize = EdgeButtonSize.Medium, + interactionSource = holdState.interactionSource, + 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, or its long click: a double tap + // and hold. + if (isHoldEnabled) { + val pay = { + onHoldComplete() + true + } + customActions = listOf(CustomAccessibilityAction(payLabel, pay)) + onLongClick(label = payLabel, action = pay) + } + } + ) { + Text(stringResource(R.string.send__hold)) + } + }, + overlay = { if (isConnecting) BezelLoading() else 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}"), + // The fee is never cut: in bitcoin with its eight decimals a long translation wraps instead. + maxLines = 2, + modifier = Modifier.testTag("WatchSendFee") + ) + } + step.payee?.let { Line(text = it, 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")) + } + } +} + +/** + * How the flow ended: a result, or a refusal with the one action that closes the flow. Every end is drawn from this + * one place, so that a pending payment that turns sent or failed changes the line that is already there: a screen + * reader is told of a live region that changes, not of one that only appears. + */ +@Composable +private fun Ended( + step: SendStep, + isAmountShown: Boolean, + onCloseClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val result = (step as? SendStep.Done)?.result + val (icon, text, tag) = when (step) { + is SendStep.Done -> when (step.result) { + SendResult.Sent -> Triple(R.drawable.ic_check, R.string.send__sent, "WatchSendSent") + SendResult.Pending -> Triple(R.drawable.ic_schedule, R.string.send__pending, "WatchSendPending") + SendResult.Unknown -> Triple(R.drawable.ic_schedule, R.string.send__unknown, "WatchSendUnknown") + } + is SendStep.Failed -> Triple(R.drawable.ic_close, step.failure.text, "WatchSendError") + else -> Triple(R.drawable.ic_cloud_off, R.string.send__error_offline, "WatchSendOfflineError") + } + StatusScreen( + icon = icon, + tint = when (result) { + SendResult.Sent -> Colors.Brand + null -> MaterialTheme.colorScheme.error + else -> Colors.White64 + }, + text = stringResource(text), + textTag = tag, + textStyle = if (result == null) MaterialTheme.typography.titleSmall else MaterialTheme.typography.titleMedium, + amount = (step as? SendStep.Done)?.amount.takeIf { isAmountShown && result != SendResult.Unknown }, + onCloseClick = onCloseClick.takeIf { result == null }, + modifier = modifier + ) +} + +/** [icon] and the one line [text], with the [amount] of a result or, for a refusal, the action that closes it. */ +@Composable +private fun StatusScreen( + @DrawableRes icon: Int, + tint: Color, + text: String, + textTag: String, + textStyle: TextStyle, + amount: DisplayAmount?, + onCloseClick: (() -> Unit)?, + modifier: Modifier = Modifier, +) { + CenteredScreen( + edgeButton = onCloseClick?.let { onClick -> + { + EdgeButton( + onClick = onClick, + buttonSize = EdgeButtonSize.Medium, + modifier = Modifier.testTag("WatchSendClose") + ) { + Text(stringResource(R.string.common__ok)) + } + } + }, + modifier = modifier + ) { + StatusIcon(icon = icon, tint = tint) + Text( + text = text, + style = textStyle, + textAlign = TextAlign.Center, + modifier = Modifier + .testTag(textTag) + .announced() + ) + amount?.let { SmallAmountRow(amount = it, amountTag = "WatchSendResultAmount") } + } +} + +/** + * Has a screen reader say the line when its text changes, as a result that nothing else would tell its wearer: a + * pending payment that turns sent or failed changes the screen under them without a touch. + */ +private fun Modifier.announced(): Modifier = semantics { liveRegion = LiveRegionMode.Polite } + +@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 Line( + text: String, + modifier: Modifier = Modifier, + color: Color = Colors.White64, + maxLines: Int = 1, +) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = color, + textAlign = TextAlign.Center, + maxLines = maxLines, + overflow = TextOverflow.Ellipsis, + modifier = modifier + ) +} + +@WearPreviewDevices +@Composable +private fun PreviewReview() { + WearPreview { + Content( + uiState = SendUiState(step = PreviewReviewStep, isWalletReady = true), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewOffline() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Offline), + 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 = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewAmount() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Amount(minSats = 1uL, maxSats = 100_000uL), amountText = "2100"), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewSending() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Sending(isWaiting = true)), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewSent() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Done(SendResult.Sent, PreviewBitcoin)), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewPending() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Done(SendResult.Pending, PreviewBitcoin)), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewFailed() { + WearPreview { + Content( + uiState = SendUiState(step = SendStep.Failed(SendFailure.OwnInvoice)), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewTagRefused() { + WearPreview { + TagRefusedScreen(onClose = {}) + } +} + +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..99c4b9f21c --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -0,0 +1,564 @@ +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.Job +import kotlinx.coroutines.awaitCancellation +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.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.R +import to.bitkit.wear.data.AmbientMonitor +import to.bitkit.wear.data.ElapsedClock +import to.bitkit.wear.data.ForegroundMonitor +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BitcoinDisplayUnit +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.SendOutcomeRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.security.DeviceLock +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] lets it out under QuickPay, straight from pricing to sending, + * and the result closes the flow by itself. A payment that Spark took and that has not settled shows as pending for + * [PENDING_CLOSE_DELAY]; an outcome that arrives meanwhile replaces it at once, and a later one is told by the app's + * outcome overlay ([SendOutcomeRepo]). The flow itself starts only once the wearer was shown how every earlier + * payment ended ([SendOutcomeRepo.awaitTold]), under its loading ring, so the end of an old payment never follows + * the result of a new one; from then on, while its screen shows, no outcome covers it + * ([SendMonitor.isOutcomeHeld]). + * 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. A send that finds the wallet not ready after + * all, as one that raced a disconnect, sent nothing: the flow returns to the review, with the hold off until the + * wallet is ready again. + * + * QuickPay is asked only for a send the wearer is there for: one priced within [QUICKPAY_WINDOW] of its link, with + * the app on screen, out of ambient mode and the watch unlocked all the while. A link that waited longer for the + * wallet, as while it connects, or across a lock, a pause or ambient mode, always ends on the review and the hold, + * so nothing is ever paid long after the wearer looked away. Nor is a flow whose screen is no longer shown, as + * one that a new link, tap or tile request just took off the back stack: it never pays unseen. A wallet that turns + * offline during that wait ends the flow as above, with no QuickPay and no review. Only the first flow of a link + * asks: one that Android builds again for the same link, as after the process was killed and the back stack + * restored, finds its mark in the saved state and ends on the review. + */ +@HiltViewModel +class SendViewModel @Inject constructor( + savedStateHandle: SavedStateHandle, + private val paymentsRepo: PaymentsRepo, + private val walletRepo: WalletRepo, + private val currencyRepo: CurrencyRepo, + private val settingsStore: SettingsStore, + private val foregroundMonitor: ForegroundMonitor, + private val ambientMonitor: AmbientMonitor, + private val sendMonitor: SendMonitor, + private val sendOutcomeRepo: SendOutcomeRepo, + private val deviceLock: DeviceLock, + private val clock: ElapsedClock, +) : ViewModel() { + companion object { + private const val TAG = "SendViewModel" + + /** How long a send waits on the network before the screen says it is waiting for it. */ + 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, and waits for the outcome, before the flow closes. */ + val PENDING_CLOSE_DELAY = 5.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 + + /** + * How long after its link arrived a send may still go out under QuickPay: long enough for a wallet that + * connects and syncs as the link opens the app, and short enough that the wearer still looks at it. + */ + val QUICKPAY_WINDOW = 30.seconds + + /** The saved state's mark that a flow already ran for this link, so a rebuilt one never asks QuickPay. */ + const val KEY_STARTED = "send_started" + } + + 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 + private var unit = BitcoinDisplayUnit.MODERN + + /** Reads, prices and shows the request before the send; cancelled when the wallet goes offline. */ + private var flow: Job? = null + + /** When the link arrived, on [clock]. */ + private val arrivedAtMs = clock.nowMs() + + /** + * Whether the wearer was away at some time since the link arrived: see [isAttended]. It never turns back, and a + * flow rebuilt for a link that already had one starts with it set, however long ago the link arrived. + */ + @Volatile + private var wasAway = savedStateHandle.get(KEY_STARTED) == true + + /** + * Whether this flow's screen is shown: its back stack entry is started. A view model is made as its screen + * shows, and lives a moment longer than an entry that was popped: see [onShownChange]. + */ + @Volatile + private var isShown = true + + /** Whether the flow is past its start, where the outcomes of earlier payments are told: see [awaitOutcomesTold]. */ + private var isPastStart = false + + /** Whether this flow keeps outcomes from showing right now: see [updateOutcomeHold]. */ + private var holdsOutcomes = false + + /** Whether the wallet was seen out of [WalletStatus.Paused], which it may be in only while the app returns. */ + private var hasLeftPause = false + + init { + savedStateHandle[KEY_STARTED] = true + flow = viewModelScope.launch { start() } + viewModelScope.launch { + combine( + walletRepo.walletState, + foregroundMonitor.isForeground, + ambientMonitor.isAmbient, + ) { wallet, isForeground, isAmbient -> Triple(wallet.status, isForeground, isAmbient) } + .collect { (status, isForeground, isAmbient) -> + val isPausedAgain = status == WalletStatus.Paused && hasLeftPause + if (status != WalletStatus.Paused) hasLeftPause = true + if (!isThere(status, isForeground, isAmbient) || isPausedAgain) wasAway = true + } + } + viewModelScope.launch { + walletRepo.walletState.collect { wallet -> + _uiState.update { it.copy(isWalletReady = wallet.status == WalletStatus.Ready) } + if (wallet.status == WalletStatus.Offline) dropOffline() + } + } + } + + /** + * The screen's back stack entry started or stopped. A stopped one asks no QuickPay, so a flow that another + * request replaced cannot pay in the moment before its view model is cleared. Nor does it keep an outcome from + * showing over the screen that took its place. + */ + fun onShownChange(isShown: Boolean) { + this.isShown = isShown + updateOutcomeHold() + } + + override fun onCleared() { + isShown = false + updateOutcomeHold() + } + + /** Keeps outcomes from showing while this flow's screen shows and is past its start, and no longer. */ + private fun updateOutcomeHold() { + val isWanted = isShown && isPastStart + if (isWanted == holdsOutcomes) return + holdsOutcomes = isWanted + if (isWanted) sendMonitor.holdOutcomes() else sendMonitor.releaseOutcomes() + } + + /** + * Waits, under the loading ring, until the wearer was shown how every earlier payment ended, and from then on + * keeps outcomes from showing over this flow. An outcome that arrived between the two is waited for as well. + */ + private suspend fun awaitOutcomesTold() { + while (true) { + sendOutcomeRepo.awaitTold() + isPastStart = true + updateOutcomeHold() + if (sendOutcomeRepo.outcomes.value.isEmpty()) return + isPastStart = false + updateOutcomeHold() + } + } + + 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 + } + flow = 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) + } + + /** + * 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 + // The refusal is this flow's own end, also for a flow that still waited at its start. + isPastStart = true + updateOutcomeHold() + _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() { + // The wait for the outcomes can outlast the wallet, as when the watch is turned away meanwhile: nothing is + // read or priced until both hold at once. + while (true) { + walletRepo.walletState.first { it.status == WalletStatus.Ready } + awaitOutcomesTold() + if (walletRepo.walletState.value.status == WalletStatus.Ready) break + isPastStart = false + updateOutcomeHold() + } + val parsed = paymentsRepo.parse(input).getOrElse { + fail(it) + return + } + request = parsed + if (parsed.fixedAmountSats == null) { + show(amountStep(parsed)) + return + } + prepare(parsed, amountSats = null) + } + + private suspend fun prepare(request: SendRequest, amountSats: ULong?) { + show(SendStep.Loading) + unit = runSuspendCatching { settingsStore.data.first().displayUnit }.getOrDefault(BitcoinDisplayUnit.MODERN) + val result = paymentsRepo.prepare(request, amountSats).getOrElse { + if (it is SendError.AmountOutOfRange && request.fixedAmountSats == null) { + show(amountStep(request).copy(isOutOfRange = true)) + } else { + fail(it) + } + return + } + if (_uiState.value.step is SendStep.Offline) return + prepared = result + // Asked last and only when it can apply, since a yes is counted against the day's limit. The wearer may + // have looked away while it was answered, hence the second look, which the repo takes before it says yes. + if (isQuickPayOpen() && paymentsRepo.skipConfirmation(result, ::canQuickPay)) { + Logger.info("Skipped the hold to pay under QuickPay", context = TAG) + send(result) + return + } + show(review(result, request)) + } + + /** Whether QuickPay may be asked for a send priced now: see the class. */ + private fun isQuickPayOpen(): Boolean = + canQuickPay() && clock.nowMs() - arrivedAtMs in 0..QUICKPAY_WINDOW.inWholeMilliseconds + + /** + * Whether this flow is shown, the wearer is there and the wallet is not offline, by its status now and by a + * request already dropped for it, which nothing pays later. + */ + private fun canQuickPay(): Boolean = isShown && isAttended() && + walletRepo.walletState.value.status != WalletStatus.Offline && + _uiState.value.step !is SendStep.Offline + + /** + * Whether the wearer was there since the link arrived and still is: the app on screen, not in ambient mode, the + * watch never locked, and the wallet never paused after it ran. + */ + private fun isAttended(): Boolean = !wasAway && isThere( + walletRepo.walletState.value.status, + foregroundMonitor.isForeground.value, + ambientMonitor.isAmbient.value, + ) + + private fun isThere(status: WalletStatus, isForeground: Boolean, isAmbient: Boolean): Boolean = + isForeground && !isAmbient && status != WalletStatus.Locked + + 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, unit), + fiat = fiatAmount(amount, currencyRepo.rates.value, currency), + fee = if (isFeeShown) bitcoinAmount(prepared.feeSats.toLong(), unit) else null, + payee = (prepared.payee ?: request.payee)?.takeIf { it.isNotBlank() }, + ) + } + + private fun send(prepared: PreparedSend) { + _uiState.update { it.copy(step = SendStep.Sending()) } + viewModelScope.launch { + // The sync before the send waits on the network, and so does a send whose wallet went offline. With + // the wallet online and the payment handed to Spark, the ring says the rest. + val hint = launch { + delay(WAITING_HINT_DELAY) + combine(sendMonitor.isSyncing, walletRepo.walletState) { isSyncing, wallet -> + isSyncing || wallet.status == WalletStatus.Offline + }.collect { isWaiting -> + _uiState.update { state -> + val step = state.step as? SendStep.Sending ?: return@update state + state.copy(step = step.copy(isWaiting = isWaiting)) + } + } + } + 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) { + val error = result.exceptionOrNull() + if (error is SendError.NotReady) reconnect(prepared) else fail(error) + return@launch + } + Logger.info("Finished send with outcome '$outcome'", context = TAG) + // The amount Spark paid, which is an earlier send's when the request was already sent at another amount. + val paymentId = result.getOrNull()?.id ?: (result.exceptionOrNull() as? SendError.Unknown)?.paymentId + finish(outcome, result.getOrNull()?.amountSats ?: prepared.amountSats, paymentId) + } + } + + /** + * Back to the review of [prepared] after a send that found the wallet not ready: nothing was sent, and the + * wearer is not left on an error for a wallet that is only connecting again. The hold stays off, under the + * loading ring, while the wallet starts again; a wallet that turns out to be offline ends the flow as always. + */ + private suspend fun reconnect(prepared: PreparedSend) { + val request = request + if (request == null) { + fail(SendError.NotReady()) + return + } + Logger.info("Returned to the review to wait for the wallet", context = TAG) + val review = review(prepared, request) + _uiState.update { if (it.step is SendStep.Offline) it else it.copy(step = review, isWalletReady = false) } + walletRepo.start() + _uiState.update { it.copy(isWalletReady = walletRepo.walletState.value.status == WalletStatus.Ready) } + } + + /** + * Shows [result] with [amountSats] and then closes the flow. A result other than sent waits, while it shows, + * for the outcome of the payment [paymentId]: sent replaces it, with the amount Spark paid, and so does failed, + * which stays until the wearer closes it. An outcome nobody would read here, in ambient mode, with the app off + * screen, with the watch locked or with this flow's screen no longer shown, is left to the app's overlay, which + * shows it once the wearer is back. + */ + private suspend fun finish(result: SendResult, amountSats: ULong?, paymentId: String? = null) { + showDone(result, amountSats) + if (result == SendResult.Sent) { + delay(SENT_CLOSE_DELAY) + _effects.send(SendEffect.Close) + return + } + val outcome = withTimeoutOrNull(PENDING_CLOSE_DELAY) { + if (paymentId == null) awaitCancellation() else sendOutcomeRepo.awaitLive(paymentId) + } + val isRead = isShown && foregroundMonitor.isForeground.value && !ambientMonitor.isAmbient.value && + !deviceLock.isLocked.value + when { + outcome == null -> Unit + !isRead -> sendOutcomeRepo.enqueue(outcome) + outcome.isSent -> { + Logger.info("Switched a pending send to sent", context = TAG) + showDone(SendResult.Sent, outcome.amountSats) + sendOutcomeRepo.consume(outcome.id) + delay(SENT_CLOSE_DELAY) + } + else -> { + Logger.info("Switched a pending send to failed", context = TAG) + show(SendStep.Failed(SendFailure.Failed)) + sendOutcomeRepo.consume(outcome.id) + return + } + } + _effects.send(SendEffect.Close) + } + + private fun showDone(result: SendResult, amountSats: ULong?) { + val amount = amountSats?.let { bitcoinAmount(it.toLong(), unit) } + _uiState.update { it.copy(step = SendStep.Done(result, amount)) } + } + + /** + * Shows why nothing was sent. A payment of this request that Spark lists as under way is no failure: it shows as + * pending, with the amount of that payment when Spark lists it, also when it was found before the review. 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, error.amountSats ?: prepared?.amountSats, error.paymentId) + return + } + show(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] while it waits on the network for longer than a moment: for its sync with + * Spark, or with the wallet offline. + */ + data class Sending(val isWaiting: Boolean = false) : SendStep + + /** + * 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. A sent and a pending payment show their [amount], which is null when it is not + * known. + */ + data class Done(val result: SendResult, val amount: DisplayAmount?) : 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 } + +/** 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), + 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), + Busy(R.string.send__error_busy), + 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.Busy -> Busy + 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, +) { + /** 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/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt index ef73968884..ba1e9ae17e 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt @@ -1,5 +1,6 @@ package to.bitkit.wear.ui.screens.settings +import android.text.format.DateUtils import androidx.annotation.DrawableRes import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize @@ -30,6 +31,7 @@ import to.bitkit.wear.ui.components.BezelLoading 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.screens.activity.rememberNowSecs @Composable fun SettingsScreen( @@ -38,9 +40,13 @@ fun SettingsScreen( viewModel: SettingsViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() + // Moves on every minute, so the import's age also grows while the page stays open. + val syncedSecs = (uiState.phoneSyncedAtMs ?: 0) / DateUtils.SECOND_IN_MILLIS Content( uiState = uiState, + nowMs = rememberNowSecs(loadedSecs = syncedSecs) * DateUtils.SECOND_IN_MILLIS, onAboutClick = onAboutClick, + onSyncClick = viewModel::onSyncClick, onRemoveClick = viewModel::onRemoveClick, onRemoveConfirm = viewModel::onRemoveConfirm, onRemoveDismiss = viewModel::onRemoveDismiss, @@ -51,7 +57,9 @@ fun SettingsScreen( @Composable private fun Content( uiState: SettingsUiState, + nowMs: Long, onAboutClick: () -> Unit, + onSyncClick: () -> Unit, onRemoveClick: () -> Unit, onRemoveConfirm: () -> Unit, onRemoveDismiss: () -> Unit, @@ -79,6 +87,42 @@ private fun Content( .testTag("WatchSettingsAbout") ) } + item { + FilledTonalButton( + onClick = onSyncClick, + enabled = !uiState.isSyncing && !uiState.isRemoving, + icon = { RowIcon(R.drawable.ic_sync) }, + label = { Text(stringResource(R.string.settings__phone_settings)) }, + secondaryLabel = uiState.phoneSyncedAtMs?.let { syncedAtMs -> + { + Text( + text = syncedAgo(syncedAtMs, nowMs), + maxLines = 1, + modifier = Modifier.testTag("WatchSettingsSyncTime") + ) + } + }, + transformation = SurfaceTransformation(spec), + modifier = Modifier + .fillMaxWidth() + .transformedHeight(this, spec) + .testTag("WatchSettingsSync") + ) + } + if (uiState.isSyncFailed) { + item { + Text( + text = stringResource(R.string.settings__phone_settings_failed), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .transformedHeight(this, spec) + .testTag("WatchSettingsSyncFailed") + ) + } + } item { FilledTonalButton( onClick = onRemoveClick, @@ -111,7 +155,7 @@ private fun Content( } } } - if (uiState.isRemoving) BezelLoading() + if (uiState.isRemoving || uiState.isSyncing) BezelLoading() } AlertDialog( visible = uiState.isRemoveDialogVisible, @@ -133,6 +177,14 @@ private fun Content( ) } +/** How long before [nowMs] the phone's settings were imported; a time ahead of it counts as now. */ +private fun syncedAgo(syncedAtMs: Long, nowMs: Long): String = DateUtils.getRelativeTimeSpanString( + syncedAtMs.coerceAtMost(nowMs), + nowMs, + DateUtils.MINUTE_IN_MILLIS, + DateUtils.FORMAT_ABBREV_RELATIVE, +).toString() + @Composable private fun RowIcon( @DrawableRes id: Int, @@ -146,8 +198,10 @@ private fun RowIcon( private fun Preview() { WearPreview { Content( - uiState = SettingsUiState(), + uiState = SettingsUiState(phoneSyncedAtMs = 0, isSyncFailed = true), + nowMs = 120_000, onAboutClick = {}, + onSyncClick = {}, onRemoveClick = {}, onRemoveConfirm = {}, onRemoveDismiss = {}, @@ -161,7 +215,9 @@ private fun PreviewRemoveConfirm() { WearPreview { Content( uiState = SettingsUiState(isRemoveDialogVisible = true), + nowMs = 0, onAboutClick = {}, + onSyncClick = {}, onRemoveClick = {}, onRemoveConfirm = {}, onRemoveDismiss = {}, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt index 1e646b76ba..0ca553a1d4 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt @@ -7,18 +7,45 @@ import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val walletRepo: WalletRepo, + private val settingsSyncRepo: SettingsSyncRepo, + settingsStore: SettingsStore, ) : ViewModel() { private val _uiState = MutableStateFlow(SettingsUiState()) val uiState: StateFlow = _uiState.asStateFlow() + init { + viewModelScope.launch { + settingsStore.data.map { it.phoneSyncedAtMs }.distinctUntilChanged().collect { syncedAtMs -> + _uiState.update { it.copy(phoneSyncedAtMs = syncedAtMs) } + } + } + } + + /** + * Imports the phone's settings now, from the row that shows when they were last imported. The wearer asked, so + * it reads also right after another import, and a failure shows. + */ + fun onSyncClick() { + if (_uiState.value.isSyncing) return + _uiState.update { it.copy(isSyncing = true, isSyncFailed = false) } + viewModelScope.launch { + settingsSyncRepo.sync(isForced = true).onFailure { _uiState.update { it.copy(isSyncFailed = true) } } + _uiState.update { it.copy(isSyncing = false) } + } + } + fun onRemoveClick() { _uiState.update { it.copy(isRemoveDialogVisible = true, isRemoveFailed = false) } } @@ -46,4 +73,8 @@ data class SettingsUiState( val isRemoveDialogVisible: Boolean = false, val isRemoving: Boolean = false, val isRemoveFailed: Boolean = false, + val isSyncing: Boolean = false, + val isSyncFailed: Boolean = false, + /** When the phone's settings were last imported, in epoch milliseconds, or null when there is no import. */ + val phoneSyncedAtMs: Long? = null, ) 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_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 @@ + + + + + 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 @@ + + + + + diff --git a/wear/src/main/res/drawable/ic_sync.xml b/wear/src/main/res/drawable/ic_sync.xml new file mode 100644 index 0000000000..3a9cc0a862 --- /dev/null +++ b/wear/src/main/res/drawable/ic_sync.xml @@ -0,0 +1,11 @@ + + + + + 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/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index d77908a7e0..18fcf93f9f 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -1,6 +1,13 @@ حول + لا يوجد نشاط + تم الاستلام + تم الإرسال + مكتمل + فشل + معلق + النشاط التالي حسنًا إعادة المحاولة @@ -10,7 +17,16 @@ NFC متوقف غير متصل تبديل الوحدة + فتح إعدادات NFC + طلب دفع Bitkit استعادة + تعذّر إنشاء الفاتورة + رمز QR مخفي + فاتورة جديدة + انقر للاستلام + مدفوع + إظهار رمز QR + استلام تمت إزالة المحفظة مراجعة عبارة غير صالحة @@ -34,6 +50,30 @@ لا تطابق الكلمة %1$d %1$d/%2$d + متابعة + المبلغ + %1$s – %2$s + مدفوعة مسبقًا + المحفظة مشغولة + انتهت صلاحية الفاتورة + فشل الدفع + رصيد غير كافٍ + فاتورة غير صالحة + المحفظة غير جاهزة + خارج النطاق + لا يمكن الدفع دون اتصال + لا يمكن دفع فاتورتك + غير مدعوم + الرسوم %1$s + اضغط مطولًا للدفع + %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 4e53c73b69..c53dab797a 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 @@ -10,7 +17,16 @@ NFC desactivado Sin conexión Cambiar unidad + Abrir ajustes de NFC + Solicitud de pago de Bitkit Restaurar + No se creó la factura + QR oculto + Nueva factura + Toca para recibir + Pagado + Mostrar QR + Recibir Billetera eliminada Revisar Frase no válida @@ -31,6 +47,30 @@ Sin coincidencias Palabra %1$d %1$d/%2$d + Continuar + Monto + %1$s – %2$s + Ya pagada + Wallet ocupada + Factura vencida + Pago fallido + Fondos insuficientes + 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 + %1$s, %2$s + Pagar + Pendiente + Enviado + Revisa la actividad + Esperando la red + Ajustes del teléfono + No se pudo importar 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..80aa892a73 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 @@ -10,7 +17,16 @@ NFC desactivat Sense connexió Canvia la unitat + Obre la configuració de l\'NFC + Sol·licitud de pagament de Bitkit Restaurar + No s\'ha creat la factura + QR amagat + Nova factura + Toca per rebre + Pagat + Mostra el QR + Rebre Cartera eliminada Revisa Frase no vàlida @@ -31,6 +47,30 @@ Cap coincidència Paraula %1$d %1$d/%2$d + Continua + Import + %1$s – %2$s + Ja pagada + Wallet ocupada + Factura caducada + El pagament ha fallat + Fons insuficients + 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 + %1$s, %2$s + Paga + Pendent + Enviat + Revisa l\'activitat + Esperant la xarxa + Configuració del telèfon + No s\'ha pogut importar 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..f1e0cb3fb1 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 @@ -10,7 +17,16 @@ NFC vypnuto Offline Přepnout jednotku + Otevřít nastavení NFC + Žádost o platbu Bitkit Obnovit + Fakturu nelze vytvořit + QR skryt + Nová faktura + Klepnutím přijměte + Zaplaceno + Zobrazit QR + Přijmout Peněženka odebrána Zkontrolovat Neplatná fráze @@ -32,6 +48,30 @@ Žádná shoda Slovo %1$d %1$d/%2$d + Pokračovat + Částka + %1$s – %2$s + Již zaplaceno + Peněženka je zaneprázdněna + Faktura vypršela + Platba selhala + Nedostatek prostředků + 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 + %1$s, %2$s + Zaplatit + Zpracovávání + Odesláno + Zkontrolujte aktivitu + Čekání na síť + Nastavení telefonu + Import se nezdařil 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..cad9a3be67 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 @@ -10,7 +17,16 @@ NFC aus Offline Einheit wechseln + NFC-Einstellungen öffnen + Bitkit-Zahlungsanforderung Wiederherstellen + Rechnung nicht erstellt + QR versteckt + Neue Rechnung + Zum Empfangen tippen + Bezahlt + QR anzeigen + Empfangen Wallet entfernt Prüfen Ungültige Phrase @@ -30,6 +46,30 @@ Kein Treffer Wort %1$d %1$d/%2$d + Weiter + Betrag + %1$s – %2$s + Bereits bezahlt + Wallet beschäftigt + Rechnung abgelaufen + Zahlung fehlgeschlagen + Nicht genug Guthaben + 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 + %1$s, %2$s + Bezahlen + Ausstehend + Gesendet + Aktivität prüfen + Warte auf Netzwerk + Telefon-Einstellungen + Import fehlgeschlagen 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..f80d5407a7 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -1,6 +1,13 @@ Σχετικά + Καμία δραστηριότητα + Ελήφθη + Στάλθηκε + Ολοκληρώθηκε + Απέτυχε + Εκκρεμεί + Δραστηριότητα Επόμενο ΟΚ Δοκιμάστε Ξανά @@ -10,7 +17,16 @@ NFC ανενεργό Εκτός σύνδεσης Αλλαγή μονάδας + Άνοιγμα ρυθμίσεων NFC + Αίτημα πληρωμής Bitkit Επαναφορά + Αποτυχία τιμολογίου + QR κρυφό + Νέο τιμολόγιο + Πατήστε για λήψη + Πληρώθηκε + Εμφάνιση QR + Λήψη Το πορτοφόλι αφαιρέθηκε Έλεγχος Μη έγκυρη φράση @@ -30,6 +46,30 @@ Καμία αντιστοιχία Λέξη %1$d %1$d/%2$d + Συνέχεια + Ποσό + %1$s – %2$s + Ήδη πληρωμένο + Το πορτοφόλι είναι απασχολημένο + Το τιμολόγιο έληξε + Η πληρωμή απέτυχε + Ανεπαρκές υπόλοιπο + Μη έγκυρο τιμολόγιο + Το πορτοφόλι δεν είναι έτοιμο + Εκτός ορίων + Δεν γίνεται πληρωμή εκτός σύνδεσης + Δικό σου τιμολόγιο + Δεν υποστηρίζεται + Χρέωση %1$s + Κράτα για πληρωμή + %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 e643f9068e..d94ea02061 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 @@ -10,7 +17,16 @@ NFC desactivado Sin conexión Cambiar unidad + Abrir ajustes de NFC + Solicitud de pago de Bitkit Restaurar + No se creó la factura + QR oculto + Nueva factura + Toca para recibir + Pagado + Mostrar QR + Recibir Cartera eliminada Revisar Frase no válida @@ -31,6 +47,30 @@ Sin coincidencias Palabra %1$d %1$d/%2$d + Continuar + Importe + %1$s – %2$s + Ya pagada + Wallet ocupada + Factura caducada + Pago fallido + Fondos insuficientes + 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 + %1$s, %2$s + Pagar + Pendiente + Enviado + Revisa la actividad + Esperando a la red + Ajustes del teléfono + No se pudo importar 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..d94ea02061 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 @@ -10,7 +17,16 @@ NFC desactivado Sin conexión Cambiar unidad + Abrir ajustes de NFC + Solicitud de pago de Bitkit Restaurar + No se creó la factura + QR oculto + Nueva factura + Toca para recibir + Pagado + Mostrar QR + Recibir Cartera eliminada Revisar Frase no válida @@ -31,6 +47,30 @@ Sin coincidencias Palabra %1$d %1$d/%2$d + Continuar + Importe + %1$s – %2$s + Ya pagada + Wallet ocupada + Factura caducada + Pago fallido + Fondos insuficientes + 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 + %1$s, %2$s + Pagar + Pendiente + Enviado + Revisa la actividad + Esperando a la red + Ajustes del teléfono + No se pudo importar 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..db0d89cd75 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 @@ -10,7 +17,16 @@ NFC désactivé Hors ligne Changer d\'unité + Ouvrir les réglages NFC + Demande de paiement Bitkit Restaurer + Facture non créée + QR masqué + Nouvelle facture + Touchez pour recevoir + Payé + Afficher le QR + Recevoir Wallet supprimé Vérifier Phrase invalide @@ -31,6 +47,30 @@ Aucune correspondance Mot %1$d %1$d/%2$d + Continuer + Montant + %1$s – %2$s + Déjà payée + Wallet occupé + Facture expirée + Échec du paiement + Fonds insuffisants + 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 + %1$s, %2$s + Payer + En attente + Envoyé + Voir l\'activité + En attente du réseau + Paramètres du téléphone + Échec de l\'importation 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..454a7ede8c 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 @@ -10,7 +17,16 @@ NFC disattivato Offline Cambia unità + Apri impostazioni NFC + Richiesta di pagamento Bitkit Ripristina + Fattura non creata + QR nascosto + Nuova fattura + Tocca per ricevere + Pagato + Mostra QR + Ricevi Portafoglio rimosso Rivedi Frase non valida @@ -31,6 +47,30 @@ Nessuna corrispondenza Parola %1$d %1$d/%2$d + Continua + Importo + %1$s – %2$s + Già pagata + Wallet occupato + Fattura scaduta + Pagamento fallito + Fondi insufficienti + Fattura non valida + Wallet non pronto + Fuori intervallo + Impossibile pagare offline + È la tua fattura + Non supportato + Commissione %1$s + Tieni premuto per pagare + %1$s, %2$s + Paga + In sospeso + Inviato + Controlla l\'attività + In attesa della rete + Impostazioni telefono + Importazione non riuscita 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..cc1b0c5a2e 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 @@ -10,7 +17,16 @@ NFC uit Offline Eenheid wisselen + NFC-instellingen openen + Bitkit-betaalverzoek Herstellen + Factuur niet gemaakt + QR verborgen + Nieuwe factuur + Tik om te ontvangen + Betaald + QR tonen + Ontvangen Wallet verwijderd Controleren Ongeldige zin @@ -30,6 +46,30 @@ Geen overeenkomst Woord %1$d %1$d/%2$d + Doorgaan + Bedrag + %1$s – %2$s + Al betaald + Wallet bezet + Factuur verlopen + Betaling mislukt + Onvoldoende saldo + Ongeldige factuur + Wallet niet gereed + Buiten bereik + Betalen kan niet offline + Eigen factuur + Niet ondersteund + Kosten %1$s + Houd vast om te betalen + %1$s, %2$s + Betalen + In behandeling + Verzonden + Bekijk activiteit + Wachten op netwerk + Telefooninstellingen + Importeren mislukt 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..e855bb5d05 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 @@ -10,7 +17,16 @@ NFC wyłączone Offline Zmień jednostkę + Otwórz ustawienia NFC + Żądanie płatności Bitkit Odzyskaj + Nie utworzono faktury + QR ukryty + Nowa faktura + Dotknij, aby odebrać + Opłacono + Pokaż QR + Odbierz Portfel usunięty Sprawdź Nieprawidłowa fraza @@ -32,6 +48,30 @@ Brak dopasowań Słowo %1$d %1$d/%2$d + Dalej + Kwota + %1$s – %2$s + Już opłacona + Portfel jest zajęty + Faktura wygasła + Płatność nieudana + Za mało środków + 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ć + %1$s, %2$s + Zapłać + Oczekuje + Wysłano + Sprawdź aktywność + Czekam na sieć + Ustawienia telefonu + Import nie powiódł się 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..40ff1f4193 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 @@ -10,7 +17,16 @@ NFC desligado Sem conexão Alternar unidade + Abrir configurações de NFC + Solicitação de pagamento Bitkit Restaurar + Invoice não criado + QR oculto + Novo invoice + Toque para receber + Pago + Mostrar QR + Receber Carteira removida Revisar Frase inválida @@ -31,6 +47,30 @@ Nenhuma correspondência Palavra %1$d %1$d/%2$d + Continuar + Valor + %1$s – %2$s + Já pago + Carteira ocupada + Invoice expirado + Pagamento falhou + Saldo insuficiente + 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 + %1$s, %2$s + Pagar + Pendente + Enviado + Veja a atividade + Aguardando a rede + Ajustes do celular + Não foi possível importar 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..0d1c2f04ff 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 @@ -10,7 +17,16 @@ NFC desligado Sem ligação Alternar unidade + Abrir definições de NFC + Pedido de pagamento Bitkit Restaurar + Fatura não criada + QR oculto + Nova fatura + Toque para receber + Pago + Mostrar QR + Receber Carteira removida Revisar Frase inválida @@ -31,6 +47,30 @@ Nenhuma correspondência Palavra %1$d %1$d/%2$d + Continuar + Montante + %1$s – %2$s + Já paga + Carteira ocupada + Fatura expirada + Pagamento falhou + Saldo insuficiente + 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 + %1$s, %2$s + Pagar + Pendente + Enviado + Veja a atividade + À espera da rede + Ajustes do telemóvel + Não foi possível importar 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..e09029d8e3 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -1,6 +1,13 @@ О приложении + Нет активности + Получено + Отправлено + Завершено + Ошибка + В ожидании + Активность Далее ОК Повторить @@ -10,7 +17,16 @@ NFC выключен Нет сети Сменить единицу + Открыть настройки NFC + Запрос на оплату Bitkit Восстановить + Счёт не создан + QR скрыт + Новый счёт + Коснитесь для получения + Оплачено + Показать QR + Получить Кошелёк удалён Проверить Неверная фраза @@ -32,6 +48,30 @@ Нет совпадений Слово %1$d %1$d/%2$d + Далее + Сумма + %1$s – %2$s + Уже оплачен + Кошелёк занят + Счёт истёк + Платёж не прошёл + Недостаточно средств + Неверный счёт + Кошелёк не готов + Вне диапазона + Нельзя платить офлайн + Это ваш счёт + Не поддерживается + Комиссия %1$s + Удерживайте для оплаты + %1$s, %2$s + Оплатить + В ожидании + Отправлено + Проверьте активность + Ожидание сети + Настройки телефона + Не удалось импортировать Удалить кошелёк Удалить кошелёк? Не удалось удалить кошелёк diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index ca2ea84874..62ada3d2c4 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 @@ -10,7 +17,16 @@ NFC off Offline Switch unit + Open NFC settings + Bitkit payment request Restore + Couldn\'t create invoice + QR hidden + New invoice + Tap to receive + Paid + Show QR + Receive Wallet removed Review Invalid phrase @@ -30,6 +46,30 @@ No match Word %1$d %1$d/%2$d + Continue + Amount + %1$s – %2$s + Already paid + Wallet busy + Invoice expired + Payment failed + Not enough funds + 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 + %1$s, %2$s + Pay + Pending + Sent + Check activity + Waiting for network + Phone settings + Couldn\'t import Remove wallet Remove wallet? Couldn\'t remove wallet diff --git a/wear/src/main/res/xml/ndef_tag_service.xml b/wear/src/main/res/xml/ndef_tag_service.xml new file mode 100644 index 0000000000..7a0df56656 --- /dev/null +++ b/wear/src/main/res/xml/ndef_tag_service.xml @@ -0,0 +1,7 @@ + + + + + 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..2176f896e0 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt @@ -0,0 +1,107 @@ +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 remove(paymentHash: String) { + invoices.remove(paymentHash.lowercase()) + } + + 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/data/QuickPaySpendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt new file mode 100644 index 0000000000..b2e81f9d82 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt @@ -0,0 +1,158 @@ +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.assertNotNull +import kotlin.test.assertNull + +/** A [QuickPaySpendStore] in memory, counting as the real one does. */ +class FakeQuickPaySpendStore : QuickPaySpendStore { + var day: String? = null + var spentCents = 0L + var failure: Throwable? = null + + override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? { + failure?.let { throw it } + if (cents <= 0 || capCents <= 0) return null + val isNewDay = day.let { it == null || dayKey > it } + val spent = if (isNewDay) 0L else spentCents + if (cents > capCents - spent) return null + if (isNewDay) day = dayKey + spentCents = spent + cents + return day + } + + override suspend fun release(dayKey: String, cents: Long) { + failure?.let { throw it } + if (dayKey == day) spentCents = (spentCents - cents).coerceAtLeast(0L) + } +} + +/** The store against the real settings file, in a temporary directory. Each [open] is a new process. */ +class QuickPaySpendStoreTest : BaseUnitTest() { + private companion object { + const val TODAY = "2026-11-28" + const val TOMORROW = "2026-11-29" + } + + @get:Rule + val folder = TemporaryFolder() + + private val settingsFile by lazy { File(folder.root, "datastore/settings.preferences_pb") } + private var scope: CoroutineScope? = null + + @Test + fun `a day takes payments up to its cap and not a cent more, also after a restart`() = test { + val sut = open().first + assertNotNull(sut.reserve(TODAY, cents = 400, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 500, capCents = 1_000)) + close() + val next = open().first + + assertNull(next.reserve(TODAY, cents = 101, capCents = 1_000)) + assertNotNull(next.reserve(TODAY, cents = 100, capCents = 1_000)) + assertNull(next.reserve(TODAY, cents = 1, capCents = 1_000)) + close() + } + + @Test + fun `a refused payment counts for nothing`() = test { + val sut = open().first + + assertNull(sut.reserve(TODAY, cents = 1_001, capCents = 1_000)) + + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a new day starts from nothing and an earlier day does not`() = test { + val sut = open().first + assertNotNull(sut.reserve(TOMORROW, cents = 1_000, capCents = 1_000)) + + assertNull(sut.reserve(TODAY, cents = 1, capCents = 1_000)) + assertNull(sut.reserve(TOMORROW, cents = 1, capCents = 1_000)) + + assertNotNull(sut.reserve("2026-11-30", cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a payment of an earlier day is counted under the day last counted`() = test { + val sut = open().first + assertEquals(TOMORROW, sut.reserve(TOMORROW, cents = 400, capCents = 1_000)) + + assertEquals(TOMORROW, sut.reserve(TODAY, cents = 600, capCents = 1_000)) + assertNull(sut.reserve(TOMORROW, cents = 1, capCents = 1_000)) + close() + } + + @Test + fun `a released payment frees its cents in the day counted, and nothing in another day`() = test { + val sut = open().first + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + + sut.release(TOMORROW, cents = 1_000) + sut.release(TODAY, cents = 0) + assertNull(sut.reserve(TODAY, cents = 1, capCents = 1_000)) + + sut.release(TODAY, cents = 400) + assertNull(sut.reserve(TODAY, cents = 401, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 400, capCents = 1_000)) + + sut.release(TODAY, cents = 5_000) + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a lowered cap counts what was already spent`() = test { + val sut = open().first + assertNotNull(sut.reserve(TODAY, cents = 800, capCents = 1_000)) + + assertNull(sut.reserve(TODAY, cents = 1, capCents = 500)) + close() + } + + @Test + fun `nothing and less than nothing are refused`() = test { + val sut = open().first + + assertNull(sut.reserve(TODAY, cents = 0, capCents = 1_000)) + assertNull(sut.reserve(TODAY, cents = -5, capCents = 1_000)) + assertNull(sut.reserve(TODAY, cents = 1, capCents = 0)) + assertNull(sut.reserve(TODAY, cents = Long.MAX_VALUE, capCents = 1_000)) + close() + } + + @Test + fun `the wallet's wipe forgets the day's spend with the settings`() = test { + val (sut, settings) = open() + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + + settings.finishWipe() + + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + 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 SettingsQuickPaySpendStore(dataStore) to settings + } + + private suspend fun close() { + scope?.coroutineContext?.job?.cancelAndJoin() + scope = null + } +} diff --git a/wear/src/test/java/to/bitkit/wear/data/SendMonitorTest.kt b/wear/src/test/java/to/bitkit/wear/data/SendMonitorTest.kt new file mode 100644 index 0000000000..c0d001115e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/SendMonitorTest.kt @@ -0,0 +1,44 @@ +package to.bitkit.wear.data + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SendMonitorTest { + private val sut = SendMonitor() + + @Test + fun `nothing is under way at first`() { + assertFalse(sut.isSending.value) + } + + @Test + fun `a send is under way from its begin to its end`() { + sut.begin() + assertTrue(sut.isSending.value) + + sut.end() + assertFalse(sut.isSending.value) + } + + @Test + fun `two sends are under way until both ended`() { + sut.begin() + sut.begin() + + sut.end() + assertTrue(sut.isSending.value) + + sut.end() + assertFalse(sut.isSending.value) + } + + @Test + fun `an end without a begin leaves nothing under way, and the next send counts`() { + sut.end() + assertFalse(sut.isSending.value) + + sut.begin() + assertTrue(sut.isSending.value) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt index 3b0a096de9..86a51f8746 100644 --- a/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt @@ -8,7 +8,10 @@ import kotlinx.coroutines.job import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.QuickPayLimits import to.bitkit.wear.security.FakeDeviceLock import to.bitkit.wear.security.FakeSeedKey import to.bitkit.wear.security.KeystoreSeedStore @@ -19,6 +22,7 @@ import java.io.IOException import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue /** @@ -26,6 +30,11 @@ import kotlin.test.assertTrue * a new process over what is on disk. */ class SettingsStoreTest : BaseUnitTest() { + private companion object { + val QUICK_PAY = QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3) + val PHONE_SETTINGS = PhoneSettings(PrimaryDisplay.FIAT, BitcoinDisplayUnit.CLASSIC, "EUR", QUICK_PAY) + } + @get:Rule val folder = TemporaryFolder() @@ -80,6 +89,100 @@ class SettingsStoreTest : BaseUnitTest() { close() } + @Test + fun `the phone's settings are adopted and survive a restart`() = test { + open().applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + close() + + val settings = open().data.first() + + assertEquals( + WatchSettings( + primaryDisplay = PrimaryDisplay.FIAT, + selectedCurrency = "EUR", + displayUnit = BitcoinDisplayUnit.CLASSIC, + quickPay = QUICK_PAY, + phoneSyncedAtMs = 5_000L, + ), + settings, + ) + close() + } + + @Test + fun `nothing is imported until the phone's settings are applied`() = test { + val settings = open().data.first() + + assertNull(settings.quickPay) + assertNull(settings.phoneSyncedAtMs) + assertEquals(BitcoinDisplayUnit.MODERN, settings.displayUnit) + close() + } + + @Test + fun `display values the backup does not hold keep the watch's, and unreadable quickpay turns it off`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + + sut.applyPhoneSettings(PhoneSettings(null, null, null, quickPay = null), syncedAtMs = 6_000L) + + val settings = sut.data.first() + assertEquals(PrimaryDisplay.FIAT, settings.primaryDisplay) + assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) + assertEquals("EUR", settings.selectedCurrency) + assertNull(settings.quickPay) + assertEquals(6_000L, settings.phoneSyncedAtMs) + close() + } + + @Test + fun `the wearer's unit swap lasts until the phone's setting changes`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + sut.setPrimaryDisplay(PrimaryDisplay.BITCOIN) + + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 6_000L) + assertEquals(PrimaryDisplay.BITCOIN, sut.data.first().primaryDisplay) + + sut.applyPhoneSettings(PHONE_SETTINGS.copy(primaryDisplay = PrimaryDisplay.BITCOIN), syncedAtMs = 7_000L) + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 8_000L) + assertEquals(PrimaryDisplay.FIAT, sut.data.first().primaryDisplay) + close() + } + + @Test + fun `clearing quickpay keeps the display values and forgets the import time`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + + sut.clearQuickPay() + + val settings = sut.data.first() + assertNull(settings.quickPay) + assertNull(settings.phoneSyncedAtMs) + assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) + assertEquals("EUR", settings.selectedCurrency) + close() + } + + @Test + fun `the wallet's wipe clears everything imported from the phone, as does an overtaken import`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + + sut.finishWipe() + + assertEquals(WatchSettings(), sut.data.first()) + + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + sut.clearPhoneSettings() + + assertEquals(WatchSettings(), sut.data.first()) + close() + assertEquals(WatchSettings(), open().data.first()) + close() + } + @Test fun `a wipe note survives the seed being deleted`() = test { val seedStore = KeystoreSeedStore(lazy { seedDirectory }, FakeSeedKey(), FakeDeviceLock(), false) 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..0fecb9788e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt @@ -0,0 +1,269 @@ +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.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(sparkPayee = send.sparkPayee?.lowercase())) != null + } + + override suspend fun settle(key: String) { + failure?.let { throw it } + sends.remove(key) + } + + override suspend fun transferKeys(sparkPayee: String): List { + failure?.let { throw it } + return sends.values.filter { it.sparkPayee == sparkPayee.lowercase() }.map { it.key }.reversed() + } + + val watchedSends = mutableMapOf() + var watchFailure: Throwable? = null + + override suspend fun watch(send: WatchedSend) { + watchFailure?.let { throw it } + watchedSends[send.id] = send + } + + override suspend fun watched(): List { + watchFailure?.let { throw it } + return watchedSends.values.reversed() + } + + override suspend fun resolve(id: String, outcome: WatchedOutcome): Boolean { + watchFailure?.let { throw it } + val send = watchedSends[id]?.takeIf { it.outcome == null } ?: return false + watchedSends[id] = send.copy(outcome = outcome) + return true + } + + var unwatchFailure: Throwable? = null + + override suspend fun unwatch(id: String): Boolean { + (unwatchFailure ?: watchFailure)?.let { throw it } + return watchedSends.remove(id) != null + } +} + +/** 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 PAYEE = "03a1b2c3d4e5f60718293a4b5c6d7e8f9001122334455667788990aabbccddeeff" + } + + @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 payee in either case, also after a restart`() = test { + assertFalse(open().first.begin(UncertainSend("key-a", sparkPayee = PAYEE))) + close() + val sut = open().first + + 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() + } + + @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", sparkPayee = PAYEE)) + sut.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL)) + + sut.settle("key-a") + sut.settle("key-0") + sut.settle("unknown") + + assertTrue(sut.transferKeys(PAYEE).isEmpty()) + 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", sparkPayee = PAYEE)) + + 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(listOf("key-a"), sut.transferKeys(PAYEE)) + 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", sparkPayee = "02payee$it")) + } + + 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", sparkPayee = PAYEE)) + + settings.finishWipe() + + assertTrue(sut.transferKeys(PAYEE).isEmpty()) + close() + } + + @Test + fun `a watched send is remembered with its quickpay count, also after a restart, until it is forgotten`() = test { + val first = open().first + first.watch(WatchedSend("key-0", quickPayDay = "2026-11-28", quickPayCents = 50)) + first.watch(WatchedSend("key-a")) + close() + val sut = open().first + + assertEquals( + setOf(WatchedSend("key-0", "2026-11-28", 50), WatchedSend("key-a")), + sut.watched().toSet(), + ) + assertTrue(sut.unwatch("key-0")) + assertFalse(sut.unwatch("key-0")) + assertEquals(listOf(WatchedSend("key-a")), sut.watched()) + close() + } + + @Test + fun `a watched send keeps its outcome and its count across a restart, until it is forgotten`() = test { + val first = open().first + first.watch(WatchedSend("key-0", quickPayDay = "2026-11-28", quickPayCents = 50)) + first.watch(WatchedSend("key-1")) + assertTrue(first.resolve("key-0", WatchedOutcome(isSent = true, amountSats = 1_000uL))) + assertTrue(first.resolve("key-1", WatchedOutcome(isSent = false, amountSats = 21uL))) + // An outcome is noted once, and only for a send that is remembered. + assertFalse(first.resolve("key-0", WatchedOutcome(isSent = false, amountSats = 1_000uL))) + assertFalse(first.resolve("unknown", WatchedOutcome(isSent = true, amountSats = 1uL))) + close() + val sut = open().first + + assertEquals( + setOf( + WatchedSend("key-0", "2026-11-28", 50, WatchedOutcome(isSent = true, amountSats = 1_000uL)), + WatchedSend("key-1", outcome = WatchedOutcome(isSent = false, amountSats = 21uL)), + ), + sut.watched().toSet(), + ) + assertTrue(sut.unwatch("key-0")) + assertEquals(listOf("key-1"), sut.watched().map { it.id }) + close() + } + + @Test + fun `watched sends do not mix with the noted ones`() = test { + val sut = open().first + sut.begin(UncertainSend("key-a", sparkPayee = PAYEE)) + sut.watch(WatchedSend("key-a")) + + sut.settle("key-a") + assertEquals(listOf(WatchedSend("key-a")), sut.watched()) + + sut.begin(UncertainSend("key-a", sparkPayee = PAYEE)) + sut.unwatch("key-a") + assertEquals(listOf("key-a"), sut.transferKeys(PAYEE)) + close() + } + + @Test + fun `only the newest watched sends are kept, each for thirty days`() = test { + val sut = open().first + repeat(SettingsUncertainSendStore.MAX_WATCHED + 1) { + now = 1_000uL + it.toULong() + sut.watch(WatchedSend("key-$it")) + } + val kept = sut.watched().map { it.id } + assertEquals(SettingsUncertainSendStore.MAX_WATCHED, kept.size) + assertEquals("key-${SettingsUncertainSendStore.MAX_WATCHED}", kept.first()) + assertFalse("key-0" in kept) + + now = 1_001uL + SettingsUncertainSendStore.WATCHED_KEPT_SECS + assertFalse("key-1" in sut.watched().map { it.id }) + assertTrue("key-2" in sut.watched().map { it.id }) + close() + } + + @Test + fun `the wallet's wipe forgets the watched sends`() = test { + val (sut, settings) = open() + sut.watch(WatchedSend("key-0", quickPayDay = "2026-11-28", quickPayCents = 50)) + + settings.finishWipe() + + assertTrue(sut.watched().isEmpty()) + 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/models/CurrencyTest.kt b/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt index cad19e7d9c..6e9db736be 100644 --- a/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt +++ b/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt @@ -14,6 +14,14 @@ class CurrencyTest { assertEquals("21 000 000", 21_000_000L.formatToModernDisplay(Locale.US)) } + @Test + fun `the classic unit writes bitcoin with eight decimals`() { + assertEquals("0.00050000", 50_000L.formatToClassicDisplay(Locale.US)) + assertEquals("1.00000000", 100_000_000L.formatToClassicDisplay(Locale.GERMANY)) + assertEquals("0.00000001", 1L.formatMoney(BitcoinDisplayUnit.CLASSIC, Locale.US)) + assertEquals("50 000", 50_000L.formatMoney(BitcoinDisplayUnit.MODERN, Locale.US)) + } + @Test fun `fiat value converts sats at the rate and formats with the symbol`() { val value = fiatValue(sats = 150_000, rate = rate("100000")) diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt new file mode 100644 index 0000000000..bbc1004c22 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt @@ -0,0 +1,58 @@ +package to.bitkit.wear.models + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Test +import to.bitkit.wear.env.Env +import to.bitkit.wear.env.WalletNetwork +import to.bitkit.wear.repositories.SettingsSyncRepo +import kotlin.test.assertEquals + +/** + * `phone-backup-contract.json` holds what the watch needs the phone to keep writing: the backup's key, the six + * settings in the phone's own encoding, and where each network's backups live. The phone's `WatchBackupContractTest` + * compares the same file with what the phone app really writes and uses, so a renamed field or a moved server fails + * a test instead of silently turning QuickPay off on the watch. + */ +class PhoneBackupContractTest { + private val contract: JsonObject by lazy { + val text = checkNotNull(javaClass.classLoader?.getResource("phone-backup-contract.json")).readText() + Json.parseToJsonElement(text).jsonObject + } + + @Test + fun `the watch reads the settings backup under the phone's key`() { + assertEquals(contract.getValue("settingsKey").jsonPrimitive.content, SettingsSyncRepo.SETTINGS_KEY) + } + + @Test + fun `the watch reads all six settings as the phone writes them`() { + val backup = contract.getValue("settingsBackup").toString().toByteArray() + + val expected = PhoneSettings( + PrimaryDisplay.FIAT, + BitcoinDisplayUnit.CLASSIC, + "EUR", + QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), + ) + assertEquals(expected, PhoneSettingsParser.parse(backup)) + } + + @Test + fun `the watch looks for each network's backups where the phone stores them`() { + val networks = contract.getValue("networks").jsonObject + + assertEquals(WalletNetwork.entries.map { it.name }.toSet(), networks.keys) + for (network in WalletNetwork.entries) { + val expected = networks.getValue(network.name).jsonObject.mapValues { it.value.jsonPrimitive.content } + val actual = mapOf( + "storeIdPrefix" to Env.vssStoreIdPrefix(network), + "vssServerUrl" to Env.vssServerUrl(network), + "lnurlAuthServerUrl" to Env.lnurlAuthServerUrl(network), + ) + assertEquals(expected, actual, "$network") + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt new file mode 100644 index 0000000000..aa2d4bf5c7 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt @@ -0,0 +1,146 @@ +package to.bitkit.wear.models + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull + +class PhoneSettingsParserTest { + private companion object { + /** A cut of what bitkit-android writes: pretty-printed, every default encoded, many keys the watch ignores. */ + val ANDROID_BACKUP = """ + { + "version": 1, + "createdAt": 1800000000000, + "settings": { + "primaryDisplay": "FIAT", + "displayUnit": "CLASSIC", + "selectedCurrency": "EUR", + "hideBalance": true, + "isPinEnabled": false, + "quickPayIntroSeen": true, + "isQuickPayEnabled": true, + "quickPayAmount": 10, + "quickPayDailyLimitMultiplier": 3, + "addressTypesToMonitor": ["NATIVE_SEGWIT"], + "someFutureSetting": {"nested": [1, 2, 3]} + } + } + """.trimIndent() + } + + @Test + fun `the phone's backup gives the units, the currency and quickpay, and ignores every other key`() { + val settings = parse(ANDROID_BACKUP) + + assertEquals( + PhoneSettings( + primaryDisplay = PrimaryDisplay.FIAT, + displayUnit = BitcoinDisplayUnit.CLASSIC, + selectedCurrency = "EUR", + quickPay = QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), + ), + settings, + ) + assertEquals(1_000L, settings.quickPay?.thresholdCents) + assertEquals(3_000L, settings.quickPay?.dailyCapCents) + } + + @Test + fun `enums written by ios are read too`() { + val settings = parse( + """{"version":1,"createdAt":1,"settings":{"primaryDisplay":{"fiat":{}},"displayUnit":"classic"}}""", + ) + + assertEquals(PrimaryDisplay.FIAT, settings.primaryDisplay) + assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) + } + + @Test + fun `a display value that is missing or unreadable is left to the watch`() { + val settings = parse( + """{"version":1,"settings":{"primaryDisplay":"GOLD","displayUnit":7,"selectedCurrency":"dollars"}}""", + ) + + assertNull(settings.primaryDisplay) + assertNull(settings.displayUnit) + assertNull(settings.selectedCurrency) + assertEquals(PhoneSettings(null, null, null, null), parse("""{"settings":{}}""")) + } + + @Test + fun `quickpay that is off keeps its limits`() { + val settings = parse(quickPay("false", "5", "5")) + + assertEquals(QuickPayLimits(isEnabled = false, amountUsd = 5, dailyMultiplier = 5), settings.quickPay) + } + + @Test + fun `quickpay with a missing, mistyped or out of range value is not adopted`() { + val settings = """{"isQuickPayEnabled":true,"quickPayAmount":5}""" + assertNull(parse("""{"version":1,"settings":$settings}""").quickPay) + assertNull(parse("""{"version":1,"settings":{"quickPayAmount":5,"quickPayDailyLimitMultiplier":5}}""").quickPay) + for ((isEnabled, amount, multiplier) in listOf( + Triple("\"true\"", "5", "5"), + Triple("1", "5", "5"), + Triple("null", "5", "5"), + Triple("true", "\"5\"", "5"), + Triple("true", "5.5", "5"), + Triple("true", "0", "5"), + Triple("true", "-5", "5"), + Triple("true", "51", "5"), + Triple("true", "99999999999", "5"), + Triple("true", "5", "0"), + Triple("true", "5", "51"), + Triple("true", "5", "[5]"), + )) { + assertNull(parse(quickPay(isEnabled, amount, multiplier)).quickPay, "$isEnabled $amount $multiplier") + } + } + + @Test + fun `the largest values the phone offers are adopted`() { + val settings = parse(quickPay("true", "50", "50")) + + assertEquals(QuickPayLimits(isEnabled = true, amountUsd = 50, dailyMultiplier = 50), settings.quickPay) + assertEquals(250_000L, settings.quickPay?.dailyCapCents) + } + + @Test + fun `a newer layout is refused`() { + val error = assertFailsWith { + parse("""{"version":2,"createdAt":1,"settings":{"isQuickPayEnabled":true}}""") + } + + assertEquals("The settings backup has version '2'", error.message) + } + + @Test + fun `what is not the phone's envelope is refused`() { + for (raw in listOf( + "", + "not json", + "[]", + "\"SETTINGS\"", + "{}", + """{"version":1}""", + """{"version":1,"settings":[]}""", + """{"version":1,"settings":"{}"}""", + """{"version":"new","settings":{}}""", + """{"version":0,"settings":{}}""", + """{"version":{},"settings":{}}""", + )) { + assertFailsWith(raw) { parse(raw) } + } + assertFailsWith { + PhoneSettingsParser.parse(ByteArray(PhoneSettingsParser.MAX_BYTES + 1) { ' '.code.toByte() }) + } + assertFailsWith { PhoneSettingsParser.parse(byteArrayOf(-1, 0, -2)) } + } + + private fun quickPay(isEnabled: String, amount: String, multiplier: String) = + """{"version":1,"settings":{"isQuickPayEnabled":$isEnabled,"quickPayAmount":$amount,""" + + """"quickPayDailyLimitMultiplier":$multiplier}}""" + + private fun parse(raw: String) = PhoneSettingsParser.parse(raw.toByteArray()) +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NdefCodecTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NdefCodecTest.kt new file mode 100644 index 0000000000..1c2f0fce89 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NdefCodecTest.kt @@ -0,0 +1,116 @@ +// Copied from app/src/test/java/to/bitkit/nfc/NdefCodecTest.kt; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NdefCodecTest { + @Test + fun `encodes a short URI record without a prefix code`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbc1") + + val payload = byteArrayOf(0x00) + "lightning:lnbc1".toByteArray() + val expected = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'U'.code.toByte()) + payload + assertArrayEquals(expected, message) + } + + @Test + fun `encodes a long URI record with a 4-byte length`() { + val uri = "bitcoin:bc1q?lightning=" + "x".repeat(400) + + val message = NdefCodec.encodeUriMessage(uri) + + assertEquals(0xC1.toByte(), message[0]) + assertEquals(listOf(uri), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes the long URI record a Square Register serves`() { + val message = PosNfcFixtures.squareMessage() + + assertEquals(465, message.size) + assertArrayEquals( + PosNfcFixtures.hex(PosNfcFixtures.SQUARE_MESSAGE_START_HEX), + message.copyOf(18), + ) + assertEquals(listOf(PosNfcFixtures.SQUARE_URI), NdefCodec.decodeTexts(message)) + assertEquals(PosNfcFixtures.SQUARE_URI, NdefCodec.payableText(NdefCodec.decodeTexts(message))) + } + + @Test + fun `encodes a Square-sized request exactly as Square does`() { + assertArrayEquals(PosNfcFixtures.squareMessage(), NdefCodec.encodeUriMessage(PosNfcFixtures.SQUARE_URI)) + } + + @Test + fun `decodes the BIP 321 request Numo serves`() { + val message = PosNfcFixtures.squareMessage(PosNfcFixtures.BIP321_URI) + + assertEquals(listOf(PosNfcFixtures.BIP321_URI), NdefCodec.decodeTexts(message)) + } + + @Test + fun `round trips a URI record`() { + val uri = "bitcoin:BC1QTEST?amount=0.001&lightning=LNBC10U1P" + + assertEquals(listOf(uri), NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri))) + } + + @Test + fun `expands URI prefix codes`() { + val payload = byteArrayOf(0x04) + "example.com/lnurlp/alice".toByteArray() + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'U'.code.toByte()) + payload + + assertEquals(listOf("https://example.com/lnurlp/alice"), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes a UTF-8 text record`() { + val text = "bitcoin:?lightning=lnbc1&creq=creqA1" + val payload = byteArrayOf(0x02, 'e'.code.toByte(), 'n'.code.toByte()) + text.toByteArray() + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'T'.code.toByte()) + payload + + assertEquals(listOf(text), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes a UTF-16 text record`() { + val text = "lnbc1" + val header = byteArrayOf(0x82.toByte(), 'e'.code.toByte(), 'n'.code.toByte()) + val payload = header + text.toByteArray(Charsets.UTF_16) + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'T'.code.toByte()) + payload + + assertEquals(listOf(text), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes every record and skips unknown types`() { + val uri = NdefCodec.encodeUriMessage("lightning:lnbc1") + val mime = byteArrayOf(0x52, 0x0A, 0x01) + "text/plain".toByteArray() + byteArrayOf(0x41) + val firstRecord = byteArrayOf((uri[0].toInt() and 0xBF).toByte()) + uri.copyOfRange(1, uri.size) + + assertEquals(listOf("lightning:lnbc1"), NdefCodec.decodeTexts(firstRecord + mime)) + } + + @Test + fun `returns nothing for a truncated message`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbc1") + + assertTrue(NdefCodec.decodeTexts(message.copyOf(message.size - 3)).isEmpty()) + } + + @Test + fun `payable text is the single distinct request`() { + assertEquals("lightning:lnbc1", NdefCodec.payableText(listOf(" lightning:lnbc1 ", "lightning:lnbc1", ""))) + } + + @Test + fun `payable text is null for no or conflicting requests`() { + assertNull(NdefCodec.payableText(emptyList())) + assertNull(NdefCodec.payableText(listOf(" "))) + assertNull(NdefCodec.payableText(listOf("lightning:lnbc1", "lightning:lnbc2"))) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcPaymentUriTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcPaymentUriTest.kt new file mode 100644 index 0000000000..34b4a592ec --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcPaymentUriTest.kt @@ -0,0 +1,167 @@ +// Copied from app/src/test/java/to/bitkit/nfc/NfcPaymentUriTest.kt; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class NfcPaymentUriTest { + @Test + fun `keeps requests that already have a payment scheme`() { + assertEquals("bitcoin:bc1q?lightning=lnbc1", nfcPaymentUri("bitcoin:bc1q?lightning=lnbc1")) + assertEquals("BITCOIN:BC1Q", nfcPaymentUri("BITCOIN:BC1Q")) + assertEquals("lightning:lnbc1", nfcPaymentUri("lightning:lnbc1")) + assertEquals("ethereum:0xabc@42161/transfer", nfcPaymentUri("ethereum:0xabc@42161/transfer")) + assertEquals("LIGHTNING:LNTBS1P", nfcPaymentUri("LIGHTNING:LNTBS1P")) + } + + @Test + fun `adds lightning to bare lightning requests`() { + assertEquals("lightning:lnbc10u1p", nfcPaymentUri("lnbc10u1p")) + assertEquals("lightning:lnbcrt1p", nfcPaymentUri(" lnbcrt1p ")) + assertEquals("lightning:LNURL1DP68", nfcPaymentUri("LNURL1DP68")) + } + + @Test + fun `adds bitcoin to bare addresses`() { + assertEquals("bitcoin:bc1qxyz", nfcPaymentUri("bc1qxyz")) + } + + @Test + fun `returns null for no request`() { + assertNull(nfcPaymentUri(null)) + assertNull(nfcPaymentUri(" ")) + } + + @Test + fun `keeps a Square request for the scanner`() { + assertEquals(PosNfcFixtures.SQUARE_URI, scannedPaymentRequest(PosNfcFixtures.SQUARE_URI)) + assertEquals("LIGHTNING:LNTBS1P", scannedPaymentRequest(" LIGHTNING:LNTBS1P\n")) + } + + @Test + fun `turns a BIP 321 request without an address into its Lightning request`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + + assertEquals("lightning:$invoice", scannedPaymentRequest(PosNfcFixtures.BIP321_URI)) + assertEquals("lightning:$invoice", scannedPaymentRequest("BITCOIN:?LIGHTNING=$invoice")) + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.0000799&lightning=$invoice&creq=x")) + } + + @Test + fun `keeps other bitcoin requests unchanged`() { + val unified = "bitcoin:bc1qtest?lightning=lnbc1" + + assertEquals(unified, scannedPaymentRequest(unified)) + assertEquals("bitcoin:?amount=0.001", scannedPaymentRequest("bitcoin:?amount=0.001")) + assertEquals("bitcoin:?lightning=", scannedPaymentRequest("bitcoin:?lightning=")) + assertEquals("bitcoin:?lno=lno1qgsq", scannedPaymentRequest("bitcoin:?lno=lno1qgsq")) + } + + @Test + fun `request repeating a parameter is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + for (repeated in listOf( + "bitcoin:?lightning=$invoice&amount=0.01&AMOUNT=0.02", + "bitcoin:?lightning=$invoice&lightning=lnbc1other", + "bitcoin:?lightning=$invoice&label=a&label=b", + "bitcoin:?lightning=$invoice&message=a&message=b", + "bitcoin:?lightning=$invoice&amount=0.0000799&amount=0.0000799", + "bitcoin:?lightning=$invoice&pop=a%3a&POP=b%3a", + )) { + assertEquals(repeated, scannedPaymentRequest(repeated)) + } + } + + @Test + fun `request repeating an optional extension is unwrapped`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals( + "lightning:$invoice", + scannedPaymentRequest("bitcoin:?lightning=$invoice&x-shop=a&X-SHOP=b&creq=c&creq=d&lno=lno1a&lno=lno1b"), + ) + } + + @Test + fun `request whose amount the invoice does not carry is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.0000799&lightning=$invoice")) + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.00007990&lightning=$invoice")) + for (kept in listOf( + "bitcoin:?amount=0.0001&lightning=$invoice", + "bitcoin:?amount=0.0001&lightning=lnbcrt1pamountless", + "bitcoin:?amount=abc&lightning=$invoice", + "bitcoin:?amount=0.0000799,50&lightning=$invoice", + "bitcoin:?amount=0.0000799BTC&lightning=$invoice", + "bitcoin:?amount=7.99E-5&lightning=$invoice", + "bitcoin:?amount=+0.0000799&lightning=$invoice", + )) { + assertEquals(kept, scannedPaymentRequest(kept)) + } + } + + @Test + fun `nfc read with a required parameter is refused`() { + assertNull(nfcPaymentRequest("bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a")) + assertNull(nfcPaymentRequest("BITCOIN:BCRT1QTEST?REQ-FOO=bar")) + // The scanner strips `lightning:` before decoding, so a wrapped Bitcoin request is checked as one. + assertNull(nfcPaymentRequest("lightning:bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a")) + val wrappedInvoice = "LIGHTNING:bitcoin:?lightning=${PosNfcFixtures.SQUARE_INVOICE}&req-pop=callback%3a" + assertNull(nfcPaymentRequest(wrappedInvoice)) + val required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=callback" + for (wrapper in listOf("bitkit://", "bitkit://lightning:", "lightning:lightning:", "lnurl:lightning:")) { + assertNull(nfcPaymentRequest("$wrapper$required")) + } + val wrappedPlain = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + assertEquals(wrappedPlain, nfcPaymentRequest(wrappedPlain)) + val lnurlPay = "https://pay.example.com/lnurlp?req-x=1&lightning=LNURL1DP68GURN8GHJ7" + assertEquals(lnurlPay, nfcPaymentRequest(lnurlPay)) + assertEquals("bitcoin:bcrt1qtest?amount=0.001", nfcPaymentRequest(" bitcoin:bcrt1qtest?amount=0.001 ")) + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals("lightning:$invoice", nfcPaymentRequest("bitcoin:?lightning=$invoice")) + } + + @Test + fun `nfc read with a required parameter behind an inner bitkit scheme is refused`() { + // The decoder deletes every `bitkit://` in a deep link, which can turn a key into `req-`. + val address = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + assertNull(nfcPaymentRequest("$address&bitkit://req-pop=callback")) + assertNull(nfcPaymentRequest("$address&rebitkit://q-pop=callback")) + // The decoder deletes only lowercase `bitkit://`, so a mixed-case one stays part of an optional key. + val mixedCase = "bitkit://bitkit://bitcoin:bcrt1qtest?REBITKIT://Q-POP=callback" + assertEquals(mixedCase, nfcPaymentRequest(mixedCase)) + val optional = "bitkit://bitcoin:bcrt1qtest?amount=0.001&reBitkit://q-x=1" + assertEquals(optional, nfcPaymentRequest(optional)) + // The decoder deletes them again while the text starts with `bitkit://`, so a nested one is removed too. + val required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=x" + assertNull(nfcPaymentRequest("bitkit://bitbitkit://kit://$required")) + assertNull(nfcPaymentRequest("bitkit://lightning:bitbitkit://kit://$required")) + // Once the text starts with `bitcoin:` the decoder deletes nothing more, so this key is not `req-`. + val payable = "bitcoin:bcrt1qtest?amount=0.001&bitbitkit://kit://req-pop=x" + assertEquals(payable, nfcPaymentRequest(payable)) + assertEquals("bitkit://$payable", nfcPaymentRequest("bitkit://$payable")) + // The decoder's trim also removes U+0085 (NEL), which Kotlin's `trim()` keeps. + assertNull(nfcPaymentRequest("\u0085$required")) + assertNull(nfcPaymentRequest("bitkit://\u0085$required")) + } + + @Test + fun `request with an empty amount is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + for (empty in listOf("bitcoin:?amount=&lightning=$invoice", "bitcoin:?lightning=$invoice&amount")) { + assertEquals(empty, scannedPaymentRequest(empty)) + } + } + + @Test + fun `request with a required parameter is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + val required = "bitcoin:?lightning=$invoice&req-pop=callback%3a" + assertEquals(required, scannedPaymentRequest(required)) + val uppercase = "BITCOIN:?REQ-FOO=bar&LIGHTNING=$invoice" + assertEquals(uppercase, scannedPaymentRequest(uppercase)) + for (empty in listOf("bitcoin:?lightning=$invoice&req-foo=", "bitcoin:?lightning=$invoice&req-foo")) { + assertEquals(empty, scannedPaymentRequest(empty)) + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcTagEmitterTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagEmitterTest.kt new file mode 100644 index 0000000000..62c346a3e6 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagEmitterTest.kt @@ -0,0 +1,54 @@ +// Copied from app/src/test/java/to/bitkit/nfc/NfcTagEmitterTest.kt, with the revoke cases added; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NfcTagEmitterTest { + private val tokens = mutableListOf() + + @After + fun tearDown() { + tokens.forEach { NfcTagEmitter.clear(it) } + } + + @Test + fun `serves the published request until its owner clears it`() { + val token = NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc1"), NfcTagEmitter.currentMessage()) + assertTrue(NfcTagEmitter.clear(token)) + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `an older publisher cannot clear a newer request`() { + val first = NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + NfcTagEmitter.publish("lightning:lnbc2").also(tokens::add) + + assertFalse(NfcTagEmitter.clear(first)) + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc2"), NfcTagEmitter.currentMessage()) + } + + @Test + fun `a revoked request is served no more, whoever published it`() { + NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + + NfcTagEmitter.revoke() + + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `revoking while nothing is published leaves the next request alone`() { + NfcTagEmitter.revoke() + + NfcTagEmitter.publish("lightning:lnbc2").also(tokens::add) + + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc2"), NfcTagEmitter.currentMessage()) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcTagOfferTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagOfferTest.kt new file mode 100644 index 0000000000..8239862be8 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagOfferTest.kt @@ -0,0 +1,153 @@ +package to.bitkit.wear.nfc + +import org.junit.After +import org.junit.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class NfcTagOfferTest { + private val route = FakeTagRoute() + private val sut = NfcTagOffer(route) + private val reader = Type4TagEmulator(NfcTagEmitter::currentMessage) + + @After + fun tearDown() { + sut.stop() + } + + @Test + fun `nothing is offered before start`() { + assertFalse(sut.isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertNull(read()) + } + + @Test + fun `a started offer serves its request to a reader, as one uri record`() { + assertTrue(sut.start(URI)) + + assertTrue(sut.isOffered) + assertEquals(1, route.opens) + assertContentEquals(NdefCodec.encodeUriMessage(URI), NfcTagEmitter.currentMessage()) + assertEquals(listOf(URI), read()) + } + + @Test + fun `a stopped offer serves nothing and closes the route`() { + sut.start(URI) + + sut.stop() + + assertFalse(sut.isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertNull(read()) + assertEquals(1, route.closes) + } + + @Test + fun `a reader that selected the tag is served nothing more once the offer stops`() { + sut.start(URI) + reader.process(SELECT_APP) + reader.process(SELECT_NDEF) + + sut.stop() + + assertContentEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, reader.process(READ_LENGTH)) + } + + @Test + fun `an offer whose route cannot be opened publishes nothing`() { + route.canOpen = false + + assertFalse(sut.start(URI)) + + assertFalse(sut.isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertEquals(0, route.closes) + } + + @Test + fun `starting again replaces the request`() { + sut.start(URI) + + assertTrue(sut.start(OTHER_URI)) + + assertEquals(listOf(OTHER_URI), read()) + sut.stop() + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `stopping twice closes the route once`() { + sut.start(URI) + + sut.stop() + sut.stop() + + assertEquals(1, route.closes) + } + + @Test + fun `an older offer that stops leaves a newer one, and its route, alone`() { + val newerRoute = FakeTagRoute() + val newer = NfcTagOffer(newerRoute) + sut.start(URI) + newer.start(OTHER_URI) + + sut.stop() + + assertEquals(0, route.closes) + assertEquals(listOf(OTHER_URI), read()) + newer.stop() + assertEquals(1, newerRoute.closes) + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `a revoked request is served no more, and its offer still closes the route when it stops`() { + sut.start(URI) + + NfcTagEmitter.revoke() + assertNull(read()) + + sut.stop() + assertEquals(1, route.closes) + } + + /** What a reader gets from the tag over the standard read sequence, or null when it finds no tag. */ + private fun read(): List? { + reader.reset() + if (!reader.process(SELECT_APP).contentEquals(Type4TagEmulator.SW_OK)) return null + if (!reader.process(SELECT_NDEF).contentEquals(Type4TagEmulator.SW_OK)) return null + val length = reader.process(READ_LENGTH) + val size = ((length[0].toInt() and 0xFF) shl 8) or (length[1].toInt() and 0xFF) + val message = reader.process(byteArrayOf(0x00, 0xB0.toByte(), 0x00, 0x02, size.toByte())).copyOf(size) + return NdefCodec.decodeTexts(message) + } + + private class FakeTagRoute : TagRoute { + var canOpen = true + var opens = 0 + var closes = 0 + + override fun open(): Boolean { + opens++ + return canOpen + } + + override fun close() { + closes++ + } + } + + private companion object { + const val URI = "lightning:lnbcrt1invoice" + const val OTHER_URI = "lightning:lnbcrt1other" + val SELECT_APP = byteArrayOf(0x00, 0xA4.toByte(), 0x04, 0x00, 0x07) + Type4TagEmulator.NDEF_AID + 0x00 + val SELECT_NDEF = byteArrayOf(0x00, 0xA4.toByte(), 0x00, 0x0C, 0x02, 0xE1.toByte(), 0x04) + val READ_LENGTH = byteArrayOf(0x00, 0xB0.toByte(), 0x00, 0x00, 0x02) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcTapFilterTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcTapFilterTest.kt new file mode 100644 index 0000000000..f34e0abda2 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcTapFilterTest.kt @@ -0,0 +1,59 @@ +package to.bitkit.wear.nfc + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class NfcTapFilterTest { + private var time = 0L + private val sut = NfcTapFilter { time } + + @Test + fun `the filter is one for the process, so a repeat is dropped whichever activity it reaches`() { + assertTrue(NfcTapFilter::class.java.isAnnotationPresent(javax.inject.Singleton::class.java)) + } + + @Test + fun `the first tap is new`() { + assertTrue(sut.isNew(REQUEST)) + } + + @Test + fun `the same request again within the window is a repeat`() { + sut.isNew(REQUEST) + time += NfcTapFilter.REPEAT_WINDOW.inWholeMilliseconds - 1 + + assertFalse(sut.isNew(REQUEST)) + } + + @Test + fun `a watch held on the tag keeps getting repeats, however long`() { + sut.isNew(REQUEST) + repeat(20) { + time += 1_000 + assertFalse(sut.isNew(REQUEST)) + } + } + + @Test + fun `the same request is a new tap once the window passed without it`() { + sut.isNew(REQUEST) + time += 1_000 + sut.isNew(REQUEST) + time += NfcTapFilter.REPEAT_WINDOW.inWholeMilliseconds + + assertTrue(sut.isNew(REQUEST)) + } + + @Test + fun `another request is a new tap at once`() { + sut.isNew(REQUEST) + + assertTrue(sut.isNew("lightning:lnbcrt1other")) + assertTrue(sut.isNew(REQUEST)) + } + + private companion object { + const val REQUEST = "lightning:lnbcrt1invoice" + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/PosNfcFixtures.kt b/wear/src/test/java/to/bitkit/wear/nfc/PosNfcFixtures.kt new file mode 100644 index 0000000000..826c15eaf0 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/PosNfcFixtures.kt @@ -0,0 +1,37 @@ +// Copied from app/src/test/java/to/bitkit/nfc/PosNfcFixtures.kt; keep both in sync. +package to.bitkit.wear.nfc + +import java.nio.ByteBuffer + +/** + * Requests as point-of-sale terminals present them over NFC. + * + * A Square Register (2nd generation) serves `lightning:` and the uppercase BOLT11 invoice from its QR code as + * one long-format NDEF URI record with identifier code 0x00. Numo, and Square in a later release, serve the + * BIP 321 form without an address. [SQUARE_INVOICE] is a real signet invoice of the size Square serves: + * its message is 465 bytes and starts like Square's. + */ +object PosNfcFixtures { + const val SQUARE_INVOICE = + "LNTBS79900N1P4TZWUQD962DCH2CTJV5S9YET8D9EHGETJYP8YVSEQWFJKWUN9WDEKJMMWYPNXJ7R5W4EX2GZNW96KZUN9YPFX2E" + + "MFWD6X2U3QFERYXGRJV4NHYETNWD5K7M3QVE5HSAR4WFJJQ5M3W4SHYEFQ2FJKW6TNW3JHYGZWGEPJQUN9VAEX2UMND9HKUGRXD9" + + "U8GATJV5PP5QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSSP5PYYSJZGFPYYSJZGFPYYSJZGFPYYSJZGFPY" + + "YSJZGFPYYSJZGFPYYS9QRSGQXQ97ZVUQCQZYSKUAHP9D6GKX2H8ERFH5E9NZZ52SY0UFR2F6VGK43QEJ0ZJU7FTYQYJTQE8705R2" + + "KM9QS5NYFM3ZPR330ML3S3HWJP5D0RERD49QGT5CPUXAWEL" + const val SQUARE_URI = "lightning:$SQUARE_INVOICE" + const val BIP321_URI = "bitcoin:?lightning=$SQUARE_INVOICE" + + /** The first bytes of Square's NDEF message: long URI record, 0x1CA-byte payload, code 0x00, `lightning:`. */ + const val SQUARE_MESSAGE_START_HEX = "C1010000 01CA 55 00 6C696768746E696E673A" + + /** Square's NDEF message, built by hand from the record layout rather than by [NdefCodec]. */ + fun squareMessage(uri: String = SQUARE_URI): ByteArray { + val payload = byteArrayOf(0x00) + uri.toByteArray(Charsets.US_ASCII) + val lengthBytes = ByteBuffer.allocate(Int.SIZE_BYTES).putInt(payload.size).array() + val header = byteArrayOf(0xC1.toByte(), 0x01) + lengthBytes + byteArrayOf(0x55) + return header + payload + } + + fun hex(value: String): ByteArray = + value.replace(" ", "").chunked(2).map { it.toInt(16).toByte() }.toByteArray() +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/Type4TagEmulatorTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/Type4TagEmulatorTest.kt new file mode 100644 index 0000000000..8b78f873f3 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/Type4TagEmulatorTest.kt @@ -0,0 +1,139 @@ +// Copied from app/src/test/java/to/bitkit/nfc/Type4TagEmulatorTest.kt; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test + +class Type4TagEmulatorTest { + private var message: ByteArray? = NdefCodec.encodeUriMessage("lightning:lnbc1") + private val sut = Type4TagEmulator { message } + + private val selectApp = hex("00A4040007D276000085010100") + private val selectCc = hex("00A4000C02E103") + private val selectNdef = hex("00A4000C02E104") + + @Test + fun `serves the NDEF message through the standard read sequence`() { + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectApp)) + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectCc)) + assertArrayEquals(hex("000F20003B00340406E104100000FF9000"), sut.process(hex("00B000000F"))) + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectNdef)) + + val expected = requireNotNull(message) + val lengthResponse = sut.process(hex("00B0000002")) + assertArrayEquals(byteArrayOf(0x00, expected.size.toByte()) + Type4TagEmulator.SW_OK, lengthResponse) + + val read = readNdef(offset = 2, total = expected.size) + assertArrayEquals(expected, read) + } + + @Test + fun `reads a long message in chunks`() { + message = NdefCodec.encodeUriMessage("bitcoin:bc1q?lightning=" + "x".repeat(700)) + sut.process(selectApp) + sut.process(selectNdef) + + val expected = requireNotNull(message) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size)) + } + + @Test + fun `serves a Square-sized request to a reader looping over offsets`() { + message = NdefCodec.encodeUriMessage(PosNfcFixtures.SQUARE_URI) + sut.process(selectApp) + sut.process(selectNdef) + + val expected = requireNotNull(message) + assertArrayEquals(hex("01D1") + Type4TagEmulator.SW_OK, sut.process(hex("00B0000002"))) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size)) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size, chunk = 0xFF)) + assertEquals(listOf(PosNfcFixtures.SQUARE_URI), NdefCodec.decodeTexts(expected)) + } + + @Test + fun `presents no tag when nothing is published`() { + message = null + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectApp)) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00B0000002"))) + } + + @Test + fun `refuses files before the application is selected`() { + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectCc)) + } + + @Test + fun `refuses other applications`() { + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00A4040007A000000003101000"))) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectCc)) + } + + @Test + fun `keeps serving the message selected for this tap`() { + sut.process(selectApp) + sut.process(selectNdef) + val first = requireNotNull(message) + message = NdefCodec.encodeUriMessage("lightning:lnbc2") + + assertArrayEquals(first, readNdef(offset = 2, total = first.size)) + } + + @Test + fun `stops serving once nothing is published`() { + sut.process(selectApp) + sut.process(selectNdef) + message = null + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00B0000002"))) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + } + + @Test + fun `is read-only`() { + sut.process(selectApp) + sut.process(selectNdef) + + assertArrayEquals(Type4TagEmulator.SW_SECURITY_NOT_SATISFIED, sut.process(hex("00D60000020000"))) + } + + @Test + fun `rejects malformed and unsupported commands`() { + assertArrayEquals(Type4TagEmulator.SW_WRONG_LENGTH, sut.process(hex("00A4"))) + assertArrayEquals(Type4TagEmulator.SW_CLA_NOT_SUPPORTED, sut.process(hex("80A4040000"))) + assertArrayEquals(Type4TagEmulator.SW_INS_NOT_SUPPORTED, sut.process(hex("00CA000000"))) + } + + @Test + fun `reset forgets the selection`() { + sut.process(selectApp) + sut.reset() + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + } + + private fun readNdef(offset: Int, total: Int, chunk: Int = MAX_READ): ByteArray { + var result = byteArrayOf() + var position = offset + while (result.size < total) { + val length = minOf(chunk, total - result.size) + val response = sut.process( + byteArrayOf(0x00, 0xB0.toByte(), (position shr 8).toByte(), position.toByte(), length.toByte()) + ) + assertArrayEquals(Type4TagEmulator.SW_OK, response.copyOfRange(response.size - 2, response.size)) + val chunk = response.copyOfRange(0, response.size - 2) + assertEquals(length, chunk.size) + result += chunk + position += chunk.size + } + return result + } + + private fun hex(value: String): ByteArray = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + + private companion object { + const val MAX_READ = 0x3B + } +} 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..10f4a39414 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -0,0 +1,1871 @@ +package to.bitkit.wear.repositories + +import android.nfc.NfcAdapter +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.doAnswer +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.data.FakeUncertainSendStore +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.UncertainSend +import to.bitkit.wear.data.WatchedOutcome +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.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentUri +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.SparkSync +import to.bitkit.wear.services.WalletSelfSendGuard +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.LaunchRequest +import java.math.BigInteger +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 + +@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 + val RESERVATION = QuickPayReservation("2026-11-28", cents = 50) + } + + 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 uncertainSends = FakeUncertainSendStore() + private val decoder = FakeInputDecoder() + private val quickPayRepo = mock() + private val sendMonitor = SendMonitor() + + private lateinit var sendOutcomeRepo: SendOutcomeRepo + 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.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()) + sendOutcomeRepo = SendOutcomeRepo( + testDispatcher, + sparkService, + walletRepo, + uncertainSends, + quickPayRepo, + sendMonitor, + ) + sut = PaymentsRepo( + testDispatcher, + sparkService, + walletRepo, + decoder, + WalletSelfSendGuard(sparkService, ownInvoices), + ownInvoices, + uncertainSends, + quickPayRepo, + sendMonitor, + sendOutcomeRepo, + ) + } + + /** A new repository over the same stores, as after the app was closed and opened again. */ + private fun restart() { + sendOutcomeRepo = SendOutcomeRepo( + testDispatcher, + sparkService, + walletRepo, + uncertainSends, + quickPayRepo, + sendMonitor, + ) + sut = PaymentsRepo( + testDispatcher, + sparkService, + walletRepo, + decoder, + WalletSelfSendGuard(sparkService, ownInvoices), + ownInvoices, + uncertainSends, + quickPayRepo, + sendMonitor, + sendOutcomeRepo, + ) + } + + // 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 `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()) } + + 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 `an invoice's payment is found in spark's list, and none when it lists none`() = test { + assertNull(sut.findPaid(invoice()).getOrThrow()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(receipt("other", paymentHash = "ff".repeat(32)), receipt("paid"))) + + assertEquals("paid", sut.findPaid(invoice()).getOrThrow()?.id) + } + + @Test + fun `a list that cannot be read is no answer about an invoice's payment`() = test { + whenever(sparkService.listPayments(anyOrNull())) + .doSuspendableAnswer { throw SdkException.NetworkException("reset") } + + assertTrue(sut.findPaid(invoice()).isFailure) + } + + @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[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["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 + 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 `the watch's own receive invoice, read back from its nfc tag, is refused and never priced`() = test { + whenever(sparkService.receiveBolt11(null, "", PaymentsRepo.INVOICE_EXPIRY_SECS)).thenReturn(BOLT11) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + val invoice = sut.createInvoice().getOrThrow() + // The tag as the receive QR offers it, and as a tap on it reaches the send flow. + val uri = nfcPaymentUri(invoice.bolt11)!! + val tapped = LaunchRequest.from( + NfcAdapter.ACTION_NDEF_DISCOVERED, + data = uri, + open = null, + tagTexts = NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri)), + ) + val input = assertIs(tapped).input + + assertIs(sut.parse(input).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(amountMsat = 15_000uL)) + + 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 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) + 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 skips the hold for an invoice with an amount, at its amount without the fee`() = test { + whenever(quickPayRepo.reserve(500uL)).thenReturn(RESERVATION) + + assertTrue(sut.skipConfirmation(preparedSend()) { true }) + + verify(quickPayRepo, times(1)).reserve(any()) + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `quickpay fetches a missing rate before it reads the limits`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + + sut.skipConfirmation(preparedSend()) { true } + + val order = inOrder(quickPayRepo) + order.verify(quickPayRepo).awaitRate() + order.verify(quickPayRepo).reserve(any()) + } + + @Test + fun `quickpay holds when the wallet stopped being ready while it waited for the rate`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(quickPayRepo.awaitRate()).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Paused) } + } + + assertFalse(sut.skipConfirmation(preparedSend()) { true }) + } + + @Test + fun `quickpay holds when the limits say no`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(null) + + assertFalse(sut.skipConfirmation(preparedSend()) { true }) + } + + @Test + fun `quickpay holds and counts nothing when the wearer left while the limits were read`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val prepared = preparedSend() + + assertFalse(sut.skipConfirmation(prepared) { false }) + + verify(quickPayRepo).release(RESERVATION) + // The wearer then holds to pay, and a failure of that send releases nothing a second time. + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + sut.send(prepared) + verify(quickPayRepo, times(1)).release(any()) + } + + @Test + fun `quickpay never skips the hold for an amount the wearer typed`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val amountless = sut.prepare(SendRequest.Invoice(BOLT11, null, null), amountSats = 500uL).getOrThrow() + val range = SendRequest.Lnurl(lnurl(10_000uL, 20_000uL), minSats = 10uL, maxSats = 20uL, payee = null) + stubLnurlInvoice() + val typed = sut.prepare(range, amountSats = 15uL).getOrThrow() + + assertFalse(sut.skipConfirmation(amountless) { true }) + assertFalse(sut.skipConfirmation(typed) { true }) + + verify(quickPayRepo, never()).awaitRate() + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay skips the hold for an lnurl or a lightning address that takes one amount, as on the phone`() = + test { + whenever(quickPayRepo.reserve(15uL)).thenReturn(RESERVATION) + val fixed = SendRequest.Lnurl(lnurl(15_000uL, 15_000uL), minSats = 15uL, maxSats = 15uL, payee = null) + stubLnurlInvoice() + + assertTrue(sut.skipConfirmation(sut.prepare(fixed).getOrThrow()) { true }) + } + + @Test + fun `quickpay skips the hold for an uppercase bitcoin uri with an amount, like a lowercase one`() = test { + whenever(quickPayRepo.reserve(500uL)).thenReturn(RESERVATION) + decoder.inputs["bitcoin:bcrt1q?lightning=$BOLT11"] = onchain(mapOf("lightning" to BOLT11)) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + val links = listOf( + "bitcoin:bcrt1q?lightning=$BOLT11", + "BITCOIN:BCRT1Q?LIGHTNING=${BOLT11.uppercase()}", + ) + + for (link in links) { + val request = sut.parse(link).getOrThrow() + assertEquals(500uL, request.fixedAmountSats, link) + assertTrue(sut.skipConfirmation(sut.prepare(request).getOrThrow()) { true }, link) + } + + verify(quickPayRepo, times(2)).reserve(500uL) + } + + @Test + fun `quickpay never skips the hold for an uppercase bitcoin uri without an amount`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + decoder.inputs["bitcoin:bcrt1q?lightning=$BOLT11"] = onchain(mapOf("lightning" to BOLT11)) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 0uL) + + val request = sut.parse("BITCOIN:BCRT1Q?LIGHTNING=${BOLT11.uppercase()}").getOrThrow() + assertNull(request.fixedAmountSats) + + assertFalse(sut.skipConfirmation(sut.prepare(request, amountSats = 500uL).getOrThrow()) { true }) + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `an lnurlp link follows the lnurl rule for quickpay, one amount only`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + decoder.inputs["https://pay.example/lnurlp/fixed"] = Scanner.LnurlPay(lnurl(15_000uL, 15_000uL)) + decoder.inputs["https://pay.example/lnurlp/range"] = Scanner.LnurlPay(lnurl(10_000uL, 20_000uL)) + stubLnurlInvoice() + + val fixed = sut.parse("lnurlp://pay.example/lnurlp/fixed").getOrThrow() + val range = sut.parse("LNURLP://pay.example/lnurlp/range").getOrThrow() + + assertEquals(15uL, fixed.fixedAmountSats) + assertNull(range.fixedAmountSats) + assertTrue(sut.skipConfirmation(sut.prepare(fixed).getOrThrow()) { true }) + assertFalse(sut.skipConfirmation(sut.prepare(range, amountSats = 15uL).getOrThrow()) { true }) + verify(quickPayRepo, times(1)).reserve(15uL) + } + + @Test + fun `quickpay holds for an lnurl whose range only rounds to one amount, as on the phone`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val rounded = SendRequest.Lnurl(lnurl(14_500uL, 15_500uL), minSats = 15uL, maxSats = 15uL, payee = null) + stubLnurlInvoice() + + assertFalse(sut.skipConfirmation(sut.prepare(rounded).getOrThrow()) { true }) + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold for a spark address`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) + whenever(sparkService.prepareSend(SPARK_ADDRESS, 500uL)).thenReturn(preparedTransfer()) + val transfer = sut.prepare(SendRequest.SparkAddress(SPARK_ADDRESS), amountSats = 500uL).getOrThrow() + + assertFalse(sut.skipConfirmation(transfer) { true }) + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold unless the wallet is ready`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val prepared = preparedSend() + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertFalse(sut.skipConfirmation(prepared) { true }, "$status") + } + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold during a wipe or once the wallet stopped being ready meanwhile`() = test { + val prepared = preparedSend() + whenever(sparkService.isWiping).thenReturn(true) + assertFalse(sut.skipConfirmation(prepared) { true }) + verify(quickPayRepo, never()).reserve(any()) + + whenever(sparkService.isWiping).thenReturn(false) + whenever(quickPayRepo.reserve(any())).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Locked) } + RESERVATION + } + assertFalse(sut.skipConfirmation(prepared) { true }) + verify(quickPayRepo).release(RESERVATION) + } + + @Test + fun `a quickpay send that is paid or still pending stays counted`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + sut.send(prepared).getOrThrow() + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay send reported as pending is taken out of the day's count when it fails later`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + assertEquals(PaymentState.Pending, sut.send(prepared).getOrThrow().state) + verify(quickPayRepo, never()).release(any()) + + events.emit(SdkEvent.PaymentFailed(payment("key-0", PaymentStatus.FAILED))) + events.emit(SdkEvent.PaymentFailed(payment("key-0", PaymentStatus.FAILED))) + + verify(quickPayRepo, times(1)).release(RESERVATION) + } + + @Test + fun `a quickpay send reported as pending stays counted when it is paid later`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + sut.send(prepared).getOrThrow() + + events.emit(SdkEvent.PaymentSucceeded(payment("key-0", PaymentStatus.COMPLETED))) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay send of unknown outcome is taken out of the day's count once spark lists it failed`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + assertIs(sut.send(prepared).exceptionOrNull()) + verify(quickPayRepo, never()).release(any()) + + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment("key-0", PaymentStatus.FAILED))) + events.emit(SdkEvent.Synced) + + verify(quickPayRepo, times(1)).release(RESERVATION) + } + + @Test + fun `a quickpay send that failed or was refused is taken out of the day's count, once`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + assertIs(sut.send(prepared).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(quickPayRepo, times(1)).release(RESERVATION) + } + + @Test + fun `a quickpay send of unknown outcome stays counted`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay send that ends in an error the watch does not know stays counted`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + whenever(sparkService.releaseSend()).thenThrow(IllegalStateException("released twice")) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay yes that its caller no longer waits for is taken out of the day's count`() = test { + val reserved = CompletableDeferred() + whenever(quickPayRepo.reserve(any())).doSuspendableAnswer { reserved.await() } + val prepared = preparedSend() + val asking = launch { sut.skipConfirmation(prepared) { true } } + + asking.cancel() + reserved.complete(RESERVATION) + asking.join() + + verify(quickPayRepo, times(1)).release(RESERVATION) + // Nothing is left for a later send of it to take out a second time. + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + sut.send(prepared) + verify(quickPayRepo, times(1)).release(any()) + } + + @Test + fun `a send that was held for releases nothing when it fails`() = test { + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a request the checks refuse never reaches quickpay`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + ownInvoices.add(PAYMENT_HASH, SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY) + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + + verify(quickPayRepo, never()).reserve(any()) + } + + // 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 { + // Priced before the list shows the payment, as when the phone sent it meanwhile. + val prepared = preparedSend() + val paid = listOf(payment("random", PaymentStatus.COMPLETED)) + whenever(sparkService.listPayments(anyOrNull())).thenReturn(paid) + assertIs(sut.send(prepared).exceptionOrNull()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("random", PaymentStatus.PENDING, paymentHash = PAYMENT_HASH.uppercase()))) + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(sparkService, never()).send(any(), any()) + assertTrue(uncertainSends.watchedSends.isEmpty()) + assertFalse(sendMonitor.isSettling.value) + } + + @Test + fun `an invoice the watch's list shows pending or paid is told before the review and never priced`() = test { + whenever(sparkService.listPayments(anyOrNull())).thenReturn( + listOf(payment("key-0", PaymentStatus.PENDING, paymentHash = PAYMENT_HASH.uppercase(), amountSats = 500)), + ) + + val inFlight = assertIs( + sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull(), + ) + assertEquals("key-0", inFlight.paymentId) + assertEquals(500uL, inFlight.amountSats) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("key-0", PaymentStatus.COMPLETED))) + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + verify(sparkService, never()).syncWallet() + } + + @Test + fun `an invoice whose earlier payment failed, or that was only received, is priced again`() = test { + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("key-0", PaymentStatus.FAILED), receipt("received"))) + + assertTrue(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).isSuccess) + } + + @Test + fun `an invoice is not priced while the list of payments cannot be read`() = test { + whenever(sparkService.listPayments(anyOrNull())) + .doSuspendableAnswer { throw SdkException.StorageException("locked") } + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + + @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 { + val prepared = preparedSend() + whenever(sparkService.listPayments(anyOrNull())) + .doSuspendableAnswer { throw SdkException.StorageException("locked") } + + assertIs(sut.send(prepared).exceptionOrNull()) + 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 { + 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) + assertEquals(10.seconds, PaymentsRepo.SETTLE_TIMEOUT) + } + + @Test + fun `a send reported as pending goes on settling, and its outcome is told afterwards`() = test { + whenever(sparkService.send(any(), eq("key-0"))) + .thenReturn(payment("key-0", PaymentStatus.PENDING, amountSats = 500)) + sut.send(preparedSend()).getOrThrow() + assertEquals(listOf("key-0"), uncertainSends.watchedSends.keys.toList()) + assertTrue(sendOutcomeRepo.outcomes.value.isEmpty()) + + events.emit(SdkEvent.PaymentSucceeded(payment("key-0", PaymentStatus.COMPLETED, amountSats = 500))) + + assertEquals(listOf(SendOutcome("key-0", 500uL, isSent = true)), sendOutcomeRepo.outcomes.value) + // Remembered with its outcome until it was shown. + assertEquals(WatchedOutcome(isSent = true, amountSats = 500uL), uncertainSends.watchedSends["key-0"]?.outcome) + sendOutcomeRepo.consume("key-0") + assertTrue(uncertainSends.watchedSends.isEmpty()) + } + + @Test + fun `a retry of a watched send that is paid in time is told once, by its own result, and counted once`() = test { + val retried = QuickPayReservation("2026-11-28", cents = 51) + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION, retried) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + assertIs(sut.send(prepared).exceptionOrNull()) + assertEquals(listOf("key-0"), uncertainSends.watchedSends.keys.toList()) + + whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { + events.emit(SdkEvent.PaymentSucceeded(payment("key-0", PaymentStatus.COMPLETED))) + payment("key-0", PaymentStatus.COMPLETED) + } + val retry = preparedSend() + sut.skipConfirmation(retry) { true } + assertEquals(PaymentState.Completed, sut.send(retry).getOrThrow().state) + events.emit(SdkEvent.PaymentSucceeded(payment("key-0", PaymentStatus.COMPLETED))) + + assertTrue(sendOutcomeRepo.outcomes.value.isEmpty()) + assertTrue(uncertainSends.watchedSends.isEmpty()) + verify(quickPayRepo, times(1)).release(retried) + verify(quickPayRepo, never()).release(RESERVATION) + } + + @Test + fun `a retry of a watched send that fails in time is told once, and both counts are taken out once`() = test { + val retried = QuickPayReservation("2026-11-28", cents = 51) + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION, retried) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + assertIs(sut.send(prepared).exceptionOrNull()) + + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.FAILED)) + val retry = preparedSend() + sut.skipConfirmation(retry) { true } + assertEquals("key-0", assertIs(sut.send(retry).exceptionOrNull()).paymentId) + events.emit(SdkEvent.PaymentFailed(payment("key-0", PaymentStatus.FAILED))) + + assertTrue(sendOutcomeRepo.outcomes.value.isEmpty()) + assertTrue(uncertainSends.watchedSends.isEmpty()) + verify(quickPayRepo, times(1)).release(RESERVATION) + verify(quickPayRepo, times(1)).release(retried) + } + + @Test + fun `a send that settles in time is not watched and tells no outcome twice`() = test { + whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { + events.emit(SdkEvent.PaymentSucceeded(payment("key-0", PaymentStatus.COMPLETED))) + payment("key-0", PaymentStatus.PENDING) + } + + sut.send(preparedSend()).getOrThrow() + + assertTrue(uncertainSends.watchedSends.isEmpty()) + assertTrue(sendOutcomeRepo.outcomes.value.isEmpty()) + assertFalse(sendMonitor.isSettling.value) + } + + @Test + fun `a send of unknown outcome is watched under its key, and told once spark lists it`() = test { + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + + val unknown = assertIs(sut.send(preparedSend()).exceptionOrNull()) + + assertEquals("key-0", unknown.paymentId) + assertEquals(listOf("key-0"), uncertainSends.watchedSends.keys.toList()) + assertFalse(sendMonitor.isSettling.value) + + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment("key-0", PaymentStatus.FAILED))) + events.emit(SdkEvent.Synced) + + assertEquals(listOf(SendOutcome("key-0", 1_000uL, isSent = false)), sendOutcomeRepo.outcomes.value) + } + + @Test + fun `spark stays held for a pending send until it settles`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + val sending = async { sut.send(preparedSend()) } + assertTrue(sendMonitor.isSettling.value) + + sending.await().getOrThrow() + assertTrue(sendMonitor.isSettling.value) + + events.emit(SdkEvent.PaymentFailed(payment("key-0", PaymentStatus.FAILED))) + + assertFalse(sendMonitor.isSettling.value) + } + + @Test + fun `spark is held for a pending send for the sdk's own check window at most`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + sut.send(preparedSend()).getOrThrow() + + testScheduler.advanceTimeBy(SendOutcomeRepo.SETTLE_HOLD - PaymentsRepo.SETTLE_TIMEOUT - 1.seconds) + assertTrue(sendMonitor.isSettling.value) + + testScheduler.advanceTimeBy(2.seconds) + + assertFalse(sendMonitor.isSettling.value) + assertEquals(listOf("key-0"), uncertainSends.watchedSends.keys.toList()) + } + + @Test + fun `a send that fails while it settles releases the hold`() = test { + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.PENDING)) + val sending = async { sut.send(preparedSend()) } + + events.emit(SdkEvent.PaymentFailed(payment("key-0", PaymentStatus.FAILED))) + + assertIs(sending.await().exceptionOrNull()) + assertFalse(sendMonitor.isSettling.value) + assertTrue(uncertainSends.watchedSends.isEmpty()) + } + + @Test + fun `a send says it waits on the network only during the sync before it goes out`() = test { + val synced = CompletableDeferred() + val prepared = preparedSend() + whenever(sparkService.syncWallet()).doSuspendableAnswer { synced.await() } + whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { + assertFalse(sendMonitor.isSyncing.value) + payment("key-0", PaymentStatus.PENDING) + } + val sending = async { sut.send(prepared) } + assertTrue(sendMonitor.isSyncing.value) + + synced.complete(SparkSync(error = null, syncedAtSecs = 1uL)) + + assertFalse(sendMonitor.isSyncing.value) + assertFalse(sending.isCompleted) + sending.await() + } + + @Test + fun `a send whose sync does not reach spark stops saying it waits`() = test { + val prepared = preparedSend() + whenever(sparkService.syncWallet()).thenReturn(SparkSync(error = "offline", syncedAtSecs = null)) + + assertIs(sut.send(prepared).exceptionOrNull()) + + assertFalse(sendMonitor.isSyncing.value) + } + + @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, also after a restart`() = test { + var refusal: Throwable = SdkException.NetworkException("reset") + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw refusal } + 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 its request is under way 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()) + assertEquals(setOf("key-0"), uncertainSends.sends.keys) + + val stalled = answer + answer = CompletableDeferred(payment("key-0", PaymentStatus.COMPLETED)) + stalled.completeExceptionally(SdkException.NetworkException("reset")) + 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 is under way for the whole process until it ends, also after its caller is cancelled`() = test { + val release = CompletableDeferred() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { release.await() } + assertFalse(sendMonitor.isSending.value) + val caller = launch { sut.send(preparedSend()) } + assertTrue(sendMonitor.isSending.value) + + caller.cancel() + assertTrue(sendMonitor.isSending.value) + + release.complete(payment("key-0", PaymentStatus.COMPLETED)) + assertFalse(sendMonitor.isSending.value) + } + + @Test + fun `a send that is refused is no longer under way`() = test { + val prepared = preparedSend() + walletState.update { it.copy(status = WalletStatus.Offline) } + + assertIs(sut.send(prepared).exceptionOrNull()) + + assertFalse(sendMonitor.isSending.value) + } + + @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 + 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 `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(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()) + + 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)) + 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()) + } + + @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 `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() + 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 + 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 stubLnurlInvoice() { + 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_000uL)) + } + + 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) + + /** 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, + paymentHash: String = PAYMENT_HASH, + ) = PrepareSendPaymentResponse( + paymentMethod = SendPaymentMethod.Bolt11Invoice( + SparkFixtures.invoice(BOLT11, paymentHash, amountMsat = amountMsat), + 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/repositories/QuickPayRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt new file mode 100644 index 0000000000..2413efa15d --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -0,0 +1,290 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.update +import org.junit.Before +import org.junit.Test +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.data.FakeQuickPaySpendStore +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.QuickPayLimits +import to.bitkit.wear.models.rate +import to.bitkit.wear.test.BaseUnitTest +import java.io.IOException +import java.time.ZoneId +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes + +/** At 100 000 dollars a bitcoin one sat is a tenth of a cent, so 5 dollars are exactly 5 000 sats. */ +@OptIn(ExperimentalCoroutinesApi::class) +class QuickPayRepoTest : BaseUnitTest() { + private companion object { + /** 2026-11-28T12:00:00Z */ + const val NOW = 1_795_867_200_000L + const val FIVE_DOLLARS = 5_000uL + val LIMITS = QuickPayLimits(isEnabled = true, amountUsd = 5, dailyMultiplier = 3) + } + + private val settingsStore = mock() + private val currencyRepo = mock() + private val spend = FakeQuickPaySpendStore() + private var zone = ZoneId.of("UTC") + private val settings = MutableStateFlow(WatchSettings(quickPay = LIMITS, phoneSyncedAtMs = NOW)) + private val rates = MutableStateFlow(listOf(rate("100000"), rate("90000", quote = "EUR"))) + private var now = NOW + + private lateinit var sut: QuickPayRepo + + @Before + fun setUp() { + whenever(settingsStore.data).thenReturn(settings) + whenever(currencyRepo.rates).thenReturn(rates) + whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) + sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, { now }, { zone }) + } + + @Test + fun `a missing dollar rate is fetched before the payment is decided, while quickpay is on`() = test { + rates.update { listOf(rate("90000", quote = "EUR")) } + whenever(currencyRepo.refresh()).doSuspendableAnswer { + rates.update { listOf(rate("100000")) } + Result.success(Unit) + } + + sut.awaitRate() + + assertNotNull(sut.reserve(1uL)) + verify(currencyRepo, times(1)).refresh() + } + + @Test + fun `the wait for the rate ends after five seconds and the payment then holds`() = test { + rates.update { emptyList() } + whenever(currencyRepo.refresh()).doSuspendableAnswer { awaitCancellation() } + + val waiting = async { sut.awaitRate() } + testScheduler.advanceTimeBy(QuickPayRepo.RATE_TIMEOUT.inWholeMilliseconds - 1) + assertFalse(waiting.isCompleted) + testScheduler.advanceTimeBy(2) + + assertTrue(waiting.isCompleted) + assertNull(sut.reserve(1uL)) + assertEquals(0L, spend.spentCents) + } + + @Test + fun `no rate is fetched with one at hand, with quickpay off or before any import`() = test { + sut.awaitRate() + + rates.update { emptyList() } + settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } + sut.awaitRate() + settings.update { WatchSettings() } + sut.awaitRate() + whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) + sut.awaitRate() + + verify(currencyRepo, never()).refresh() + } + + @Test + fun `the last import decides however old it is, as the phone's own settings do`() = test { + now = NOW + 30.days.inWholeMilliseconds + assertNotNull(sut.reserve(1uL)) + + settings.update { it.copy(phoneSyncedAtMs = null) } + assertNotNull(sut.reserve(1uL)) + } + + @Test + fun `a payment of exactly the phone's amount skips the hold and one sat more does not`() = test { + assertNull(sut.reserve(FIVE_DOLLARS + 1uL)) + assertEquals(0L, spend.spentCents) + + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertEquals(500L, spend.spentCents) + } + + @Test + fun `the last sat of an amount that rounded up is worth more than the phone's amount and holds`() = test { + // 1 dollar is 1 030.9 sats, rounded up to 1 031, which are worth 1.00007 dollars. + rates.update { listOf(rate("97000")) } + settings.update { it.copy(quickPay = LIMITS.copy(amountUsd = 1)) } + + assertNull(sut.reserve(1_031uL)) + assertEquals(0L, spend.spentCents) + + assertNotNull(sut.reserve(1_030uL)) + assertEquals(100L, spend.spentCents) + } + + @Test + fun `the smallest payment skips the hold and counts as a whole cent`() = test { + assertNotNull(sut.reserve(1uL)) + + assertEquals(1L, spend.spentCents) + } + + @Test + fun `nothing skips the hold before the phone's settings were ever imported`() = test { + settings.update { WatchSettings() } + + assertNull(sut.reserve(1uL)) + assertNull(sut.reserve(FIVE_DOLLARS)) + } + + @Test + fun `nothing skips the hold while quickpay is off on the phone`() = test { + settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } + + assertNull(sut.reserve(1uL)) + } + + @Test + fun `without a dollar rate nothing skips the hold`() = test { + rates.update { listOf(rate("90000", quote = "EUR")) } + assertNull(sut.reserve(1uL)) + + for (price in listOf("n/a", "0", "-100000", "")) { + rates.update { listOf(rate(price)) } + assertNull(sut.reserve(1uL), price) + } + assertEquals(0L, spend.spentCents) + + rates.update { listOf(rate("100000")) } + assertNotNull(sut.reserve(1uL)) + } + + @Test + fun `the amount is valued and rounded as on the phone`() = test { + // 5 dollars at 64 321.98 are 7 773.39 sats, which the phone rounds to 7 773. + rates.update { listOf(rate("64321.98")) } + assertNull(sut.reserve(7_774uL)) + + // 7 773 sats are 499.97 cents, counted as 500; 100 sats are 6.43 cents, counted as 6. + assertEquals(500L, sut.reserve(7_773uL)?.cents) + assertEquals(6L, sut.reserve(100uL)?.cents) + } + + @Test + fun `a payment worth more than the phone's amount holds, so none counts for more`() = test { + // At 3 000 000 dollars a bitcoin 5 dollars round up to 167 sats, which are worth 501 cents. + rates.update { listOf(rate("3000000")) } + + assertNull(sut.reserve(167uL)) + assertEquals(498L, sut.reserve(166uL)?.cents) + } + + @Test + fun `a payment that failed is taken out of the day's count again`() = test { + repeat(2) { assertNotNull(sut.reserve(FIVE_DOLLARS)) } + val failed = assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNull(sut.reserve(1uL)) + + sut.release(failed) + + assertEquals(1_000L, spend.spentCents) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + } + + @Test + fun `a payment of an earlier day is not taken out of today's count`() = test { + val yesterday = assertNotNull(sut.reserve(FIVE_DOLLARS)) + now = NOW + 12.hours.inWholeMilliseconds + assertNotNull(sut.reserve(FIVE_DOLLARS)) + + sut.release(yesterday) + + assertEquals(500L, spend.spentCents) + spend.failure = IOException("disk") + sut.release(yesterday) + } + + @Test + fun `the limit follows the rate, not the sats`() = test { + rates.update { listOf(rate("200000")) } + + assertNull(sut.reserve(2_501uL)) + assertNotNull(sut.reserve(2_500uL)) + } + + @Test + fun `no amount and an absurd amount skip nothing`() = test { + assertNull(sut.reserve(0uL)) + assertNull(sut.reserve(ULong.MAX_VALUE)) + assertNull(sut.reserve(Long.MAX_VALUE.toULong())) + } + + @Test + fun `the day's payments stop at the phone's daily limit`() = test { + repeat(3) { assertNotNull(sut.reserve(FIVE_DOLLARS), "payment $it") } + + assertNull(sut.reserve(1uL)) + assertEquals(1_500L, spend.spentCents) + } + + @Test + fun `a payment that would pass the daily limit is refused whole`() = test { + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(4_000uL)) + + // 1 005 sats are 100.5 cents, counted as 101. + assertNull(sut.reserve(1_005uL)) + assertNotNull(sut.reserve(1_000uL)) + } + + @Test + fun `the next day starts a new count`() = test { + repeat(3) { sut.reserve(FIVE_DOLLARS) } + assertNull(sut.reserve(1uL)) + + now = NOW + 12.hours.inWholeMilliseconds + + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertEquals("2026-11-29", spend.day) + } + + @Test + fun `the day is the watch's local date where that differs from the date in UTC`() = test { + // Noon UTC on the 28th is 02:00 on the 29th at UTC+14. + zone = ZoneId.of("Pacific/Kiritimati") + repeat(3) { assertNotNull(sut.reserve(FIVE_DOLLARS)) } + assertEquals("2026-11-29", spend.day) + + // 23:00 UTC, the 28th still, and 13:00 on the 29th there: the same day. + now = NOW + 11.hours.inWholeMilliseconds + assertNull(sut.reserve(1uL)) + + // 10:30 UTC on the 29th is 00:30 on the 30th there: a new day, although UTC's date is the one counted. + now = NOW + 22.hours.inWholeMilliseconds + 30.minutes.inWholeMilliseconds + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertEquals("2026-11-30", spend.day) + } + + @Test + fun `settings or a count that cannot be read skip nothing`() = test { + spend.failure = IOException("disk") + assertNull(sut.reserve(1uL)) + + spend.failure = null + whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) + assertNull(sut.reserve(1uL)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/SendOutcomeRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/SendOutcomeRepoTest.kt new file mode 100644 index 0000000000..817cdec7d3 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/SendOutcomeRepoTest.kt @@ -0,0 +1,471 @@ +package to.bitkit.wear.repositories + +import breez_sdk_spark.PaymentStatus +import breez_sdk_spark.SdkEvent +import breez_sdk_spark.SdkException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +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.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.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.FakeUncertainSendStore +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.WatchedOutcome +import to.bitkit.wear.data.WatchedSend +import to.bitkit.wear.services.SparkFixtures.payment +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.utils.AppError +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +@OptIn(ExperimentalCoroutinesApi::class) +class SendOutcomeRepoTest : BaseUnitTest() { + private companion object { + const val ID = "key-0" + val RESERVATION = QuickPayReservation("2026-11-28", cents = 50) + val SENT = SendOutcome(ID, 1_000uL, isSent = true) + val FAILED = SendOutcome(ID, 1_000uL, isSent = false) + } + + private val sparkService = mock() + private val walletRepo = mock() + private val events = MutableSharedFlow() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 10_000uL, hasSynced = true)) + private val store = FakeUncertainSendStore() + private val quickPayRepo = mock() + private val sendMonitor = SendMonitor() + + /** Made when a test first uses it, so a test can set up what an earlier run of the app left behind. */ + private val sut by lazy { create() } + + @Before + fun setUp() { + whenever(sparkService.events).thenReturn(events) + whenever(walletRepo.walletState).thenReturn(walletState) + whenever { sparkService.listPayments(anyOrNull()) }.thenReturn(emptyList()) + whenever { walletRepo.syncBalance() }.thenReturn(Result.success(Unit)) + } + + /** A new repository over the same store, as after the app was closed and opened again. */ + private fun create() = SendOutcomeRepo(testDispatcher, sparkService, walletRepo, store, quickPayRepo, sendMonitor) + + @Test + fun `a watched payment that completes while the app is open is told as sent, once`() = test { + sut.watch(ID, reservation = null) + + events.emit(SdkEvent.PaymentPending(payment(ID, PaymentStatus.PENDING))) + assertTrue(sut.outcomes.value.isEmpty()) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + assertEquals(listOf(SENT), sut.outcomes.value) + assertEquals(WatchedOutcome(isSent = true, amountSats = 1_000uL), store.watchedSends[ID]?.outcome) + } + + @Test + fun `an outcome found while nobody looked is still told after the process ended, until it was shown`() = test { + sut.watch(ID, reservation = null) + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + // Android stopped the process before the wearer came back: the next run tells it, with no wallet needed. + walletState.update { it.copy(status = WalletStatus.Idle) } + val reopened = create() + assertEquals(listOf(FAILED), reopened.outcomes.value) + + reopened.consume(ID) + + assertTrue(reopened.outcomes.value.isEmpty()) + assertTrue(store.watchedSends.isEmpty()) + assertTrue(create().outcomes.value.isEmpty()) + } + + @Test + fun `outcomes an earlier run found are told the oldest first, and their counts are not taken out again`() = test { + store.watchedSends["key-1"] = WatchedSend("key-1", outcome = WatchedOutcome(isSent = true, amountSats = 5uL)) + store.watchedSends[ID] = + WatchedSend(ID, RESERVATION.dayKey, RESERVATION.cents, WatchedOutcome(isSent = false, amountSats = 1_000uL)) + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment(ID, PaymentStatus.FAILED), payment("key-1", PaymentStatus.COMPLETED))) + + events.emit(SdkEvent.Synced) + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + assertEquals(listOf(SendOutcome("key-1", 5uL, isSent = true), FAILED), sut.outcomes.value) + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a removed wallet's outcomes from an earlier run are not told`() = test { + store.watchedSends[ID] = WatchedSend(ID, outcome = WatchedOutcome(isSent = true, amountSats = 1_000uL)) + walletState.update { it.copy(status = WalletStatus.Missing) } + + assertTrue(sut.outcomes.value.isEmpty()) + } + + @Test + fun `a watched payment that fails while the app is open is told as failed`() = test { + sut.watch(ID, reservation = null) + + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + assertEquals(listOf(FAILED), sut.outcomes.value) + } + + @Test + fun `a payment the watch did not report is never told`() = test { + events.emit(SdkEvent.PaymentSucceeded(payment("phone", PaymentStatus.COMPLETED))) + events.emit(SdkEvent.PaymentFailed(payment("other", PaymentStatus.FAILED))) + + assertTrue(sut.outcomes.value.isEmpty()) + } + + @Test + fun `an outcome that arrived before the payment was watched is found in the list at once`() = test { + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.COMPLETED))) + + sut.watch(ID, reservation = null) + + assertEquals(listOf(SENT), sut.outcomes.value) + } + + @Test + fun `a payment resolved while the app was closed is told at the next open, when the wallet is ready`() = test { + // What an earlier run of the app left: a payment it reported as pending, which failed while it was closed. + store.watchedSends[ID] = WatchedSend(ID) + walletState.update { it.copy(status = WalletStatus.Connecting) } + // The first sync after a reconnect updates the list and emits no event. + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.FAILED))) + assertTrue(sut.outcomes.value.isEmpty()) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertEquals(listOf(FAILED), sut.outcomes.value) + assertEquals(WatchedOutcome(isSent = false, amountSats = 1_000uL), store.watchedSends[ID]?.outcome) + } + + @Test + fun `a payment still pending at the next open stays watched, and a later sync tells it`() = test { + sut.watch(ID, reservation = null) + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.PENDING))) + walletState.update { it.copy(status = WalletStatus.Paused) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertTrue(sut.outcomes.value.isEmpty()) + assertEquals(listOf(ID), store.watchedSends.keys.toList()) + + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.COMPLETED))) + events.emit(SdkEvent.Synced) + + assertEquals(listOf(SENT), sut.outcomes.value) + } + + @Test + fun `a list that cannot be read tells nothing and keeps the payment watched`() = test { + sut.watch(ID, reservation = null) + whenever(sparkService.listPayments(anyOrNull())) + .doSuspendableAnswer { throw SdkException.StorageException("locked") } + + events.emit(SdkEvent.Synced) + + assertTrue(sut.outcomes.value.isEmpty()) + assertEquals(listOf(ID), store.watchedSends.keys.toList()) + } + + @Test + fun `a payment that cannot be remembered is not announced, and watching it does not fail`() = test { + store.watchFailure = AppError("disk") + + sut.watch(ID, reservation = null) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + assertTrue(sut.outcomes.value.isEmpty()) + } + + @Test + fun `a shown outcome is taken out, and the next one stays`() = test { + sut.watch(ID, reservation = null) + sut.watch("key-1", reservation = null) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + events.emit(SdkEvent.PaymentFailed(payment("key-1", PaymentStatus.FAILED))) + + sut.consume(ID) + + assertEquals(listOf(SendOutcome("key-1", 1_000uL, isSent = false)), sut.outcomes.value) + assertEquals(listOf("key-1"), store.watchedSends.keys.toList()) + } + + @Test + fun `a shown outcome that cannot be forgotten still leaves the queue`() = test { + sut.watch(ID, reservation = null) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + store.unwatchFailure = AppError("disk") + + sut.consume(ID) + + assertTrue(sut.outcomes.value.isEmpty()) + } + + @Test + fun `an outcome found just before the screen waited for it is taken from the overlay's queue`() = test { + sut.watch(ID, reservation = null) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + assertEquals(listOf(SENT), sut.outcomes.value) + + assertEquals(SENT, sut.awaitLive(ID)) + + assertTrue(sut.outcomes.value.isEmpty()) + // Remembered until the screen has shown it. + assertEquals(listOf(ID), store.watchedSends.keys.toList()) + } + + @Test + fun `a watched payment whose retry ended sent is forgotten untold, and keeps its count`() = test { + sut.watch(ID, RESERVATION) + + assertTrue(sut.forget(ID, isSent = true)) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + assertTrue(sut.outcomes.value.isEmpty()) + assertTrue(store.watchedSends.isEmpty()) + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a watched payment whose retry ended failed is forgotten untold, and its count is taken out once`() = test { + sut.watch(ID, RESERVATION) + sut.holdConnection(ID) + + assertTrue(sut.forget(ID, isSent = false)) + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + assertTrue(sut.outcomes.value.isEmpty()) + assertFalse(sendMonitor.isSettling.value) + verify(quickPayRepo, times(1)).release(RESERVATION) + } + + @Test + fun `a retry that ends after the event already resolved the payment takes its outcome back`() = test { + sut.watch(ID, RESERVATION) + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + assertEquals(listOf(FAILED), sut.outcomes.value) + + assertTrue(sut.forget(ID, isSent = false)) + + assertTrue(sut.outcomes.value.isEmpty()) + assertTrue(store.watchedSends.isEmpty()) + verify(quickPayRepo, times(1)).release(RESERVATION) + } + + @Test + fun `forgetting a payment that is not watched, or was not counted, tells so`() = test { + sut.watch(ID, reservation = null) + + assertFalse(sut.forget("other", isSent = true)) + assertFalse(sut.forget(ID, isSent = false)) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `nothing is remembered for a wallet that is being wiped or is gone`() = test { + whenever(sparkService.isWiping).thenReturn(true) + sut.watch(ID, RESERVATION) + assertTrue(store.watchedSends.isEmpty()) + + whenever(sparkService.isWiping).thenReturn(false) + walletState.update { it.copy(status = WalletStatus.Missing) } + sut.watch(ID, RESERVATION) + + assertTrue(store.watchedSends.isEmpty()) + } + + @Test + fun `a send flow waits until every outcome was shown, also one the list holds from while the app was closed`() = + test { + store.watchedSends[ID] = WatchedSend(ID) + walletState.update { it.copy(status = WalletStatus.Connecting) } + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.FAILED))) + + val told = async { sut.awaitTold() } + + assertEquals(listOf(FAILED), sut.outcomes.value) + assertFalse(told.isCompleted) + + sut.consume(ID) + + assertTrue(told.isCompleted) + } + + @Test + fun `a send flow does not wait when nothing is left to tell`() = test { + sut.awaitTold() + + verify(sparkService, never()).listPayments(anyOrNull()) + } + + @Test + fun `a screen that waits for the outcome gets it in place of the overlay`() = test { + sut.watch(ID, reservation = null) + val live = async { sut.awaitLive(ID) } + + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + assertEquals(SENT, live.await()) + assertTrue(sut.outcomes.value.isEmpty()) + } + + @Test + fun `an outcome that arrives after the screen stopped waiting goes to the overlay`() = test { + sut.watch(ID, reservation = null) + val live = async { sut.awaitLive(ID) } + live.cancel() + + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + assertEquals(listOf(FAILED), sut.outcomes.value) + } + + @Test + fun `an outcome a screen could not show is left to the overlay, once`() = test { + sut.enqueue(SENT) + sut.enqueue(SENT) + + assertEquals(listOf(SENT), sut.outcomes.value) + } + + @Test + fun `the connection is held until the payment's outcome, or for the hold's length at most`() = test { + sut.holdConnection(ID) + sut.holdConnection(ID) + sut.holdConnection("key-1") + assertTrue(sendMonitor.isSettling.value) + + sut.releaseConnection(ID) + assertTrue(sendMonitor.isSettling.value) + + testScheduler.advanceTimeBy(SendOutcomeRepo.SETTLE_HOLD - 1.seconds) + assertTrue(sendMonitor.isSettling.value) + testScheduler.advanceTimeBy(2.seconds) + + assertFalse(sendMonitor.isSettling.value) + } + + @Test + fun `a watched payment's outcome releases the connection`() = test { + sut.holdConnection(ID) + sut.watch(ID, reservation = null) + + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + assertFalse(sendMonitor.isSettling.value) + } + + @Test + fun `a quickpay payment that failed after all is taken out of its day's count, also at the next open`() = test { + store.watchedSends[ID] = WatchedSend(ID, RESERVATION.dayKey, RESERVATION.cents) + walletState.update { it.copy(status = WalletStatus.Paused) } + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.FAILED))) + assertTrue(sut.outcomes.value.isEmpty()) + + walletState.update { it.copy(status = WalletStatus.Ready) } + events.emit(SdkEvent.Synced) + + verify(quickPayRepo, times(1)).release(RESERVATION) + assertEquals(listOf(FAILED), sut.outcomes.value) + } + + @Test + fun `a quickpay payment that was paid after all stays counted`() = test { + sut.watch(ID, RESERVATION) + + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a payment counted once keeps that count when it is watched again`() = test { + val second = QuickPayReservation("2026-11-29", cents = 50) + sut.watch(ID, RESERVATION) + assertEquals(WatchedSend(ID, "2026-11-28", 50), store.watchedSends[ID]) + + sut.watch(ID, reservation = null) + sut.watch(ID, second) + + assertEquals(WatchedSend(ID, "2026-11-28", 50), store.watchedSends[ID]) + verify(quickPayRepo).release(second) + verify(quickPayRepo, never()).release(RESERVATION) + } + + @Test + fun `a watched payment that fails syncs the balance, so what it gives back shows`() = test { + sut.watch(ID, reservation = null) + events.emit(SdkEvent.PaymentPending(payment(ID, PaymentStatus.PENDING))) + verify(walletRepo, never()).syncBalance() + + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + assertEquals(listOf(FAILED), sut.outcomes.value) + verify(walletRepo, times(1)).syncBalance() + } + + @Test + fun `a watched payment that is sent syncs the balance too`() = test { + sut.watch(ID, reservation = null) + + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + + verify(walletRepo, times(1)).syncBalance() + } + + @Test + fun `a watched payment that Spark's list shows failed syncs the balance, and one still pending does not`() = test { + sut.watch(ID, reservation = null) + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.PENDING))) + events.emit(SdkEvent.Synced) + verify(walletRepo, never()).syncBalance() + + whenever(sparkService.listPayments(anyOrNull())).thenReturn(listOf(payment(ID, PaymentStatus.FAILED))) + events.emit(SdkEvent.Synced) + + verify(walletRepo, times(1)).syncBalance() + } + + @Test + fun `a balance that cannot be synced still tells the outcome`() = test { + whenever(walletRepo.syncBalance()).thenReturn(Result.failure(AppError("no sync"))) + sut.watch(ID, reservation = null) + + events.emit(SdkEvent.PaymentFailed(payment(ID, PaymentStatus.FAILED))) + + assertEquals(listOf(FAILED), sut.outcomes.value) + } + + @Test + fun `nothing is told during a wipe, and a removed wallet's outcomes and holds are dropped`() = test { + sut.watch(ID, reservation = null) + sut.holdConnection("key-1") + sut.enqueue(SendOutcome("key-2", 5uL, isSent = true)) + whenever(sparkService.isWiping).thenReturn(true) + events.emit(SdkEvent.PaymentSucceeded(payment(ID, PaymentStatus.COMPLETED))) + assertEquals(1, sut.outcomes.value.size) + + walletState.update { it.copy(status = WalletStatus.Missing) } + + assertTrue(sut.outcomes.value.isEmpty()) + assertFalse(sendMonitor.isSettling.value) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt new file mode 100644 index 0000000000..191dc2314a --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt @@ -0,0 +1,361 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PhoneSettings +import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.QuickPayLimits +import to.bitkit.wear.security.FakeSeedStore +import to.bitkit.wear.security.SeedStoreError +import to.bitkit.wear.security.WalletSeed +import to.bitkit.wear.services.PhoneBackupReader +import to.bitkit.wear.services.PhoneBackupUnreadable +import to.bitkit.wear.services.SparkError +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.test.BaseUnitTest +import java.io.IOException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +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 + +@OptIn(ExperimentalCoroutinesApi::class) +class SettingsSyncRepoTest : BaseUnitTest() { + private companion object { + const val NOW = 1_795_867_200_000L + const val TOKEN = 4 + const val WAIT_SECS = 10L + val SEED = WalletSeed("abandon about", passphrase = "pass") + val BACKUP = """ + {"version":1,"createdAt":1,"settings":{"primaryDisplay":"FIAT","displayUnit":"CLASSIC", + "selectedCurrency":"EUR","isQuickPayEnabled":true,"quickPayAmount":10,"quickPayDailyLimitMultiplier":3}} + """.trimIndent().toByteArray() + val SETTINGS = PhoneSettings( + PrimaryDisplay.FIAT, + BitcoinDisplayUnit.CLASSIC, + "EUR", + QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), + ) + } + + private val seedStore = FakeSeedStore(SEED) + private val settingsStore = mock() + private val sparkService = mock() + private val walletRepo = mock() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 1uL, hasSynced = true)) + private val reads = mutableListOf>() + private var read: suspend () -> ByteArray? = { BACKUP } + private var elapsedMs = 90_000L + private val reader = PhoneBackupReader { seed, key -> + reads += seed to key + read() + } + + private lateinit var sut: SettingsSyncRepo + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + whenever(sparkService.wipeToken()).thenReturn(TOKEN) + whenever(sparkService.isCurrent(TOKEN)).thenReturn(true) + sut = SettingsSyncRepo( + testDispatcher, + seedStore, + reader, + settingsStore, + sparkService, + walletRepo, + { elapsedMs }, + { NOW }, + ) + } + + @Test + fun `the phone's settings backup is read with the wallet's seed and adopted`() = test { + sut.sync().getOrThrow() + + assertEquals(listOf(SEED to "SETTINGS"), reads) + verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a missing backup keeps the watch's values and turns quickpay off`() = test { + read = { null } + + sut.sync().getOrThrow() + + verify(settingsStore).clearQuickPay() + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `an unreadable backup or a newer layout keeps the watch's values and turns quickpay off`() = test { + for (raw in listOf("garbage", """{"version":2,"settings":{"isQuickPayEnabled":true}}""")) { + read = { raw.toByteArray() } + + assertTrue(sut.sync(isForced = true).isSuccess, raw) + } + + verify(settingsStore, times(2)).clearQuickPay() + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a backup that cannot be decrypted turns quickpay off at once`() = test { + read = { throw PhoneBackupUnreadable() } + + assertTrue(sut.sync().isSuccess) + + verify(settingsStore).clearQuickPay() + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `an import right after another reads nothing, unless the wearer asked or a minute passed`() = test { + sut.sync().getOrThrow() + + elapsedMs += SettingsSyncRepo.MIN_READ_GAP.inWholeMilliseconds - 1 + assertTrue(sut.sync().isSuccess) + assertEquals(1, reads.size) + + assertTrue(sut.sync(isForced = true).isSuccess) + assertEquals(2, reads.size) + + elapsedMs += SettingsSyncRepo.MIN_READ_GAP.inWholeMilliseconds + assertTrue(sut.sync().isSuccess) + assertEquals(3, reads.size) + verify(settingsStore, times(3)).applyPhoneSettings(SETTINGS, NOW) + } + + @Test + fun `a missing backup counts as read, a failed read does not, and another wallet's read never does`() = test { + read = { throw IOException("offline") } + assertTrue(sut.sync().isFailure) + read = { null } + assertTrue(sut.sync().isSuccess) + assertTrue(sut.sync().isSuccess) + assertEquals(2, reads.size) + + // A wipe and a restore later the last read was the removed wallet's. + whenever(sparkService.wipeToken()).thenReturn(TOKEN + 2) + whenever(sparkService.isCurrent(TOKEN + 2)).thenReturn(true) + assertTrue(sut.sync().isSuccess) + assertEquals(3, reads.size) + } + + @Test + fun `a second import that waited for the first joins it and reads nothing`() = test { + val gate = CompletableDeferred() + read = { + gate.await() + BACKUP + } + val first = async { sut.sync() } + val second = async { sut.sync() } + + gate.complete(Unit) + + assertTrue(first.await().isSuccess) + assertTrue(second.await().isSuccess) + assertEquals(1, reads.size) + } + + @Test + fun `a read is given up the moment the wallet stops being ready`() = test { + for (status in listOf(WalletStatus.Locked, WalletStatus.Paused, WalletStatus.Offline)) { + walletState.update { it.copy(status = WalletStatus.Ready) } + var isReadEnded = false + read = { + try { + awaitCancellation() + } finally { + isReadEnded = true + } + } + val result = async { sut.sync(isForced = true) } + assertFalse(result.isCompleted) + + walletState.update { it.copy(status = status) } + + assertIs(result.await().exceptionOrNull(), "$status") + assertTrue(isReadEnded, "$status") + } + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a read that fails changes nothing`() = test { + read = { throw IOException("offline") } + + assertIs(sut.sync().exceptionOrNull()) + + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a read that takes too long is given up and changes nothing`() = test { + var isReadEnded = false + read = { + try { + awaitCancellation() + } finally { + isReadEnded = true + } + } + + val result = async { sut.sync() } + testScheduler.advanceTimeBy(SettingsSyncRepo.READ_TIMEOUT.inWholeMilliseconds + 1) + + assertIs(result.await().exceptionOrNull()) + assertTrue(isReadEnded) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a read that blocks its thread holds back neither the import nor its caller`() { + val isReading = CountDownLatch(1) + val release = CountDownLatch(1) + val isReadEnded = CountDownLatch(1) + val blocking = SettingsSyncRepo( + Dispatchers.IO, + seedStore, + { _, _ -> + isReading.countDown() + release.await() + isReadEnded.countDown() + BACKUP + }, + settingsStore, + sparkService, + walletRepo, + { elapsedMs }, + { NOW }, + ) + try { + runBlocking { + val result = async(Dispatchers.Default) { blocking.sync() } + assertTrue(isReading.await(WAIT_SECS, TimeUnit.SECONDS)) + + // The wallet stops being ready: the import answers though the read is stuck. + walletState.update { it.copy(status = WalletStatus.Locked) } + val failure = withTimeout(WAIT_SECS.seconds) { result.await() }.exceptionOrNull() + assertIs(failure) + + // So does a caller that stops waiting, as a payment does after its 5 s. + walletState.update { it.copy(status = WalletStatus.Ready) } + val waited = withTimeout(WAIT_SECS.seconds) { withTimeoutOrNull(50) { blocking.sync(isForced = true) } } + assertNull(waited) + } + } finally { + release.countDown() + } + // The second import was only left waiting, so it lands once its read ends. + assertTrue(isReadEnded.await(WAIT_SECS, TimeUnit.SECONDS)) + runBlocking { verify(settingsStore, timeout(WAIT_SECS * 1_000)).applyPhoneSettings(SETTINGS, NOW) } + } + + @Test + fun `nothing is read unless the wallet is ready`() = test { + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertIs(sut.sync().exceptionOrNull(), "$status") + } + + assertTrue(reads.isEmpty()) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `nothing is read during a wipe or without a seed`() = test { + whenever(sparkService.wipeToken()).thenReturn(null) + assertIs(sut.sync().exceptionOrNull()) + + whenever(sparkService.wipeToken()).thenReturn(TOKEN) + seedStore.seed = null + assertIs(sut.sync().exceptionOrNull()) + + assertTrue(reads.isEmpty()) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `an import that a wipe overtook is taken out again`() = test { + val gate = CompletableDeferred() + read = { + gate.await() + BACKUP + } + val result = async { sut.sync() } + + whenever(sparkService.isCurrent(TOKEN)).thenReturn(false) + gate.complete(Unit) + + assertIs(result.await().exceptionOrNull()) + val order = inOrder(settingsStore) + order.verify(settingsStore).applyPhoneSettings(any(), any()) + order.verify(settingsStore).clearPhoneSettings() + } + + @Test + fun `an import whose caller stopped waiting still lands, and the next call finds it`() = test { + val gate = CompletableDeferred() + read = { + gate.await() + BACKUP + } + + val result = async { sut.sync() } + result.cancel() + verifyNoMoreInteractions(settingsStore) + val next = async { sut.sync() } + gate.complete(Unit) + + assertTrue(next.await().isSuccess) + assertEquals(1, reads.size) + verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a caller that goes away after the read still gets the outcome written whole`() = test { + val stored = CompletableDeferred() + whenever(settingsStore.applyPhoneSettings(any(), any())).doSuspendableAnswer { stored.await() } + val result = async { sut.sync() } + + // A wipe overtakes the import while it is stored, and the caller leaves. + whenever(sparkService.isCurrent(TOKEN)).thenReturn(false) + result.cancel() + stored.complete(Unit) + + val order = inOrder(settingsStore) + order.verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) + order.verify(settingsStore).clearPhoneSettings() + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt index 4781895178..df8089b035 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt @@ -26,6 +26,7 @@ import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.security.DeviceLock import to.bitkit.wear.security.FakeDeviceLock @@ -54,6 +55,7 @@ class WalletRepoTest : BaseUnitTest() { private val deviceLock = FakeDeviceLock() private val networkMonitor = FakeNetworkMonitor() private val foregroundMonitor = FakeForegroundMonitor() + private val sendMonitor = SendMonitor() private val seed = WalletSeed(mnemonic = "words", passphrase = null) private lateinit var sut: WalletRepo @@ -75,6 +77,7 @@ class WalletRepoTest : BaseUnitTest() { deviceLock, networkMonitor, foregroundMonitor, + sendMonitor, ) } @@ -560,6 +563,7 @@ class WalletRepoTest : BaseUnitTest() { unannouncedLock, networkMonitor, foregroundMonitor, + sendMonitor, ) whenever(seedStore.load()).thenReturn(Result.success(seed)) whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) @@ -810,6 +814,113 @@ class WalletRepoTest : BaseUnitTest() { assertEquals(WalletStatus.Offline, sut.walletState.value.status) } + @Test + fun `a start whose sync reaches Spark without a network ends offline, and ready once the network returns`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + networkMonitor.isOnline.update { false } + + sut.start() + + // A local stack is reached over adb's loopback, which airplane mode leaves up. + assertEquals(WalletState(WalletStatus.Offline, 21_000uL, hasSynced = true), sut.walletState.value) + + networkMonitor.isOnline.update { true } + + verify(sparkService, times(2)).syncWallet() + assertEquals(WalletStatus.Ready, sut.walletState.value.status) + } + + @Test + fun `a wallet paused when the network went is offline when the app returns, never ready`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(WalletRepo.BACKGROUND_GRACE + 1.seconds) + assertEquals(WalletStatus.Paused, sut.walletState.value.status) + networkMonitor.isOnline.update { false } + val seen = mutableListOf() + val collector = launch { sut.walletState.collect { seen += it.status } } + + foregroundMonitor.isForeground.update { true } + + assertEquals(WalletStatus.Offline, sut.walletState.value.status) + assertFalse(WalletStatus.Ready in seen) + collector.cancel() + } + + @Test + fun `a wallet locked when the network went is offline after the unlock, never ready`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + deviceLock.isLocked.update { true } + assertEquals(WalletStatus.Locked, sut.walletState.value.status) + networkMonitor.isOnline.update { false } + + deviceLock.isLocked.update { false } + + assertEquals(WalletStatus.Offline, sut.walletState.value.status) + } + + @Test + fun `the network going while the wallet syncs ends offline, never ready`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + whenever(sparkService.syncWallet()).doSuspendableAnswer { + networkMonitor.isOnline.update { false } + synced + } + + sut.start() + + assertEquals(WalletStatus.Offline, sut.walletState.value.status) + } + + @Test + fun `the retry of an offline wallet without a network stays offline`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + networkMonitor.isOnline.update { false } + + sut.start() + + assertEquals(WalletStatus.Offline, sut.walletState.value.status) + } + + @Test + fun `syncing the balance syncs with Spark before it loads the balance`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(20_000uL)) + sut.start() + // What a failed payment gives back is in Spark's balance only after the next sync. + whenever(sparkService.syncWallet()).doSuspendableAnswer { + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + synced + } + + val result = sut.syncBalance() + + assertTrue(result.isSuccess) + assertEquals(21_000uL, sut.walletState.value.balanceSats) + } + + @Test + fun `syncing the balance leaves a wallet alone that is not ready`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + networkMonitor.isOnline.update { false } + + val result = sut.syncBalance() + + assertTrue(result.isSuccess) + verify(sparkService, times(1)).syncWallet() + verify(sparkService, times(1)).getInfo() + } + @Test fun `the network returning leaves an error for the wearer to retry`() = test { whenever(seedStore.load()).thenReturn(Result.success(seed)) @@ -900,6 +1011,185 @@ class WalletRepoTest : BaseUnitTest() { assertEquals(WalletState(WalletStatus.Paused, 21_000uL, hasSynced = true), sut.walletState.value) } + @Test + fun `a payment that is settling keeps spark connected off screen, until its hold ends and the grace after`() = + test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + sendMonitor.holdSettling() + + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(SendOutcomeRepo.SETTLE_HOLD) + verify(sparkService, never()).disconnect() + assertEquals(WalletStatus.Ready, sut.walletState.value.status) + + sendMonitor.releaseSettling() + testScheduler.advanceTimeBy(WalletRepo.BACKGROUND_GRACE - 1.seconds) + verify(sparkService, never()).disconnect() + + testScheduler.advanceTimeBy(2.seconds) + + verify(sparkService).disconnect() + assertEquals(WalletStatus.Paused, sut.walletState.value.status) + } + + @Test + fun `a payment that starts to settle during the grace period keeps spark connected`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(WalletRepo.BACKGROUND_GRACE - 1.seconds) + sendMonitor.holdSettling() + testScheduler.advanceTimeBy(1.minutes) + + verify(sparkService, never()).disconnect() + sendMonitor.releaseSettling() + } + + @Test + fun `the app returning while a payment settles cancels the pause that waited for it`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + sendMonitor.holdSettling() + + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(1.minutes) + foregroundMonitor.isForeground.update { true } + sendMonitor.releaseSettling() + testScheduler.advanceTimeBy(WalletRepo.BACKGROUND_GRACE + 1.seconds) + + verify(sparkService, never()).disconnect() + assertEquals(WalletStatus.Ready, sut.walletState.value.status) + } + + @Test + fun `a lock disconnects at once, also while a payment is settling`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + sendMonitor.holdSettling() + + deviceLock.isLocked.update { true } + + verify(sparkService).disconnect() + assertEquals(WalletStatus.Locked, sut.walletState.value.status) + sendMonitor.releaseSettling() + } + + @Test + fun `the wallet reads locked while a lock disconnects it, never ready`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + val disconnected = CompletableDeferred() + val seen = mutableListOf() + whenever(sparkService.disconnect()).doSuspendableAnswer { + seen += sut.walletState.value.status + disconnected.await() + } + + deviceLock.isLocked.update { true } + + assertEquals(listOf(WalletStatus.Locked), seen) + assertEquals(WalletStatus.Locked, sut.walletState.value.status) + + disconnected.complete(Unit) + + assertEquals(WalletStatus.Locked, sut.walletState.value.status) + verify(sparkService, times(1)).connect(seed, 0) + } + + @Test + fun `an unlock that lands while the lock still disconnects connects again once it is over`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + val disconnected = CompletableDeferred() + whenever(sparkService.disconnect()).doSuspendableAnswer { disconnected.await() } + deviceLock.isLocked.update { true } + + deviceLock.isLocked.update { false } + assertEquals(WalletStatus.Locked, sut.walletState.value.status) + disconnected.complete(Unit) + + verify(sparkService, times(2)).connect(seed, 0) + assertEquals(WalletStatus.Ready, sut.walletState.value.status) + } + + @Test + fun `a start that an unlock began while the lock still disconnects never leaves a disconnected wallet ready`() = + test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + var isConnected = false + whenever(sparkService.connect(seed, 0)).doSuspendableAnswer { + isConnected = true + true + } + sut.start() + // The disconnect waits, as for a send that is still inside Spark. + val disconnected = CompletableDeferred() + whenever(sparkService.disconnect()).doSuspendableAnswer { + disconnected.await() + isConnected = false + } + deviceLock.isLocked.update { true } + + // The window regains focus after an unlock: this start finds Spark still connected. + deviceLock.pendingIsLocked = false + sut.refreshLock() + disconnected.complete(Unit) + + assertEquals(WalletStatus.Ready, sut.walletState.value.status) + assertTrue(isConnected) + } + + @Test + fun `a lock leaves a paused wallet paused and a removed one removed, and still disconnects`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(WalletRepo.BACKGROUND_GRACE + 1.seconds) + assertEquals(WalletStatus.Paused, sut.walletState.value.status) + + deviceLock.isLocked.update { true } + + assertEquals(WalletStatus.Paused, sut.walletState.value.status) + verify(sparkService, times(2)).disconnect() + } + + @Test + fun `the wallet is not ready while a pause disconnects it, also to an app that returned meanwhile`() = test { + whenever(seedStore.load()).thenReturn(Result.success(seed)) + whenever(sparkService.getInfo()).thenReturn(info(21_000uL)) + sut.start() + val disconnected = CompletableDeferred() + val seen = mutableListOf() + whenever(sparkService.disconnect()).doSuspendableAnswer { + seen += sut.walletState.value.status + // The app returns while Spark is still disconnecting, as for a tapped tag. + foregroundMonitor.isForeground.update { true } + seen += sut.walletState.value.status + disconnected.await() + } + + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(WalletRepo.BACKGROUND_GRACE + 1.seconds) + + assertEquals(listOf(WalletStatus.Connecting, WalletStatus.Connecting), seen) + verify(sparkService, times(1)).connect(seed, 0) + + disconnected.complete(Unit) + + verify(sparkService, times(2)).connect(seed, 0) + assertEquals(WalletStatus.Ready, sut.walletState.value.status) + } + @Test fun `the app returning within the grace period keeps spark connected`() = test { whenever(seedStore.load()).thenReturn(Result.success(seed)) diff --git a/wear/src/test/java/to/bitkit/wear/repositories/WalletWipeRecoveryTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/WalletWipeRecoveryTest.kt index 051d30ed97..8a31a4f1f4 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/WalletWipeRecoveryTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/WalletWipeRecoveryTest.kt @@ -10,6 +10,7 @@ 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.SendMonitor import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.security.FakeDeviceLock import to.bitkit.wear.security.FakeForegroundMonitor @@ -218,6 +219,7 @@ class WalletWipeRecoveryTest : BaseUnitTest() { FakeDeviceLock(), FakeNetworkMonitor(), FakeForegroundMonitor(), + SendMonitor(), ) private fun assertWiped() { 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..d8c9b834de 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 { @@ -35,8 +38,9 @@ class FakeNetworkMonitor(isOnline: Boolean = true) : NetworkMonitor { override val isOnline = MutableStateFlow(isOnline) } -class FakeNfcMonitor(state: NfcState = NfcState.On) : NfcMonitor { +class FakeNfcMonitor(state: NfcState = NfcState.On, hasCardEmulation: Boolean = true) : NfcMonitor { override val state = MutableStateFlow(state) + override val hasCardEmulation = MutableStateFlow(hasCardEmulation) } class FakeDeviceLock( diff --git a/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt b/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt new file mode 100644 index 0000000000..21a1d8f160 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt @@ -0,0 +1,67 @@ +package to.bitkit.wear.services + +import org.junit.Test +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The watch must never write to VSS. That is kept by structure, which these tests pin: the reader's interface has + * one call, a read, and the only source file that names the VSS library imports nothing of it that writes. + */ +class PhoneBackupReaderTest { + private companion object { + const val VSS_PACKAGE = "com.synonym.vssclient" + const val READER_FILE = "PhoneBackupReader.kt" + + /** + * Everything of vss-client the watch may name: the calls that derive the store id, sign in, read one object + * and shut down, and the library's error type, which calls nothing. + */ + val ALLOWED_IMPORTS = setOf( + "$VSS_PACKAGE.VssException", + "$VSS_PACKAGE.vssDeriveStoreId", + "$VSS_PACKAGE.vssGet", + "$VSS_PACKAGE.vssNewClientWithLnurlAuth", + "$VSS_PACKAGE.vssShutdownClient", + ) + } + + private val sources: List by lazy { + val module = generateSequence(File("").absoluteFile) { it.parentFile } + .map { if (it.name == "wear") it else File(it, "wear") } + .first { File(it, "src/main/java").isDirectory } + File(module, "src/main").walkTopDown().filter { it.isFile && it.extension in setOf("kt", "java") }.toList() + } + + @Test + fun `the reader can only read`() { + assertEquals(listOf("read"), PhoneBackupReader::class.java.declaredMethods.map { it.name }) + } + + @Test + fun `only the reader's file names the vss library`() { + val naming = sources.filter { VSS_PACKAGE in it.readText() }.map { it.name } + + assertEquals(listOf(READER_FILE), naming) + } + + @Test + fun `the reader imports only the error type and the calls that derive, sign in, read and shut down`() { + val reader = sources.single { it.name == READER_FILE }.readText() + val imports = reader.lines().filter { it.startsWith("import $VSS_PACKAGE") }.map { it.removePrefix("import ") } + + assertEquals(ALLOWED_IMPORTS, imports.toSet()) + // Named only through its imports: no wildcard, no alias and no fully qualified call slips past them. + assertEquals(ALLOWED_IMPORTS.size, Regex(Regex.escape(VSS_PACKAGE)).findAll(reader).count()) + assertTrue(imports.none { it.endsWith("*") || " as " in it }) + } + + @Test + fun `no source of the watch app names a vss call that writes, deletes or lists`() { + val writes = Regex("\\bvss(Store|Delete|Put\\w*|Ldk\\w*|NewLdk\\w*|NewClient|List\\w*)\\b") + val offenders = sources.filter { writes.containsMatchIn(it.readText()) }.map { it.name } + + assertEquals(emptyList(), offenders) + } +} 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()) } + } +} 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..c7b3afd998 100644 --- a/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt +++ b/wear/src/test/java/to/bitkit/wear/services/WatchSparkServiceTest.kt @@ -4,11 +4,27 @@ 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.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 @@ -24,7 +40,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 +101,159 @@ 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) + } + + @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() + } + + @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()) + 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 +270,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 +286,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 +307,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 +320,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 +338,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 +355,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 +376,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 +390,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 +402,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 +418,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 +431,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 +444,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 +459,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 +473,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 { 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..f4afd14b6a --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt @@ -0,0 +1,82 @@ +package to.bitkit.wear.tile + +import org.junit.Test +import to.bitkit.wear.models.BitcoinDisplayUnit.CLASSIC +import to.bitkit.wear.models.BitcoinDisplayUnit.MODERN +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`() { + val wallet = WalletState(WalletStatus.Idle) + + assertEquals(TileState.SignedOut, tileState(hasWallet = false, wallet, MODERN, 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), MODERN, Locale.US), + ) + assertEquals( + TileState.SignedOut, + tileState(hasWallet = true, synced.copy(status = WalletStatus.Removed), MODERN, Locale.US), + ) + } + + @Test + fun `a synced balance shows in bitcoin in the modern unit`() { + val wallet = WalletState(WalletStatus.Ready, balanceSats = 125_000uL, hasSynced = true) + + assertEquals( + TileState.Wallet(DisplayAmount("₿", "125 000")), + tileState(hasWallet = true, wallet, MODERN, Locale.US), + ) + } + + @Test + fun `a synced balance shows in bitcoin in the classic unit`() { + val wallet = WalletState(WalletStatus.Ready, balanceSats = 125_000uL, hasSynced = true) + + assertEquals( + TileState.Wallet(DisplayAmount("₿", "0.00125000")), + tileState(hasWallet = true, wallet, CLASSIC, 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, MODERN, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, unsynced, MODERN, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, failed, MODERN, 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) + + val shown = TileState.Wallet(DisplayAmount("₿", "1 000")) + + assertEquals(shown, tileState(hasWallet = true, paused, MODERN, Locale.US)) + assertEquals(shown, tileState(hasWallet = true, offline, MODERN, 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, MODERN, Locale.US)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt new file mode 100644 index 0000000000..bb701336e5 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt @@ -0,0 +1,96 @@ +package to.bitkit.wear.ui + +import org.junit.Test +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.nfc.NfcTapFilter +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** What a link or a tapped tag may open, decided for the process and not for one activity. */ +class LaunchGateTest { + private var time = 0L + private val sendMonitor = SendMonitor() + private val sut = LaunchGate(NfcTapFilter { time }, sendMonitor) + + @Test + fun `a link and the tile's request pass`() { + assertEquals(SEND, sut.admit(SEND)) + assertEquals(LaunchRequest.Receive, sut.admit(LaunchRequest.Receive)) + assertNull(sut.admit(null)) + } + + @Test + fun `a link is never taken for the repeat of a tap`() { + assertEquals(SEND, sut.admit(SEND, isTap = true)) + + assertEquals(SEND, sut.admit(SEND)) + assertEquals(SEND, sut.admit(SEND)) + } + + @Test + fun `a tapped tag passes once, and its repeats are dropped whichever activity asks`() { + assertEquals(SEND, sut.admit(SEND, isTap = true)) + + // The gate holds no activity's state: a second activity instance asks the same gate. + repeat(5) { + time += 1_000 + assertNull(sut.admit(SEND, isTap = true)) + } + } + + @Test + fun `the same tag tapped again after the window passes`() { + sut.admit(SEND, isTap = true) + time += NfcTapFilter.REPEAT_WINDOW.inWholeMilliseconds + + assertEquals(SEND, sut.admit(SEND, isTap = true)) + } + + @Test + fun `another tag passes at once`() { + sut.admit(SEND, isTap = true) + + assertEquals(OTHER, sut.admit(OTHER, isTap = true)) + } + + @Test + fun `nothing passes while a send is under way, and it passes again afterwards`() { + sendMonitor.begin() + + assertNull(sut.admit(SEND)) + assertNull(sut.admit(LaunchRequest.Receive)) + assertNull(sut.admit(OTHER, isTap = true)) + assertNull(sut.admit(null, isTap = true, tapData = "lnurlw:abc")) + + sendMonitor.end() + assertEquals(SEND, sut.admit(SEND)) + } + + @Test + fun `a tag dropped during a send stays dropped while the watch rests on it after the send`() { + sendMonitor.begin() + assertNull(sut.admit(SEND, isTap = true)) + sendMonitor.end() + + time += 1_000 + assertNull(sut.admit(SEND, isTap = true)) + } + + @Test + fun `a tag without a payment request the watch takes asks for its refusal, once`() { + assertEquals(LaunchRequest.TagRefused, sut.admit(null, isTap = true, tapData = "lnurlw:abc")) + + time += 1_000 + assertNull(sut.admit(null, isTap = true, tapData = "lnurlw:abc")) + } + + @Test + fun `a tag's intent never opens the receive qr`() { + assertEquals(LaunchRequest.TagRefused, sut.admit(LaunchRequest.Receive, isTap = true)) + } + + private companion object { + val SEND = LaunchRequest.Send("lightning:lnbcrt1invoice") + val OTHER = LaunchRequest.Send("lightning:lnbcrt1other") + } +} 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..5a7756cfe8 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -0,0 +1,140 @@ +package to.bitkit.wear.ui + +import android.content.Intent +import android.nfc.NfcAdapter +import org.junit.Test +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentUri +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class LaunchRequestTest { + @Test + fun `a payment link asks for a send of the whole link`() { + 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)) + } + } + + @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, 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) + } + } + + // region nfc tag + + @Test + fun `a tapped tag asks for a send of its payment request`() { + val links = listOf( + "lightning:lnbcrt1abc", + "bitcoin:bcrt1q?lightning=lnbcrt1abc", + "lnurl:lnurl1abc", + "lnurlp://pay.example/lnurlp/satoshi", + "spark:sprt1abc", + ) + for (link in links) { + assertEquals(LaunchRequest.Send(link), fromTag(data = link), link) + assertEquals(LaunchRequest.Send(link), fromTag(data = link, texts = listOf(link)), link) + } + } + + @Test + fun `a tag is read from its records when the intent carries them, not from the intent's data`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbcrt1abc") + + val request = fromTag(data = "lightning:lnbcrt1other", texts = NdefCodec.decodeTexts(message)) + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), request) + } + + @Test + fun `the tag another bitkit offers for its receive invoice asks for a send of that invoice`() { + val uri = nfcPaymentUri("lnbcrt1abc")!! + val tag = NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri)) + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), fromTag(data = uri, texts = tag)) + } + + @Test + fun `a bip321 tag without an address asks for a send of its lightning invoice`() { + val uri = "bitcoin:?lightning=lnbcrt1abc" + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), fromTag(data = uri, texts = listOf(uri))) + } + + @Test + fun `a tag whose records repeat one request asks for it once`() { + val texts = listOf("lightning:lnbcrt1abc", " lightning:lnbcrt1abc ") + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), fromTag(data = texts.first(), texts = texts)) + } + + @Test + fun `a tag with several different requests asks for nothing`() { + val texts = listOf("lightning:lnbcrt1abc", "lightning:lnbcrt1other") + + assertNull(fromTag(data = texts.first(), texts = texts)) + } + + @Test + fun `a tag whose request has a required parameter asks for nothing`() { + val uri = "bitcoin:bcrt1q?lightning=lnbcrt1abc&req-pop=callback" + + assertNull(fromTag(data = uri)) + assertNull(fromTag(data = uri, texts = listOf(uri))) + } + + @Test + fun `a tag with no readable record, or with another kind of link, asks for nothing`() { + assertNull(fromTag(data = "lightning:lnbcrt1abc", texts = emptyList())) + assertNull(fromTag(data = null)) + assertNull(fromTag(data = "https://bitkit.to", texts = listOf("https://bitkit.to"))) + assertNull(fromTag(data = "lnurlw://pay.example/withdraw")) + assertNull(fromTag(data = "lightning:lnbcrt1abc", texts = listOf("Coffee"))) + } + + @Test + fun `the tile's extra wins over a tag`() { + val request = LaunchRequest.from( + NfcAdapter.ACTION_NDEF_DISCOVERED, + data = "lightning:lnbcrt1abc", + open = LaunchRequest.OPEN_RECEIVE, + ) + + assertEquals(LaunchRequest.Receive, request) + } + + // endregion + + private fun fromTag(data: String?, texts: List? = null) = + LaunchRequest.from(NfcAdapter.ACTION_NDEF_DISCOVERED, data, open = null, tagTexts = texts) +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt b/wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt new file mode 100644 index 0000000000..3ac3ce4f8e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt @@ -0,0 +1,20 @@ +package to.bitkit.wear.ui + +import android.content.Intent +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ReplayedLaunchTest { + @Test + fun `a link opened again from recents is a replay, whatever else its flags say`() { + assertTrue(isReplayedLaunch(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)) + assertTrue(isReplayedLaunch(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY or Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + @Test + fun `a link that arrives now is not a replay`() { + assertFalse(isReplayedLaunch(0)) + assertFalse(isReplayedLaunch(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/SendOutcomeViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/SendOutcomeViewModelTest.kt new file mode 100644 index 0000000000..19ffe636e2 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/SendOutcomeViewModelTest.kt @@ -0,0 +1,194 @@ +package to.bitkit.wear.ui + +import kotlinx.coroutines.ExperimentalCoroutinesApi +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.doAnswer +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.AmbientMonitor +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.repositories.SendOutcome +import to.bitkit.wear.repositories.SendOutcomeRepo +import to.bitkit.wear.security.FakeDeviceLock +import to.bitkit.wear.security.FakeForegroundMonitor +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.time.Duration.Companion.seconds + +@OptIn(ExperimentalCoroutinesApi::class) +class SendOutcomeViewModelTest : BaseUnitTest() { + private companion object { + val SENT = SendOutcome("key-0", 21_000uL, isSent = true) + val FAILED = SendOutcome("key-1", 500uL, isSent = false) + val SHOWN_SENT = ShownOutcome("key-0", isSent = true, DisplayAmount("₿", "21 000")) + val SHOWN_FAILED = ShownOutcome("key-1", isSent = false, DisplayAmount("₿", "500")) + } + + private val sendOutcomeRepo = mock() + private val settingsStore = mock() + private val outcomes = MutableStateFlow>(emptyList()) + private val foregroundMonitor = FakeForegroundMonitor() + private val ambientMonitor = AmbientMonitor() + private val deviceLock = FakeDeviceLock() + private val sendMonitor = SendMonitor() + + @Before + fun setUp() { + whenever(sendOutcomeRepo.outcomes).thenReturn(outcomes) + whenever { sendOutcomeRepo.consume(any()) }.doAnswer { call -> + outcomes.update { queue -> queue.filter { it.id != call.arguments[0] } } + } + whenever(settingsStore.data).thenReturn(flowOf(WatchSettings())) + } + + private fun createSut() = SendOutcomeViewModel( + sendOutcomeRepo, + settingsStore, + foregroundMonitor, + ambientMonitor, + deviceLock, + sendMonitor, + ) + + @Test + fun `an outcome shows with its amount for a moment and is then taken out`() = test { + val sut = createSut() + assertNull(sut.uiState.value.outcome) + + outcomes.update { listOf(SENT) } + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR - 1.seconds) + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + testScheduler.advanceTimeBy(2.seconds) + + verify(sendOutcomeRepo).consume("key-0") + assertNull(sut.uiState.value.outcome) + } + + @Test + fun `an outcome found as the app opens shows at once, and a second one after it`() = test { + outcomes.update { listOf(FAILED, SENT) } + + val sut = createSut() + + assertEquals(SHOWN_FAILED, sut.uiState.value.outcome) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR + 1.seconds) + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR + 1.seconds) + assertNull(sut.uiState.value.outcome) + } + + @Test + fun `an outcome waits in ambient mode and shows in full once the watch wakes`() = test { + ambientMonitor.set(true) + val sut = createSut() + outcomes.update { listOf(SENT) } + testScheduler.advanceTimeBy(1.seconds * 60) + assertNull(sut.uiState.value.outcome) + verify(sendOutcomeRepo, never()).consume(any()) + + ambientMonitor.set(false) + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + + // Cut short by ambient mode, it is not taken out and shows again for its whole time. + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR - 1.seconds) + ambientMonitor.set(true) + assertNull(sut.uiState.value.outcome) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR) + verify(sendOutcomeRepo, never()).consume(any()) + ambientMonitor.set(false) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR - 1.seconds) + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + testScheduler.advanceTimeBy(2.seconds) + + verify(sendOutcomeRepo).consume("key-0") + } + + @Test + fun `an outcome waits while the app is off screen`() = test { + foregroundMonitor.isForeground.update { false } + val sut = createSut() + outcomes.update { listOf(FAILED) } + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR + 1.seconds) + assertNull(sut.uiState.value.outcome) + verify(sendOutcomeRepo, never()).consume(any()) + + foregroundMonitor.isForeground.update { true } + + assertEquals(SHOWN_FAILED, sut.uiState.value.outcome) + } + + @Test + fun `an outcome waits while a screen it must not cover is up, and shows once that screen is left`() = test { + sendMonitor.holdOutcomes() + val sut = createSut() + outcomes.update { listOf(SENT) } + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR + 1.seconds) + assertNull(sut.uiState.value.outcome) + verify(sendOutcomeRepo, never()).consume(any()) + + sendMonitor.releaseOutcomes() + + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR + 1.seconds) + verify(sendOutcomeRepo).consume("key-0") + } + + @Test + fun `an outcome a second screen holds back waits for both`() = test { + sendMonitor.holdOutcomes() + sendMonitor.holdOutcomes() + val sut = createSut() + outcomes.update { listOf(FAILED) } + + sendMonitor.releaseOutcomes() + assertNull(sut.uiState.value.outcome) + sendMonitor.releaseOutcomes() + + assertEquals(SHOWN_FAILED, sut.uiState.value.outcome) + } + + @Test + fun `an outcome waits under the lock screen and shows in full once the watch is unlocked`() = test { + val sut = createSut() + outcomes.update { listOf(SENT) } + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR - 1.seconds) + + deviceLock.isLocked.update { true } + assertNull(sut.uiState.value.outcome) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR + 1.seconds) + verify(sendOutcomeRepo, never()).consume(any()) + + deviceLock.isLocked.update { false } + + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + testScheduler.advanceTimeBy(SendOutcomeViewModel.SHOWN_FOR - 1.seconds) + verify(sendOutcomeRepo, never()).consume(any()) + testScheduler.advanceTimeBy(2.seconds) + verify(sendOutcomeRepo).consume("key-0") + } + + @Test + fun `an outcome never covers a send that is under way`() = test { + sendMonitor.begin() + val sut = createSut() + outcomes.update { listOf(SENT) } + assertNull(sut.uiState.value.outcome) + + sendMonitor.end() + + assertEquals(SHOWN_SENT, sut.uiState.value.outcome) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/components/NfcTagEffectTest.kt b/wear/src/test/java/to/bitkit/wear/ui/components/NfcTagEffectTest.kt new file mode 100644 index 0000000000..31215dc008 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/components/NfcTagEffectTest.kt @@ -0,0 +1,193 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.lifecycle.Lifecycle +import org.junit.After +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.nfc.NdefCodec +import to.bitkit.wear.nfc.NfcTagEmitter +import to.bitkit.wear.nfc.TagRoute +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** The tag is offered only while its screen is resumed with a request, and stopped on every way out. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class NfcTagEffectTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + private val route = FakeRoute() + private var uri by mutableStateOf(URI) + private var isShown by mutableStateOf(true) + private var isOffered = false + private var isCurrent = true + + @After + fun tearDown() { + assertEquals(route.opens, route.closes + if (NfcTagEmitter.currentMessage() == null) 0 else 1) + } + + @Test + fun `a resumed screen with a request offers it, registering once`() { + setContent() + + assertOffered(URI) + assertEquals(1, route.opens) + assertEquals(0, route.closes) + } + + @Test + fun `a screen without a request offers nothing`() { + uri = null + setContent() + + assertStopped() + assertEquals(0, route.opens) + } + + @Test + fun `the offer stops when the request is taken away, and starts again with a new one`() { + setContent() + + uri = null + composeRule.waitForIdle() + assertStopped() + + uri = OTHER_URI + composeRule.waitForIdle() + assertOffered(OTHER_URI) + } + + @Test + fun `a new request replaces the old one`() { + setContent() + + uri = OTHER_URI + composeRule.waitForIdle() + + assertOffered(OTHER_URI) + assertEquals(1, route.closes) + } + + @Test + fun `the offer stops when the screen leaves`() { + setContent() + + isShown = false + composeRule.waitForIdle() + + assertStopped() + } + + @Test + fun `the offer stops when the app is paused or stopped, and starts again when it returns`() { + setContent() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.STARTED) + composeRule.waitForIdle() + assertStopped() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.CREATED) + assertStopped() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.RESUMED) + composeRule.waitForIdle() + assertOffered(URI) + } + + @Test + fun `a request that is no longer current is not offered`() { + isCurrent = false + setContent() + + assertStopped() + assertEquals(0, route.opens) + } + + @Test + fun `a request that stopped being current while the app was away is not offered on return`() { + setContent() + composeRule.activityRule.scenario.moveToState(Lifecycle.State.STARTED) + composeRule.waitForIdle() + + isCurrent = false + composeRule.activityRule.scenario.moveToState(Lifecycle.State.RESUMED) + composeRule.waitForIdle() + + assertStopped() + assertEquals(1, route.opens) + } + + @Test + fun `the offer stops when the activity is destroyed`() { + setContent() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.DESTROYED) + + assertNull(NfcTagEmitter.currentMessage()) + assertEquals(route.opens, route.closes) + } + + @Test + fun `a tag that cannot be registered is not offered`() { + route.canOpen = false + setContent() + + assertFalse(isOffered) + assertNull(NfcTagEmitter.currentMessage()) + route.canOpen = true + route.opens = 0 + } + + private fun setContent() { + composeRule.setContent { + if (isShown) { + NfcTagEffect(uri = uri, route = route, onOfferChange = { isOffered = it }, isCurrent = { isCurrent }) + } + } + composeRule.waitForIdle() + } + + private fun assertOffered(uri: String) { + assertTrue(isOffered) + assertContentEquals(NdefCodec.encodeUriMessage(uri), NfcTagEmitter.currentMessage()) + } + + private fun assertStopped() { + assertFalse(isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertEquals(route.opens, route.closes) + } + + private class FakeRoute : TagRoute { + var canOpen = true + var opens = 0 + var closes = 0 + + override fun open(): Boolean { + opens++ + return canOpen + } + + override fun close() { + closes++ + } + } + + private companion object { + const val URI = "lightning:lnbcrt1invoice" + const val OTHER_URI = "lightning:lnbcrt1other" + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt b/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt new file mode 100644 index 0000000000..63416e26c8 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt @@ -0,0 +1,61 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.ComponentActivity +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertContentDescriptionEquals +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +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.ShownOutcome +import to.bitkit.wear.ui.screens.home.DisplayAmount + +/** + * The outcome overlay as a screen reader gets it: one line with the status and the amount, which is also its pane + * title. Whether TalkBack says it as it appears is a manual test. + */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class SendOutcomeOverlayTest { + private companion object { + val AMOUNT = DisplayAmount(symbol = "₿", text = "1 000") + fun isPane(title: String) = SemanticsMatcher.expectValue(SemanticsProperties.PaneTitle, title) + val isLiveRegion = SemanticsMatcher.keyIsDefined(SemanticsProperties.LiveRegion) + } + + @get:Rule + val composeRule = createAndroidComposeRule() + + @Test + fun `a sent outcome is a pane titled with its status and amount`() { + composeRule.setContent { WearPreview { OutcomeContent(ShownOutcome("id", isSent = true, AMOUNT)) } } + + composeRule.onNodeWithTag("WatchOutcomeSent") + .assertContentDescriptionEquals("Sent, ₿ 1 000") + .assert(isPane("Sent, ₿ 1 000")) + // Not a live region as well, which could have it said twice. + .assert(!isLiveRegion) + composeRule.onNodeWithTag("WatchOutcomeFailed").assertDoesNotExist() + } + + @Test + fun `a failed outcome is a pane titled with its status and amount`() { + composeRule.setContent { WearPreview { OutcomeContent(ShownOutcome("id", isSent = false, AMOUNT)) } } + + composeRule.onNodeWithTag("WatchOutcomeFailed") + .assertContentDescriptionEquals("Payment failed, ₿ 1 000") + .assert(isPane("Payment failed, ₿ 1 000")) + } + + @Test + fun `the outcome is one node, with nothing of its own beneath for a screen reader to step through`() { + composeRule.setContent { WearPreview { OutcomeContent(ShownOutcome("id", isSent = true, AMOUNT)) } } + + composeRule.onNodeWithTag("WatchOutcomeAmount").assertDoesNotExist() + } +} 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/activity/ActivityViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt new file mode 100644 index 0000000000..b1bdb1dfc7 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt @@ -0,0 +1,109 @@ +package to.bitkit.wear.ui.screens.activity + +import kotlinx.coroutines.flow.MutableSharedFlow +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.doReturn +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.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +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 settingsStore = mock { on { data } doReturn flowOf(WatchSettings()) } + 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, settingsStore) { 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/home/HomeViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt index 8a5eb0d6e5..5b91c1a21f 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt @@ -10,12 +10,15 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.AmbientMonitor import to.bitkit.wear.data.NfcState import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.FxRate import to.bitkit.wear.models.rate import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus @@ -24,6 +27,7 @@ import to.bitkit.wear.security.FakeNetworkMonitor import to.bitkit.wear.security.FakeNfcMonitor import to.bitkit.wear.security.SeedStoreError import to.bitkit.wear.test.BaseUnitTest +import java.util.Locale import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -38,6 +42,8 @@ class HomeViewModelTest : BaseUnitTest() { private val nfcMonitor = FakeNfcMonitor() private val networkMonitor = FakeNetworkMonitor() private val foregroundMonitor = FakeForegroundMonitor() + private val settingsSyncRepo = mock() + private val ambientMonitor = AmbientMonitor() private lateinit var sut: HomeViewModel @@ -49,7 +55,17 @@ class HomeViewModelTest : BaseUnitTest() { whenever { walletRepo.start() }.thenReturn(Result.success(Unit)) whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) whenever { currencyRepo.togglePrimaryDisplay() }.thenReturn(Result.success(Unit)) - sut = HomeViewModel(walletRepo, currencyRepo, settingsStore, nfcMonitor, networkMonitor, foregroundMonitor) + whenever { settingsSyncRepo.sync() }.thenReturn(Result.success(Unit)) + sut = HomeViewModel( + walletRepo, + currencyRepo, + settingsStore, + nfcMonitor, + networkMonitor, + foregroundMonitor, + settingsSyncRepo, + ambientMonitor, + ) } override fun onTestEnd() = foregroundMonitor.isForeground.update { false } @@ -65,6 +81,60 @@ class HomeViewModelTest : BaseUnitTest() { verify(currencyRepo, times(2)).refresh() } + @Test + fun `the phone's settings are imported when the wallet is ready, on each return and every five minutes`() = test { + verify(settingsSyncRepo, times(1)).sync() + + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL + 1.seconds) + verify(settingsSyncRepo, times(2)).sync() + + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + verify(settingsSyncRepo, times(2)).sync() + + foregroundMonitor.isForeground.update { true } + verify(settingsSyncRepo, times(3)).sync() + + walletState.update { it.copy(status = WalletStatus.Paused) } + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + verify(settingsSyncRepo, times(3)).sync() + + walletState.update { it.copy(status = WalletStatus.Ready) } + verify(settingsSyncRepo, times(4)).sync() + } + + @Test + fun `the phone's settings are not imported in ambient mode, and again once the watch wakes`() = test { + ambientMonitor.set(true) + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + verify(settingsSyncRepo, times(1)).sync() + + ambientMonitor.set(false) + verify(settingsSyncRepo, times(2)).sync() + } + + @Test + fun `the phone's settings are not imported before the wallet is ready`() = test { + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + } + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + + verify(settingsSyncRepo, times(1)).sync() + } + + @Test + fun `the balance is written in the phone's bitcoin unit`() { + val state = homeUiState( + WalletState(WalletStatus.Ready, 50_000uL, hasSynced = true), + rates = emptyList(), + settings = WatchSettings(displayUnit = BitcoinDisplayUnit.CLASSIC), + locale = Locale.US, + ) + + assertEquals(DisplayAmount("₿", "0.00050000"), state.primaryAmount) + } + @Test fun `rates are fetched every five minutes only while the app is on screen`() = test { testScheduler.advanceTimeBy(HomeViewModel.RATES_REFRESH_INTERVAL + 1.seconds) 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..8117d95898 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt @@ -0,0 +1,196 @@ +package to.bitkit.wear.ui.screens.receive + +import androidx.activity.ComponentActivity +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +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.NfcHintState +import to.bitkit.wear.ui.components.WearPreview +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertTrue +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 + private var nfcSettingsOpens = 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() + } + + @Test + fun `the nfc hint shows below the qr, clear of its square`() = assertHintPlaced() + + @Test + @Config(sdk = [34], qualifiers = "w192dp-h192dp-round") + fun `the nfc hint shows below the qr, clear of its square, on the smallest round screen`() = assertHintPlaced() + + @Test + fun `the nfc hint with nfc off sits in the same place and opens the nfc settings`() = assertDisabledHint() + + @Test + @Config(sdk = [34], qualifiers = "w192dp-h192dp-round") + fun `the nfc hint with nfc off stays on the smallest round screen and opens the nfc settings`() = + assertDisabledHint() + + private fun assertHintPlaced() { + setContent(shown, isAmbient = false, nfcHint = NfcHintState.Active) + + val hint = composeRule.onNodeWithTag("WatchReceiveNfc") + hint.assertContentDescriptionEquals("Tap to receive") + val qr = composeRule.onNodeWithTag("WatchReceiveQr").fetchSemanticsNode().boundsInRoot + val bounds = hint.fetchSemanticsNode().boundsInRoot + val screen = composeRule.onRoot().fetchSemanticsNode().boundsInRoot + assertTrue(bounds.top >= qr.bottom, "$bounds overlaps $qr") + assertTrue(bounds.bottom <= screen.bottom, "$bounds leaves $screen") + assertEquals(screen.center.x, bounds.center.x, 1f) + // Its corners stay inside the round screen. + val radius = screen.width / 2 + val corner = bounds.bottomRight - screen.center + assertTrue(corner.getDistance() <= radius, "$bounds leaves the round screen") + } + + /** The disabled hint's bounds are its touch area: on screen, around the place of the active hint's icon. */ + private fun assertDisabledHint() { + setContent(shown, isAmbient = false, nfcHint = NfcHintState.Disabled) + + val hint = composeRule.onNodeWithTag("WatchReceiveNfcOff") + hint.assertContentDescriptionEquals("NFC off") + hint.assert( + SemanticsMatcher("click label is 'Open NFC settings'") { + it.config.getOrNull(SemanticsActions.OnClick)?.label == "Open NFC settings" + } + ) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + val bounds = hint.fetchSemanticsNode().boundsInRoot + val screen = composeRule.onRoot().fetchSemanticsNode().boundsInRoot + val qr = composeRule.onNodeWithTag("WatchReceiveQr").fetchSemanticsNode().boundsInRoot + assertTrue(bounds.bottom <= screen.bottom + 0.5f, "$bounds leaves $screen") + assertTrue(bounds.top >= screen.top && bounds.left >= screen.left && bounds.right <= screen.right) + assertEquals(screen.center.x, bounds.center.x, 1f) + // The icon keeps the active hint's place: centred in the strip below the QR's square. + val density = composeRule.density.density + val iconCenterY = bounds.top + 14 * density + 10 * density + assertEquals((qr.bottom + screen.bottom) / 2, iconCenterY, 1.5f) + ShadowSystemClock.advanceBy(2.seconds.toJavaDuration()) + hint.performTouchInput { click() } + composeRule.waitForIdle() + + assertEquals(1, nfcSettingsOpens) + } + + @Test + fun `no nfc hint shows in ambient mode`() { + setContent(shown, isAmbient = true, nfcHint = NfcHintState.Active) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + } + + @Test + fun `no nfc hint shows while the qr rests`() { + setContent(shown, isAmbient = false, isResting = true, nfcHint = NfcHintState.Active) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + } + + @Test + fun `no nfc hint shows once paid`() { + setContent(paid, isAmbient = false, nfcHint = NfcHintState.Active) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + } + + @Test + fun `the qr shows without a hint when there is none`() { + setContent(shown, isAmbient = false) + + composeRule.onNodeWithTag("WatchReceiveQr").assertExists() + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + composeRule.onNodeWithTag("WatchReceiveNfcOff").assertDoesNotExist() + } + + private fun setContent( + uiState: ReceiveUiState, + isAmbient: Boolean, + isResting: Boolean = false, + nfcHint: NfcHintState = NfcHintState.Hidden, + ) { + composeRule.setContent { + WearPreview { + ReceiveQrContent( + uiState = uiState, + isAmbient = isAmbient, + onRefreshClick = {}, + isResting = isResting, + nfcHint = nfcHint, + onShowClick = { shows++ }, + onNfcSettingsClick = { nfcSettingsOpens++ }, + ) + } + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveTagTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveTagTest.kt new file mode 100644 index 0000000000..f1d2ddc5df --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveTagTest.kt @@ -0,0 +1,125 @@ +package to.bitkit.wear.ui.screens.receive + +import org.junit.Test +import to.bitkit.wear.data.NfcState +import to.bitkit.wear.ui.components.NfcHintState +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** When the receive QR offers its invoice as an NFC tag, and what the hint below the QR shows. */ +class ReceiveTagTest { + private val shown = ReceiveUiState(qrContent = "LNBCRT1INVOICE", nfcUri = URI) + + @Test + fun `the invoice on screen is offered with nfc on`() { + assertEquals(URI, tagUri()) + assertEquals(NfcHintState.Active, hint(isOffered = true)) + } + + @Test + fun `an invoice being replaced is still offered while it shows`() { + assertEquals(URI, tagUri(shown.copy(isLoading = true))) + } + + @Test + fun `nothing is offered in ambient mode`() { + assertNull(tagUri(isAmbient = true)) + assertEquals(NfcHintState.Hidden, hint(isAmbient = true, isOffered = true)) + } + + @Test + fun `nothing is offered while the qr rests`() { + assertNull(tagUri(isResting = true)) + assertEquals(NfcHintState.Hidden, hint(isResting = true, isOffered = true)) + } + + @Test + fun `nothing is offered once paid`() { + val paid = ReceiveUiState(paidAmount = DisplayAmount("₿", "21 000")) + assertNull(tagUri(paid)) + // Not even if a request were left behind in the state. + assertNull(tagUri(paid.copy(qrContent = "LNBCRT1INVOICE", nfcUri = URI))) + assertEquals(NfcHintState.Hidden, hint(paid, isOffered = true)) + } + + @Test + fun `nothing is offered while the view model holds the request back`() { + // The wallet is not ready, or the invoice expired: see ReceiveViewModelTest. + val held = shown.copy(nfcUri = null) + assertNull(tagUri(held)) + assertEquals(NfcHintState.Hidden, hint(held, isOffered = true)) + assertEquals(NfcHintState.Hidden, hint(held, nfc = NfcState.Off)) + } + + @Test + fun `nothing is offered, and no hint shows, while the repeat guard holds reader mode`() { + assertNull(tagUri(isReaderHeld = true)) + assertEquals(NfcHintState.Hidden, hint(isOffered = true, isReaderHeld = true)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Off, isReaderHeld = true)) + } + + @Test + fun `nothing is offered while there is no invoice`() { + for (state in listOf(ReceiveUiState(isLoading = true), ReceiveUiState(isError = true), ReceiveUiState())) { + assertNull(tagUri(state)) + assertNull(tagUri(state.copy(nfcUri = URI))) + assertEquals(NfcHintState.Hidden, hint(state, isOffered = true)) + } + } + + @Test + fun `nothing is offered unless nfc is on`() { + for (nfc in NfcState.entries - NfcState.On) { + assertNull(tagUri(nfc = nfc), "$nfc") + } + } + + @Test + fun `nothing is offered on a watch that cannot act as a tag`() { + assertNull(tagUri(hasCardEmulation = false)) + assertEquals(NfcHintState.Hidden, hint(hasCardEmulation = false, isOffered = true)) + assertEquals(NfcHintState.Hidden, hint(hasCardEmulation = false, nfc = NfcState.Off)) + } + + @Test + fun `the hint is the disabled one with nfc off, only where the tag would be offered`() { + assertEquals(NfcHintState.Disabled, hint(nfc = NfcState.Off)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Off, isAmbient = true)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Off, isResting = true)) + } + + @Test + fun `the hint is hidden without nfc hardware and until the nfc state was read`() { + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Unavailable, isOffered = true)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Unknown, isOffered = true)) + } + + @Test + fun `the hint is hidden while the tag is not offered, as when it could not be registered`() { + assertEquals(NfcHintState.Hidden, hint(isOffered = false)) + } + + private fun tagUri( + uiState: ReceiveUiState = shown, + nfc: NfcState = NfcState.On, + hasCardEmulation: Boolean = true, + isAmbient: Boolean = false, + isResting: Boolean = false, + isReaderHeld: Boolean = false, + ) = receiveTagUri(uiState, nfc, hasCardEmulation, isAmbient, isResting, isReaderHeld) + + private fun hint( + uiState: ReceiveUiState = shown, + nfc: NfcState = NfcState.On, + hasCardEmulation: Boolean = true, + isAmbient: Boolean = false, + isResting: Boolean = false, + isOffered: Boolean = false, + isReaderHeld: Boolean = false, + ) = receiveNfcHintState(uiState, nfc, hasCardEmulation, isAmbient, isResting, isOffered, isReaderHeld) + + private companion object { + const val URI = "lightning:lnbcrt1invoice" + } +} 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..408f1edeeb --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt @@ -0,0 +1,647 @@ +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 +import kotlinx.coroutines.flow.flowOf +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.doReturn +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.data.SendMonitor +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +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.security.FakeNfcMonitor +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 settingsStore = mock { on { data } doReturn flowOf(WatchSettings()) } + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 0uL, hasSynced = true)) + + /** The watch's wall clock, which the tests move apart from the scheduler's time, as a sleeping watch does. */ + private var now = NOW + private var revocations = 0 + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.success(null)) + } + + private val created = mutableListOf() + + private val nfcMonitor = FakeNfcMonitor() + private val sendMonitor = SendMonitor() + + private fun createSut() = + ReceiveViewModel(paymentsRepo, walletRepo, settingsStore, nfcMonitor, sendMonitor, { now }, { revocations++ }) + .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 `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 `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())) + 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())) + 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) + } + + // region nfc tag + + @Test + fun `the invoice on screen is the tag's request, as a lowercase lightning uri`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + } + + @Test + fun `no tag request exists while the invoice is made or failed`() = test { + walletState.update { it.copy(status = WalletStatus.Connecting) } + whenever(paymentsRepo.createInvoice()).thenReturn(Result.failure(ReceiveError.NotReady())) + val sut = createSut() + assertNull(sut.uiState.value.nfcUri) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertTrue(sut.uiState.value.isError) + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `the tag request is taken away whenever the wallet stops being ready, and comes back with it`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + assertNull(sut.uiState.value.nfcUri, "$status") + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent, "$status") + + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri, "$status") + } + } + + @Test + fun `a paid invoice is no longer the tag's request`() = test { + val paid = CompletableDeferred() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { paid.await() } + val sut = createSut() + val states = mutableListOf() + val collector = backgroundScope.launch { sut.uiState.collect { states += it } } + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + paid.complete(payment(21_000uL)) + + assertNull(sut.uiState.value.nfcUri) + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + // Nor in any state between the payment and the check. + val afterPaid = states.dropWhile { it.nfcUri == null }.dropWhile { it.nfcUri != null } + assertTrue(afterPaid.isNotEmpty()) + assertTrue(afterPaid.all { it.nfcUri == null }) + collector.cancel() + + // The wallet's status moving afterwards brings nothing back. + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `the replacement becomes the tag's request, and the replaced invoice never returns`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.success(invoice("lnbcrt1next", hash = "cd34"))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN - 1.seconds) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + testScheduler.advanceTimeBy(2.seconds) + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + + // Past the first invoice's expiry, and across a wallet that reconnects, the tag stays on the new invoice. + testScheduler.advanceTimeBy(EXPIRY_MARGIN_AND_MORE) + walletState.update { it.copy(status = WalletStatus.Connecting) } + assertNull(sut.uiState.value.nfcUri) + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + } + + @Test + fun `an invoice still on screen at its expiry is no longer the tag's request`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.failure(ReceiveError.NotReady())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + testScheduler.advanceTimeBy(LIFETIME.seconds - 1.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + testScheduler.advanceTimeBy(2.seconds) + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `an invoice the watch's clock takes for expired shows as a qr but is never the tag's request`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice(lifetime = 0))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertNull(sut.uiState.value.nfcUri) + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `asking for a new invoice drops the old tag request before the new invoice exists`() = test { + val next = CompletableDeferred>() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).doSuspendableAnswer { next.await() } + + sut.onRefreshClick() + + assertNull(sut.uiState.value.nfcUri) + next.complete(Result.success(invoice("lnbcrt1next", hash = "cd34"))) + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + } + + @Test + fun `a paid invoice's request is taken from the nfc service at once`() = test { + val paid = CompletableDeferred() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { paid.await() } + createSut() + assertEquals(0, revocations) + + paid.complete(payment(21_000uL)) + + assertEquals(1, revocations) + } + + @Test + fun `a payment takes whatever the nfc service holds, also when the invoice on screen has no tag request`() = 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.Connecting) } + assertNull(sut.uiState.value.nfcUri) + + paid.complete(payment(21_000uL)) + + assertEquals(1, revocations) + } + + @Test + fun `an invoice without a tag request is not current for the tag, though it has not expired`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertTrue(sut.isTagCurrent()) + + walletState.update { it.copy(status = WalletStatus.Connecting) } + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertFalse(sut.isTagCurrent()) + } + + @Test + fun `an invoice the watch slept past is not the tag's request when the wallet is ready again`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertTrue(sut.isTagCurrent()) + + // The wall clock passes the expiry while the timers stand still, as in deep sleep. + walletState.update { it.copy(status = WalletStatus.Paused) } + now += LIFETIME + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertNull(sut.uiState.value.nfcUri) + assertFalse(sut.isTagCurrent()) + } + + @Test + fun `an invoice the watch slept past loses its tag request and is replaced when the screen shows again`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.success(invoice("lnbcrt1next", lifetime = 3 * LIFETIME, hash = "cd34"))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + now += LIFETIME + 1 + // Still offered by the timers alone, which did not move; the screen asks before it starts the tag. + assertFalse(sut.isTagCurrent()) + sut.onShow() + + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + assertTrue(sut.isTagCurrent()) + verify(paymentsRepo, times(2)).createInvoice() + } + + @Test + fun `an expired invoice is not shown while its replacement is made`() = test { + val next = CompletableDeferred>() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).doSuspendableAnswer { next.await() } + + now += LIFETIME + 1 + sut.onShow() + + assertNull(sut.uiState.value.qrContent) + assertNull(sut.uiState.value.nfcUri) + assertTrue(sut.uiState.value.isLoading) + } + + @Test + fun `a screen that shows again before the invoice is due changes nothing`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + now += LIFETIME - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds - 1 + sut.onShow() + + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + verify(paymentsRepo, times(1)).createInvoice() + } + + @Test + fun `a screen that shows again after a sleep has the invoice replaced on time by the wall clock`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + // Half the invoice's life passes in sleep, where the timers stand still, and the watch stays awake after. + now += LIFETIME / 2 + sut.onShow() + verify(paymentsRepo, times(1)).createInvoice() + + val left = LIFETIME / 2 - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds + now += left - 1 + testScheduler.advanceTimeBy((left - 1).seconds) + verify(paymentsRepo, times(1)).createInvoice() + + now += 2 + testScheduler.advanceTimeBy(2.seconds) + verify(paymentsRepo, times(2)).createInvoice() + } + + @Test + fun `a screen that shows again after a sleep ends the tag request at the wall clock's expiry`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.failure(ReceiveError.NotReady())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + // The replacement is under way, and fails for as long as it is tried. + val awake = LIFETIME - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds + 1 + now += awake + testScheduler.advanceTimeBy(awake.seconds) + + // Half a minute of sleep, then awake again with less than that left on the invoice. + now += 30 + sut.onShow() + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + now += 28 + testScheduler.advanceTimeBy(28.seconds) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + // The replacement's own timer runs half a minute late, so the QR is still there; the tag is not. + now += 2 + testScheduler.advanceTimeBy(2.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `an invoice near its expiry stays on screen while the screen that shows again has it replaced`() = test { + val next = CompletableDeferred>() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).doSuspendableAnswer { next.await() } + + now += LIFETIME - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds + 1 + sut.onShow() + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + assertTrue(sut.uiState.value.isLoading) + } + + @Test + fun `an invoice paid while the wallet was away never returns as the tag's request`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + val states = mutableListOf() + walletState.update { it.copy(status = WalletStatus.Paused) } + val collector = backgroundScope.launch { sut.uiState.collect { states += it } } + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.success(payment(21_000uL))) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertTrue(states.all { it.nfcUri == null }) + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + collector.cancel() + } + + @Test + fun `the tag request stays away while spark's list cannot be read after the wallet was away`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.failure(IllegalStateException("offline"))) + + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertNull(sut.uiState.value.nfcUri) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.success(null)) + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + } + + @Test + fun `an earlier payment's outcome waits while the receive screen shows`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + val sut = createSut() + assertFalse(sendMonitor.isOutcomeHeld.value) + + sut.onShownChange(true) + sut.onShownChange(true) + assertTrue(sendMonitor.isOutcomeHeld.value) + + sut.onShownChange(false) + + assertFalse(sendMonitor.isOutcomeHeld.value) + } + + // endregion + + 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", + 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 + val EXPIRY_MARGIN_AND_MORE = ReceiveViewModel.EXPIRY_MARGIN + 10.seconds + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt new file mode 100644 index 0000000000..aa31acec2f --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt @@ -0,0 +1,133 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +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 + +/** The result of a send as it reads awake and on the always-on screen, which shows no amount. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class SendResultTest { + private companion object { + val AMOUNT = DisplayAmount(symbol = "₿", text = "1 000") + } + + @get:Rule + val composeRule = createAndroidComposeRule() + + @Test + fun `a pending result shows its amount`() { + setResult(SendStep.Done(SendResult.Pending, AMOUNT), isAmbient = false) + + composeRule.onNodeWithTag("WatchSendPending").assertIsDisplayed() + composeRule.onNodeWithTag("WatchSendResultAmount").assertTextEquals("1 000") + } + + @Test + fun `a pending result of an amount not known shows without one`() { + setResult(SendStep.Done(SendResult.Pending, amount = null), isAmbient = false) + + composeRule.onNodeWithTag("WatchSendPending").assertIsDisplayed() + composeRule.onNodeWithTag("WatchSendResultAmount").assertDoesNotExist() + } + + @Test + fun `a pending result stays readable in ambient mode, without its amount`() { + setResult(SendStep.Done(SendResult.Pending, AMOUNT), isAmbient = true) + + composeRule.onNodeWithTag("WatchSendPending").assertIsDisplayed() + composeRule.onNodeWithTag("WatchSendResultAmount").assertDoesNotExist() + composeRule.onNodeWithTag("WatchSendHidden").assertDoesNotExist() + } + + @Test + fun `an unknown result stays readable in ambient mode`() { + setResult(SendStep.Done(SendResult.Unknown, AMOUNT), isAmbient = true) + + composeRule.onNodeWithTag("WatchSendUnknown").assertIsDisplayed() + composeRule.onNodeWithTag("WatchSendResultAmount").assertDoesNotExist() + } + + @Test + fun `a sent result hides in ambient mode, with its amount`() { + setResult(SendStep.Done(SendResult.Sent, AMOUNT), isAmbient = true) + + composeRule.onNodeWithTag("WatchSendHidden").assertIsDisplayed() + composeRule.onNodeWithTag("WatchSendSent").assertDoesNotExist() + composeRule.onNodeWithTag("WatchSendResultAmount").assertDoesNotExist() + } + + @Test + fun `a pending result that turns sent or failed changes the one live line, which a screen reader is told of`() { + val isLive = SemanticsMatcher.expectValue(SemanticsProperties.LiveRegion, LiveRegionMode.Polite) + var step by mutableStateOf(SendStep.Done(SendResult.Pending, AMOUNT)) + composeRule.setContent { + WearPreview { + Content( + uiState = SendUiState(step = step), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } + } + // Compose reports a live region only for a node that was already there, so the line has to stay the same + // node. Whether TalkBack then says it is a manual test. + val line = composeRule.onNodeWithTag("WatchSendPending").assert(isLive).fetchSemanticsNode().id + + step = SendStep.Done(SendResult.Sent, AMOUNT) + val sent = composeRule.onNodeWithTag("WatchSendSent").assert(isLive).assertTextEquals("Sent") + assertEquals(line, sent.fetchSemanticsNode().id) + composeRule.onNodeWithTag("WatchSendClose").assertDoesNotExist() + + step = SendStep.Done(SendResult.Pending, AMOUNT) + composeRule.waitForIdle() + step = SendStep.Failed(SendFailure.Failed) + val failed = composeRule.onNodeWithTag("WatchSendError").assert(isLive).assertTextEquals("Payment failed") + assertEquals(line, failed.fetchSemanticsNode().id) + composeRule.onNodeWithTag("WatchSendResultAmount").assertDoesNotExist() + composeRule.onNodeWithTag("WatchSendClose").assertIsDisplayed() + } + + @Test + fun `a slow send shows the ring alone unless it waits for the network`() { + setResult(SendStep.Sending(isWaiting = false), isAmbient = false) + + composeRule.onNodeWithTag("WatchSendSending").assertIsDisplayed() + composeRule.onNodeWithTag("WatchSendWaiting").assertDoesNotExist() + } + + private fun setResult(step: SendStep, isAmbient: Boolean) { + composeRule.setContent { + WearPreview { + Content( + uiState = SendUiState(step = step), + isAmbient = isAmbient, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } + } + } +} 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..a9f5251bdf --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendReviewTest.kt @@ -0,0 +1,89 @@ +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, + 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 new file mode 100644 index 0000000000..ce361f69c1 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -0,0 +1,1134 @@ +package to.bitkit.wear.ui.screens.send + +import android.nfc.NfcAdapter +import androidx.lifecycle.SavedStateHandle +import app.cash.turbine.test +import breez_sdk_spark.PrepareSendPaymentResponse +import com.synonym.bitkitcore.LnurlPayData +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +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.eq +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.data.AmbientMonitor +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.BitcoinDisplayUnit +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.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentUri +import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.PaymentsRepo +import to.bitkit.wear.repositories.SendOutcome +import to.bitkit.wear.repositories.SendOutcomeRepo +import to.bitkit.wear.repositories.WalletRepo +import to.bitkit.wear.repositories.WalletState +import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.security.FakeDeviceLock +import to.bitkit.wear.security.FakeForegroundMonitor +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.LaunchRequest +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)) + private val foregroundMonitor = FakeForegroundMonitor() + private val ambientMonitor = AmbientMonitor() + private val sendMonitor = SendMonitor() + private val sendOutcomeRepo = mock() + private val deviceLock = FakeDeviceLock() + + /** What the pending result's wait for its payment's outcome ends with, once completed. */ + private val outcome = CompletableDeferred() + + /** The outcomes of earlier payments the wearer was not shown yet. */ + private val outcomes = MutableStateFlow>(emptyList()) + private var isAwaitingOutcome = false + private var elapsedMs = 1_000_000L + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + whenever(currencyRepo.rates).thenReturn(MutableStateFlow(emptyList())) + whenever(settingsStore.data).thenReturn(flowOf(WatchSettings())) + whenever { paymentsRepo.skipConfirmation(any(), any()) }.thenReturn(false) + whenever { walletRepo.start() }.thenReturn(Result.success(Unit)) + whenever(sendOutcomeRepo.outcomes).thenReturn(outcomes) + whenever { sendOutcomeRepo.awaitTold() }.doSuspendableAnswer { + outcomes.first { it.isEmpty() } + Unit + } + whenever { sendOutcomeRepo.awaitLive(any()) }.doSuspendableAnswer { + isAwaitingOutcome = true + try { + outcome.await() + } finally { + isAwaitingOutcome = false + } + } + } + + private fun createSut( + savedState: SavedStateHandle = SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT)), + ) = SendViewModel( + savedState, + paymentsRepo, + walletRepo, + currencyRepo, + settingsStore, + foregroundMonitor, + ambientMonitor, + sendMonitor, + sendOutcomeRepo, + deviceLock, + ) { elapsedMs } + + @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 `quickpay sends without the review or the hold and ends on the same result`() = test { + val prepared = prepared() + stubInvoice(prepared) + val sent = CompletableDeferred>() + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { sent.await() } + + val sut = createSut() + + assertIs(sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + verify(paymentsRepo, times(1)).skipConfirmation(eq(prepared), any()) + + sent.complete(Result.success(payment(PaymentState.Completed))) + + val done = assertIs(sut.uiState.value.step) + assertEquals(SendResult.Sent, done.result) + verify(paymentsRepo, times(1)).send(prepared) + } + + @Test + fun `quickpay still applies to a link that opened the app and waited a moment for the wallet`() = test { + for (status in listOf(WalletStatus.Idle, WalletStatus.Paused, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Connecting) } + elapsedMs += SendViewModel.QUICKPAY_WINDOW.inWholeMilliseconds + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, "$status") + } + } + + @Test + fun `a link that waited long for the wallet is reviewed and held, never paid under quickpay`() = test { + for (status in listOf(WalletStatus.Error, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + elapsedMs += SendViewModel.QUICKPAY_WINDOW.inWholeMilliseconds + 1 + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, "$status") + assertTrue(sut.uiState.value.isHoldEnabled) + } + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a wallet that turns offline while the link waits for it ends on the offline error, without quickpay`() = + test { + for (status in listOf(WalletStatus.Idle, WalletStatus.Paused, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + assertEquals(SendStep.Loading, sut.uiState.value.step, "$status") + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Offline) } + // The network returns well within the QuickPay window: the dropped request stays dropped. + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertEquals(SendStep.Offline, sut.uiState.value.step, "$status") + assertFalse(sut.uiState.value.isHoldEnabled) + sut.onHoldComplete() + } + verify(paymentsRepo, never()).parse(any()) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a wallet that turns offline while quickpay is decided ends on the offline error and sends nothing`() = + test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { + walletState.update { state -> state.copy(status = WalletStatus.Offline) } + it.getArgument<() -> Boolean>(1)() + } + + val sut = createSut() + + assertEquals(SendStep.Offline, sut.uiState.value.step) + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals(SendStep.Offline, sut.uiState.value.step) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a flow rebuilt for a link that already had one is reviewed and held, never paid under quickpay`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + // The first flow ends on the review, as when the watch dimmed, and the wearer leaves without paying. + ambientMonitor.set(true) + val savedState = SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT)) + assertIs(createSut(savedState).uiState.value.step) + ambientMonitor.set(false) + + // The process is killed and the back stack restored: a new flow on what the first one saved. + val restored = SavedStateHandle(savedState.keys().associateWith { savedState.get(it) }) + val sut = createSut(restored) + + assertIs(sut.uiState.value.step) + assertTrue(sut.uiState.value.isHoldEnabled) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + + sut.onHoldComplete() + + verify(paymentsRepo).send(prepared) + } + + @Test + fun `a link whose wait crossed a lock, a pause or ambient mode is reviewed and held`() = test { + val interruptions = listOf Unit>>( + "lock" to { + walletState.update { it.copy(status = WalletStatus.Locked) } + walletState.update { it.copy(status = WalletStatus.Connecting) } + }, + "pause" to { + foregroundMonitor.isForeground.update { false } + foregroundMonitor.isForeground.update { true } + }, + "wallet pause" to { + walletState.update { it.copy(status = WalletStatus.Paused) } + walletState.update { it.copy(status = WalletStatus.Connecting) } + }, + "ambient" to { + ambientMonitor.set(true) + ambientMonitor.set(false) + }, + ) + for ((name, interrupt) in interruptions) { + walletState.update { it.copy(status = WalletStatus.Connecting) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + interrupt() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, name) + } + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a link that arrives on a locked watch is reviewed and held`() = test { + walletState.update { it.copy(status = WalletStatus.Locked) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + } + + @Test + fun `a wearer who looked away while quickpay was decided is asked to hold`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { + ambientMonitor.set(true) + it.getArgument<() -> Boolean>(1)() + } + + val sut = createSut() + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a flow whose screen left while quickpay was decided sends nothing`() = test { + val prepared = prepared() + stubInvoice(prepared) + val decision = CompletableDeferred() + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { + decision.await() + it.getArgument<() -> Boolean>(1)() + } + val sut = createSut() + + // Another request took this flow off the back stack: its entry stops before its view model is cleared. + sut.onShownChange(false) + decision.complete(Unit) + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a flow whose screen is not shown asks no quickpay`() = test { + val parsed = CompletableDeferred() + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.prepare(any(), anyOrNull())).doSuspendableAnswer { + parsed.await() + Result.success(prepared) + } + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + val sut = createSut() + + sut.onShownChange(false) + parsed.complete(Unit) + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a quickpay send that fails shows the failure like any other`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.Failed())) + + val sut = createSut() + + assertEquals(SendStep.Failed(SendFailure.Failed), sut.uiState.value.step) + } + + @Test + fun `without quickpay the send waits on review, written in the phone's unit`() = test { + whenever(settingsStore.data) + .thenReturn(flowOf(WatchSettings(displayUnit = BitcoinDisplayUnit.CLASSIC))) + val prepared = prepared(amountSats = 21_000uL) + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(false) + + val sut = createSut() + + val step = assertIs(sut.uiState.value.step) + assertEquals("0.00021000", step.amount.text) + verify(paymentsRepo, never()).send(any()) + } + + @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) + sut.onHoldComplete() + verify(paymentsRepo, never()).send(any()) + } + + @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 + 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.effects.test { + sut.onHoldComplete() + assertEquals(SendStep.Done(SendResult.Pending, DisplayAmount("₿", "21 000")), sut.uiState.value.step) + assertFalse(sut.uiState.value.isBusy) + + testScheduler.advanceTimeBy(SendViewModel.PENDING_CLOSE_DELAY - 1.seconds) + expectNoEvents() + testScheduler.advanceTimeBy(2.seconds) + assertEquals(SendEffect.Close, awaitItem()) + } + assertEquals(5.seconds, SendViewModel.PENDING_CLOSE_DELAY) + } + + @Test + fun `a pending payment that settles while it shows switches to sent, with the amount paid`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + + sut.effects.test { + sut.onHoldComplete() + assertEquals(SendResult.Pending, assertIs(sut.uiState.value.step).result) + + outcome.complete(SendOutcome("send", 20_000uL, isSent = true)) + + assertEquals(SendStep.Done(SendResult.Sent, DisplayAmount("₿", "20 000")), sut.uiState.value.step) + expectNoEvents() + testScheduler.advanceTimeBy(SendViewModel.SENT_CLOSE_DELAY + 1.seconds) + assertEquals(SendEffect.Close, awaitItem()) + } + verify(sendOutcomeRepo, never()).enqueue(any()) + verify(sendOutcomeRepo).consume("send") + } + + @Test + fun `a pending payment that fails while it shows switches to the failure and stays`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + + sut.effects.test { + sut.onHoldComplete() + + outcome.complete(SendOutcome("send", 21_000uL, isSent = false)) + + assertEquals(SendStep.Failed(SendFailure.Failed), sut.uiState.value.step) + testScheduler.advanceTimeBy(SendViewModel.PENDING_CLOSE_DELAY + 1.seconds) + expectNoEvents() + } + verify(sendOutcomeRepo).consume("send") + } + + @Test + fun `an outcome that arrives in ambient mode is left to the overlay and the flow closes`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + + sut.effects.test { + sut.onHoldComplete() + ambientMonitor.set(true) + + outcome.complete(SendOutcome("send", 21_000uL, isSent = true)) + + assertEquals(SendEffect.Close, awaitItem()) + } + verify(sendOutcomeRepo).enqueue(SendOutcome("send", 21_000uL, isSent = true)) + verify(sendOutcomeRepo, never()).consume(any()) + } + + @Test + fun `an outcome that arrives with the app off screen is left to the overlay, never shown unseen`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + sut.onHoldComplete() + // The wearer pressed the crown on "Pending": the view model lives on behind the watch face. + foregroundMonitor.isForeground.update { false } + + outcome.complete(SendOutcome("send", 21_000uL, isSent = false)) + + verify(sendOutcomeRepo).enqueue(SendOutcome("send", 21_000uL, isSent = false)) + verify(sendOutcomeRepo, never()).consume(any()) + assertEquals(SendResult.Pending, assertIs(sut.uiState.value.step).result) + } + + @Test + fun `an outcome that arrives under the lock screen is left to the overlay and the flow closes`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + + sut.effects.test { + sut.onHoldComplete() + // The keyguard came up over "Pending", with the display awake and the app still in front. + deviceLock.isLocked.update { true } + + outcome.complete(SendOutcome("send", 21_000uL, isSent = true)) + + assertEquals(SendEffect.Close, awaitItem()) + } + verify(sendOutcomeRepo).enqueue(SendOutcome("send", 21_000uL, isSent = true)) + verify(sendOutcomeRepo, never()).consume(any()) + assertEquals(SendResult.Pending, assertIs(sut.uiState.value.step).result) + } + + @Test + fun `an outcome that arrives after the flow's screen left is left to the overlay`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + sut.onHoldComplete() + sut.onShownChange(false) + + outcome.complete(SendOutcome("send", 21_000uL, isSent = true)) + + verify(sendOutcomeRepo).enqueue(SendOutcome("send", 21_000uL, isSent = true)) + verify(sendOutcomeRepo, never()).consume(any()) + } + + @Test + fun `a flow waits at its start until earlier outcomes were shown, and no outcome covers it from then on`() = test { + val prepared = prepared() + stubInvoice(prepared) + outcomes.update { listOf(SendOutcome("earlier", 1_000uL, isSent = false)) } + + val sut = createSut() + + assertEquals(SendStep.Loading, sut.uiState.value.step) + assertFalse(sendMonitor.isOutcomeHeld.value) + verify(paymentsRepo, never()).parse(any()) + + outcomes.update { emptyList() } + + assertIs(sut.uiState.value.step) + assertTrue(sendMonitor.isOutcomeHeld.value) + + // A flow whose screen left, as for the app in the background, holds nothing back; back on screen it does. + sut.onShownChange(false) + assertFalse(sendMonitor.isOutcomeHeld.value) + sut.onShownChange(true) + assertTrue(sendMonitor.isOutcomeHeld.value) + } + + @Test + fun `a flow whose wallet left while it waited for an outcome waits for the wallet again`() = test { + stubInvoice(prepared()) + outcomes.update { listOf(SendOutcome("earlier", 1_000uL, isSent = false)) } + val sut = createSut() + + walletState.update { it.copy(status = WalletStatus.Connecting) } + outcomes.update { emptyList() } + + assertEquals(SendStep.Loading, sut.uiState.value.step) + verify(paymentsRepo, never()).parse(any()) + // Still at its start, so an outcome that arrives now is shown before the flow goes on. + assertFalse(sendMonitor.isOutcomeHeld.value) + outcomes.update { listOf(SendOutcome("later", 500uL, isSent = true)) } + + walletState.update { it.copy(status = WalletStatus.Ready) } + + verify(paymentsRepo, never()).parse(any()) + + outcomes.update { emptyList() } + + assertIs(sut.uiState.value.step) + assertTrue(sendMonitor.isOutcomeHeld.value) + } + + @Test + fun `quickpay pays only after an earlier payment's outcome was shown`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + outcomes.update { listOf(SendOutcome("earlier", 21_000uL, isSent = false)) } + + val sut = createSut() + testScheduler.advanceTimeBy(2.seconds) + + verify(paymentsRepo, never()).send(any()) + + outcomes.update { emptyList() } + + verify(paymentsRepo).send(prepared) + assertEquals(SendResult.Sent, assertIs(sut.uiState.value.step).result) + } + + @Test + fun `a flow that ended offline while it waited at its start is not covered either`() = test { + outcomes.update { listOf(SendOutcome("earlier", 1_000uL, isSent = false)) } + val sut = createSut() + + walletState.update { it.copy(status = WalletStatus.Offline) } + + assertEquals(SendStep.Offline, sut.uiState.value.step) + assertTrue(sendMonitor.isOutcomeHeld.value) + } + + @Test + fun `an outcome after the pending result closed is not waited for`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Pending))) + val sut = createSut() + + sut.onHoldComplete() + assertTrue(isAwaitingOutcome) + verify(sendOutcomeRepo).awaitLive("send") + testScheduler.advanceTimeBy(SendViewModel.PENDING_CLOSE_DELAY + 1.seconds) + + assertFalse(isAwaitingOutcome) + } + + @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(paymentId = "key-0"))) + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendResult.Unknown, assertIs(sut.uiState.value.step).result) + verify(sendOutcomeRepo).awaitLive("key-0") + } + + @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 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)) + whenever(paymentsRepo.prepare(INVOICE, null)) + .thenReturn(Result.failure(SendError.InFlight("key-0", amountSats = 20_000uL))) + + val sut = createSut() + + sut.effects.test { + assertEquals(SendStep.Done(SendResult.Pending, DisplayAmount("₿", "20 000")), sut.uiState.value.step) + verify(sendOutcomeRepo).awaitLive("key-0") + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + testScheduler.advanceTimeBy(SendViewModel.PENDING_CLOSE_DELAY + 1.seconds) + assertEquals(SendEffect.Close, awaitItem()) + } + } + + @Test + fun `a hold that finds the wallet not ready returns to the review, with the hold off until it is ready`() = + test { + val prepared = prepared() + stubInvoice(prepared) + val started = CompletableDeferred>() + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.NotReady())) + whenever(walletRepo.start()).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Connecting) } + started.await() + } + val sut = createSut() + + sut.onHoldComplete() + + assertIs(sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + assertFalse(sut.uiState.value.isBusy) + sut.onHoldComplete() + verify(paymentsRepo, times(1)).send(prepared) + + walletState.update { it.copy(status = WalletStatus.Ready) } + started.complete(Result.success(Unit)) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + + assertTrue(sut.uiState.value.isHoldEnabled) + sut.onHoldComplete() + assertEquals(SendResult.Sent, assertIs(sut.uiState.value.step).result) + } + + @Test + fun `a hold that finds the wallet not ready keeps the hold off when the wallet's status never changed`() = test { + val prepared = prepared() + stubInvoice(prepared) + val started = CompletableDeferred>() + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.NotReady())) + whenever(walletRepo.start()).doSuspendableAnswer { started.await() } + val sut = createSut() + + sut.onHoldComplete() + assertIs(sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + + started.complete(Result.success(Unit)) + + assertTrue(sut.uiState.value.isHoldEnabled) + } + + @Test + fun `a hold that finds the wallet not ready ends on the offline error when the wallet is offline`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.NotReady())) + whenever(walletRepo.start()).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Offline) } + Result.failure(SendError.NotReady()) + } + val sut = createSut() + + sut.onHoldComplete() + + assertEquals(SendStep.Offline, sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + } + + @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) + + sendMonitor.setSyncing(true) + testScheduler.advanceTimeBy(SendViewModel.WAITING_HINT_DELAY + 1.seconds) + assertEquals(SendStep.Sending(isWaiting = true), sut.uiState.value.step) + } + + @Test + fun `a send whose wallet went offline says it is waiting for the network, until it is back`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + sut.onHoldComplete() + + walletState.update { it.copy(status = WalletStatus.Offline) } + testScheduler.advanceTimeBy(SendViewModel.WAITING_HINT_DELAY + 1.seconds) + assertEquals(SendStep.Sending(isWaiting = true), sut.uiState.value.step) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertEquals(SendStep.Sending(isWaiting = false), sut.uiState.value.step) + } + + @Test + fun `a send stops blaming the network once spark has it, and never does while it settles`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + sut.onHoldComplete() + sendMonitor.setSyncing(true) + testScheduler.advanceTimeBy(SendViewModel.WAITING_HINT_DELAY + 1.seconds) + + sendMonitor.setSyncing(false) + + assertEquals(SendStep.Sending(isWaiting = false), sut.uiState.value.step) + testScheduler.advanceTimeBy(PaymentsRepo.SETTLE_TIMEOUT) + assertEquals(SendStep.Sending(isWaiting = false), 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) + } + + // region nfc tap + + @Test + fun `a tapped tag opens the review of its request, and nothing is sent before the hold`() = test { + stubInvoice(prepared(amountSats = 21_000uL)) + + val sut = createSut(tapped()) + + val step = assertIs(sut.uiState.value.step) + assertEquals(DisplayAmount("₿", "21 000"), step.amount) + verify(paymentsRepo).parse(INPUT) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a tap counts as attended, so quickpay pays it without the hold`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut(tapped()) + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, times(1)).send(prepared) + } + + @Test + fun `a tap that brought the app back from the background is attended once the wallet runs again`() = test { + walletState.update { it.copy(status = WalletStatus.Paused) } + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut(tapped()) + walletState.update { it.copy(status = WalletStatus.Connecting) } + elapsedMs += 5_000 + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step) + } + + @Test + fun `a tap on a locked watch, or one the wearer left, is reviewed and held`() = test { + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + walletState.update { it.copy(status = WalletStatus.Locked) } + val locked = createSut(tapped()) + walletState.update { it.copy(status = WalletStatus.Ready) } + assertIs(locked.uiState.value.step) + + walletState.update { it.copy(status = WalletStatus.Connecting) } + val left = createSut(tapped()) + foregroundMonitor.isForeground.value = false + foregroundMonitor.isForeground.value = true + walletState.update { it.copy(status = WalletStatus.Ready) } + assertIs(left.uiState.value.step) + + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a tap while offline ends on the offline error`() = test { + walletState.update { it.copy(status = WalletStatus.Offline) } + + val sut = createSut(tapped()) + + assertEquals(SendStep.Offline, sut.uiState.value.step) + verify(paymentsRepo, never()).parse(any()) + } + + @Test + fun `a tap on a tag with the watch's own invoice ends on the own invoice error`() = test { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.failure(SendError.OwnInvoice())) + + val sut = createSut(tapped()) + + assertEquals(SendStep.Failed(SendFailure.OwnInvoice), sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + /** + * The saved state of the send flow a tapped tag opens: the tag another Bitkit offers for [BOLT11], read from its + * record, taken as a launch request and passed on as the route's input, as `WearNavHost` does. + */ + private fun tapped(): SavedStateHandle { + val uri = nfcPaymentUri(BOLT11)!! + val request = LaunchRequest.from( + NfcAdapter.ACTION_NDEF_DISCOVERED, + data = uri, + open = null, + tagTexts = NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri)), + ) + return SavedStateHandle(mapOf(Routes.SEND_INPUT to assertIs(request).input)) + } + + // endregion + + 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", + expiresAtSecs = 1_800_003_600uL, + sparkPayee = null, + transferKey = "transfer", + ) + + 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") + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/TagRefusedTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/TagRefusedTest.kt new file mode 100644 index 0000000000..7451a0a679 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/TagRefusedTest.kt @@ -0,0 +1,38 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +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 kotlin.test.assertEquals + +/** What a tapped tag without a payment request the watch takes ends on. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class TagRefusedTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + @Test + fun `a refused tag shows one line and closes on its one action`() { + var closes = 0 + composeRule.setContent { + WearPreview { + TagRefusedScreen(onClose = { closes++ }) + } + } + + composeRule.onNodeWithTag("WatchTagRefused").assertTextEquals("Not supported") + composeRule.onNodeWithTag("WatchSendClose").performClick() + composeRule.waitForIdle() + + assertEquals(1, closes) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt index cc40e995f0..24645030b9 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt @@ -1,25 +1,80 @@ package to.bitkit.wear.ui.screens.settings +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import org.junit.Before import org.junit.Test +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.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.services.SparkError import to.bitkit.wear.test.BaseUnitTest +import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class SettingsViewModelTest : BaseUnitTest() { private val walletRepo = mock() + private val settingsSyncRepo = mock() + private val settingsStore = mock() + private val settings = MutableStateFlow(WatchSettings()) private lateinit var sut: SettingsViewModel @Before fun setUp() { - sut = SettingsViewModel(walletRepo) + whenever(settingsStore.data).thenReturn(settings) + sut = SettingsViewModel(walletRepo, settingsSyncRepo, settingsStore) + } + + @Test + fun `the row shows when the phone's settings were last imported`() = test { + assertNull(sut.uiState.value.phoneSyncedAtMs) + + settings.update { it.copy(phoneSyncedAtMs = 1_000L) } + + assertEquals(1_000L, sut.uiState.value.phoneSyncedAtMs) + } + + @Test + fun `a tap on the row imports the phone's settings once at a time`() = test { + val gate = CompletableDeferred>() + whenever { settingsSyncRepo.sync(isForced = true) }.doSuspendableAnswer { gate.await() } + + sut.onSyncClick() + sut.onSyncClick() + + assertTrue(sut.uiState.value.isSyncing) + verify(settingsSyncRepo, times(1)).sync(isForced = true) + + gate.complete(Result.success(Unit)) + + assertFalse(sut.uiState.value.isSyncing) + assertFalse(sut.uiState.value.isSyncFailed) + } + + @Test + fun `a tapped import that fails shows the failure until the next tap`() = test { + whenever { settingsSyncRepo.sync(isForced = true) }.thenReturn(Result.failure(SparkError.WipeInProgress())) + + sut.onSyncClick() + + assertTrue(sut.uiState.value.isSyncFailed) + assertFalse(sut.uiState.value.isSyncing) + + whenever { settingsSyncRepo.sync(isForced = true) }.thenReturn(Result.success(Unit)) + sut.onSyncClick() + + assertFalse(sut.uiState.value.isSyncFailed) } @Test diff --git a/wear/src/test/resources/phone-backup-contract.json b/wear/src/test/resources/phone-backup-contract.json new file mode 100644 index 0000000000..e7d438d82d --- /dev/null +++ b/wear/src/test/resources/phone-backup-contract.json @@ -0,0 +1,31 @@ +{ + "settingsKey": "SETTINGS", + "settingsBackup": { + "version": 1, + "settings": { + "primaryDisplay": "FIAT", + "displayUnit": "CLASSIC", + "selectedCurrency": "EUR", + "isQuickPayEnabled": true, + "quickPayAmount": 10, + "quickPayDailyLimitMultiplier": 3 + } + }, + "networks": { + "BITCOIN": { + "storeIdPrefix": "bitkit_v1_bitcoin", + "vssServerUrl": "https://api.bitkit.to/vss_rs_auth", + "lnurlAuthServerUrl": "https://bitkit.to/lnurl_auth/auth" + }, + "TESTNET": { + "storeIdPrefix": "bitkit_v1_testnet", + "vssServerUrl": "https://bitkit.stag0.blocktank.to/vss_rs_auth", + "lnurlAuthServerUrl": "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" + }, + "REGTEST": { + "storeIdPrefix": "bitkit_v1_regtest", + "vssServerUrl": "https://bitkit.stag0.blocktank.to/vss_rs_auth", + "lnurlAuthServerUrl": "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" + } + } +}