From 1b639b6ed2e0ed3b21c4113230d2140672ec9a85 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Fri, 20 Nov 2026 17:01:40 -0500 Subject: [PATCH 1/3] feat: wake the wallet to claim pubky swaps --- .../main/java/to/bitkit/data/CacheStore.kt | 2 + .../main/java/to/bitkit/fcm/WakeHandlers.kt | 20 +- .../repositories/PubkySwapsRouteRepo.kt | 107 ++++++++++ .../java/to/bitkit/repositories/WakeRepo.kt | 43 ++++ .../java/to/bitkit/services/WakeService.kt | 26 +++ .../java/to/bitkit/fcm/WakeHandlersTest.kt | 52 +++++ .../repositories/PubkySwapsRouteRepoTest.kt | 196 +++++++++++++++++- .../to/bitkit/repositories/WakeRepoTest.kt | 64 ++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 1 + 9 files changed, 509 insertions(+), 2 deletions(-) create mode 100644 app/src/test/java/to/bitkit/fcm/WakeHandlersTest.kt diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 47e49828e2..29e857b672 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -360,6 +360,8 @@ data class AppCacheData( val unfinishedPubkySwaps: List = listOf(), /** The hold payment hash of each unfinished Pubky Swaps route by swap id, so its failure stops the swap. */ val pubkySwapHoldHashes: Map = mapOf(), + /** The wake grant id of each unfinished Pubky Swaps route by swap id, so the grant is revoked once it ends. */ + val pubkySwapWakeGrants: Map = mapOf(), /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ val sparkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/fcm/WakeHandlers.kt b/app/src/main/java/to/bitkit/fcm/WakeHandlers.kt index cf1335e605..ab62752a9d 100644 --- a/app/src/main/java/to/bitkit/fcm/WakeHandlers.kt +++ b/app/src/main/java/to/bitkit/fcm/WakeHandlers.kt @@ -3,12 +3,14 @@ package to.bitkit.fcm import android.content.Context import com.synonym.bitkitcore.WakeAckOutcome import com.synonym.bitkitcore.WakeEnvelope +import dagger.Lazy import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.first import to.bitkit.data.WakeStore import to.bitkit.data.WakeTopicText import to.bitkit.ext.nowMs import to.bitkit.ext.runSuspendCatching +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.WakeConfig import to.bitkit.services.WakeService import to.bitkit.ui.ID_NOTIFICATION_SKIPPED @@ -36,10 +38,16 @@ class WakeHandlers internal constructor(private val byTopic: Map, +) : WakeHandler { + override suspend fun handle(wake: WakeEnvelope) = pubkySwapsRouteRepo.get().claimAfterWake().getOrThrow() +} + /** * Posts the topic's display text as a local notification. A v1 wake is always a data message, which Android shows * nothing for, so this is how an alert topic reaches the user. diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 4beceec66c..67cf3d7280 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -12,6 +12,7 @@ import com.synonym.bitkitcore.pubkySwapsAdvance import com.synonym.bitkitcore.pubkySwapsCommitRoute import com.synonym.bitkitcore.pubkySwapsRestore import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment +import com.synonym.bitkitcore.pubkySwapsSendWakeCapability import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineStart @@ -43,6 +44,7 @@ import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching +import to.bitkit.fcm.WakeHandlers import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.toCoreNetwork @@ -70,6 +72,7 @@ class PubkySwapsRouteRepo @Inject constructor( private val pubkyRepo: PubkyRepo, private val lightningRepo: LightningRepo, private val cacheStore: CacheStore, + private val wakeRepo: WakeRepo, ) { companion object { private const val TAG = "PubkySwapsRouteRepo" @@ -88,6 +91,15 @@ class PubkySwapsRouteRepo @Inject constructor( /** How long a restore waits before asking again the providers it read only in part. */ private val RESTORE_RETRY_INTERVAL = 1.minutes + + /** How long a swap's wake grant lasts: past a reverse swap's claim window. It is revoked once the swap ends. */ + private const val WAKE_GRANT_DAYS = 2u + + /** How often a `swap.claimable` wake advances the unfinished swaps. */ + private val WAKE_CLAIM_POLL_INTERVAL = 3.seconds + + /** How long a `swap.claimable` wake advances the unfinished swaps before it leaves them to the background. */ + private val WAKE_CLAIM_TIMEOUT = 2.minutes } private val scope = appScope(ioDispatcher, TAG) @@ -264,9 +276,99 @@ class PubkySwapsRouteRepo @Inject constructor( pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase).also { committed.add(it.swapId) track(listOf(it.swapId)) + if (it.providerTakesWake) scope.launch(walletJob) { handOverWake(it.swapId) } + } + } + + // Best effort: the swap goes on without a wake, as it does on a provider that takes none. + private suspend fun handOverWake(swapId: String) { + val grant = wakeRepo.createGrant(WakeHandlers.SWAP_CLAIMABLE_TOPIC, WAKE_GRANT_DAYS) + .onFailure { Logger.warn("Failed to create wake grant for Pubky Swaps route '$swapId'", it, context = TAG) } + .getOrNull() ?: return + if (!rememberWakeGrant(swapId, grant.id)) { + revokeWakeGrant(swapId, grant.id) + return + } + val isClaimable = withSecrets { mnemonic, passphrase -> + pubkySwapsSendWakeCapability(swapId, grant.gatewayUrl, grant.token, grant.expiresAt, mnemonic, passphrase) + }.getOrElse { + Logger.warn("Failed to send wake capability of Pubky Swaps route '$swapId'", it, context = TAG) + forgetWakeGrant(swapId) + return + } + Logger.info("Sent wake capability of Pubky Swaps route '$swapId'", context = TAG) + // The provider sends no wake for a swap already claimable, so it is advanced now instead. + if (!isClaimable) return + forgetWakeGrant(swapId) + if (swapId !in claiming) advanceInBackground(swapId) + } + + private suspend fun rememberWakeGrant(swapId: String, grantId: String): Boolean { + var isKept = false + runSuspendCatching { + cacheStore.update { + isKept = swapId in it.unfinishedPubkySwaps + if (!isKept) return@update it + it.copy(pubkySwapWakeGrants = it.pubkySwapWakeGrants + (swapId to grantId)) + } + }.onFailure { + isKept = false + Logger.warn("Failed to record wake grant of Pubky Swaps route '$swapId'", it, context = TAG) + } + return isKept + } + + private suspend fun forgetWakeGrant(swapId: String) { + var grantId: String? = null + runSuspendCatching { + cacheStore.update { + grantId = it.pubkySwapWakeGrants[swapId] + it.copy(pubkySwapWakeGrants = it.pubkySwapWakeGrants - swapId) + } + }.onFailure { Logger.warn("Failed to drop wake grant of Pubky Swaps route '$swapId'", it, context = TAG) } + grantId?.let { revokeWakeGrant(swapId, it) } + } + + private suspend fun revokeWakeGrant(swapId: String, grantId: String) { + wakeRepo.revokeGrant(grantId) + .onFailure { Logger.warn("Failed to revoke wake grant of Pubky Swaps route '$swapId'", it, context = TAG) } + } + + /** + * Claims the swaps a `swap.claimable` wake is for. The wake names none, so every unfinished swap is advanced until + * each has its claim broadcast or has ended, or [WAKE_CLAIM_TIMEOUT] passes, and then left to the background + * advance, which rebroadcasts the claims until they confirm. Fails when no claim went out and a swap is still open. + */ + suspend fun claimAfterWake(): Result = runSuspendCatching { + val swapIds = cacheStore.data.first().unfinishedPubkySwaps.filterNot { it in dropped } + val open = swapIds.toMutableSet() + var isClaimBroadcast = false + withTimeoutOrNull(WAKE_CLAIM_TIMEOUT) { + while (open.isNotEmpty()) { + open.toList().forEach { swapId -> + val advance = advanceOnce(swapId) + val isEnded = when (advance.getOrNull()?.state) { + is PubkySwapRouteState.ClaimBroadcast, is PubkySwapRouteState.Claimed -> { + isClaimBroadcast = true + true + } + is PubkySwapRouteState.Failed -> true + null -> advance.exceptionOrNull() is PubkySwapException.NotFound + else -> false + } + if (isEnded) open.remove(swapId) + } + if (open.isNotEmpty()) delay(WAKE_CLAIM_POLL_INTERVAL) + } } + swapIds.filterNot { it in claiming }.forEach { advanceInBackground(it) } + if (!isClaimBroadcast && open.isNotEmpty()) throw PubkySwapWakeUnclaimedException(open.toList()) } + private suspend fun advanceOnce(swapId: String) = + withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } + .onFailure { Logger.warn("Failed to advance Pubky Swaps route '$swapId' after a wake", it, context = TAG) } + /** Records the hold payment of a committed swap, so its failure stops the swap, also after a restart. */ suspend fun watchHold(swapId: String, holdPaymentHash: String) { runSuspendCatching { @@ -415,6 +517,7 @@ class PubkySwapsRouteRepo @Inject constructor( ) } }.onFailure { Logger.warn("Failed to drop finished Pubky Swaps route '$swapId'", it, context = TAG) } + forgetWakeGrant(swapId) } private suspend fun pollClaim( @@ -478,6 +581,10 @@ data class RestoredPubkySwaps( /** The swap's hold payment failed, so the provider never funds its lockup and the swap is not advanced further. */ class PubkySwapHoldFailedException(swapId: String) : AppError("Hold payment of swap '$swapId' failed") +/** A `swap.claimable` wake after which no claim went out and these swaps are still open. */ +class PubkySwapWakeUnclaimedException(swapIds: List) : + AppError("No claim went out after a wake for swaps '$swapIds'") + /** A claim wait that ran out with the swap still open: its hold payment may yet settle. */ class PubkySwapClaimTimeoutException(swapId: String, cause: Throwable?) : AppError("Swap '$swapId' not claimed yet", cause) diff --git a/app/src/main/java/to/bitkit/repositories/WakeRepo.kt b/app/src/main/java/to/bitkit/repositories/WakeRepo.kt index 0ccf3a6d82..099415d12f 100644 --- a/app/src/main/java/to/bitkit/repositories/WakeRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WakeRepo.kt @@ -185,6 +185,44 @@ class WakeRepo @Inject constructor( } } + /** + * Lets a peer wake this install on [topic] for [expiresInDays], as its `pk:` identity, else its `ln:` one. Null + * while wakes are off, the user has not opted in or the gateway holds no registration of this install. + */ + suspend fun createGrant(topic: String, expiresInDays: UInt): Result = + withContext(ioDispatcher) { + runSuspendCatching { + val gatewayUrl = wakeConfig.gatewayUrl ?: return@runSuspendCatching null + if (!wakeConfig.isRegistrationEnabled || !wakeConfig.isOptedIn()) return@runSuspendCatching null + if (credentialStore.registrationState().fingerprint == null) return@runSuspendCatching null + val credentials = credentialStore.load() ?: return@runSuspendCatching null + val recipient = pubkyRepo.wakeIdentity().getOrNull() + ?: lightningRepo.getNodeId()?.let(::lightningWakeIdentity) + ?: return@runSuspendCatching null + val grant = wakeService.createGrant( + gatewayUrl = gatewayUrl, + deviceSecret = credentials.deviceSecret, + recipient = recipient, + topics = listOf(topic), + expiresInDays = expiresInDays, + ) + IssuedWakeGrant( + gatewayUrl = gatewayUrl, + id = grant.id, + token = grant.token, + expiresAt = grant.expiresAt, + ) + } + } + + /** Revokes a grant [createGrant] made. Repeating it is harmless. */ + suspend fun revokeGrant(grantId: String): Result = withContext(ioDispatcher) { + runSuspendCatching { + val device = requireDevice() + wakeService.revokeGrant(device.gatewayUrl, device.credentials.deviceSecret, grantId) + } + } + private suspend fun sync(pushToken: String?, force: Boolean): WakeSync { val gatewayUrl = wakeConfig.gatewayUrl if (gatewayUrl == null || !wakeConfig.isRegistrationEnabled) return WakeSync.Off @@ -376,6 +414,11 @@ class WakeRepo @Inject constructor( } } +/** A grant this install made and the gateway it holds on. [toString] leaves the bearer [token] out. */ +class IssuedWakeGrant(val gatewayUrl: String, val id: String, val token: String, val expiresAt: ULong) { + override fun toString(): String = "IssuedWakeGrant(id='$id')" +} + /** What [WakeRepo.syncRegistration] did. */ sealed interface WakeSync { /** Wakes are off in this build, or it is an E2E build. */ diff --git a/app/src/main/java/to/bitkit/services/WakeService.kt b/app/src/main/java/to/bitkit/services/WakeService.kt index df024c2d76..98e2d6cee5 100644 --- a/app/src/main/java/to/bitkit/services/WakeService.kt +++ b/app/src/main/java/to/bitkit/services/WakeService.kt @@ -5,6 +5,7 @@ import com.synonym.bitkitcore.WakeDevice import com.synonym.bitkitcore.WakeEnvelope import com.synonym.bitkitcore.WakeEnvironment import com.synonym.bitkitcore.WakeException +import com.synonym.bitkitcore.WakeGrant import com.synonym.bitkitcore.WakeIdentityProof import com.synonym.bitkitcore.WakePlatform import com.synonym.bitkitcore.WakeRegistration @@ -13,6 +14,7 @@ import com.synonym.bitkitcore.WakeServerInfo import com.synonym.bitkitcore.WakeTopic import com.synonym.bitkitcore.wakeAck import com.synonym.bitkitcore.wakeClearPresence +import com.synonym.bitkitcore.wakeCreateGrant import com.synonym.bitkitcore.wakeDecryptPush import com.synonym.bitkitcore.wakeGenerateDeviceSecret import com.synonym.bitkitcore.wakeGenerateInstallId @@ -21,6 +23,7 @@ import com.synonym.bitkitcore.wakeGetDevice import com.synonym.bitkitcore.wakeListTopics import com.synonym.bitkitcore.wakePrepareRegistration import com.synonym.bitkitcore.wakeRegister +import com.synonym.bitkitcore.wakeRevokeGrant import com.synonym.bitkitcore.wakeSendTest import com.synonym.bitkitcore.wakeServerInfo import com.synonym.bitkitcore.wakeSetPresence @@ -128,6 +131,29 @@ class WakeService @Inject constructor() { suspend fun listTopics(gatewayUrl: String): List = ServiceQueue.CORE.background { wakeListTopics(gatewayUrl = gatewayUrl) } + + suspend fun createGrant( + gatewayUrl: String, + deviceSecret: String, + recipient: String, + topics: List, + expiresInDays: UInt, + ): WakeGrant = ServiceQueue.CORE.background { + wakeCreateGrant( + gatewayUrl = gatewayUrl, + deviceSecret = deviceSecret, + recipient = recipient, + topics = topics, + perHour = null, + perDay = null, + expiresInDays = expiresInDays, + ) + } + + suspend fun revokeGrant(gatewayUrl: String, deviceSecret: String, grantId: String) = + ServiceQueue.CORE.background { + wakeRevokeGrant(gatewayUrl = gatewayUrl, deviceSecret = deviceSecret, grantId = grantId) + } } /** diff --git a/app/src/test/java/to/bitkit/fcm/WakeHandlersTest.kt b/app/src/test/java/to/bitkit/fcm/WakeHandlersTest.kt new file mode 100644 index 0000000000..d6b58f48b3 --- /dev/null +++ b/app/src/test/java/to/bitkit/fcm/WakeHandlersTest.kt @@ -0,0 +1,52 @@ +package to.bitkit.fcm + +import com.synonym.bitkitcore.WakeAckOutcome +import com.synonym.bitkitcore.WakeEnvelope +import dagger.Lazy +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.repositories.PubkySwapWakeUnclaimedException +import to.bitkit.repositories.PubkySwapsRouteRepo +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +class WakeHandlersTest : BaseUnitTest() { + private val pubkySwapsRouteRepo = mock() + + private val sut = WakeHandlers( + alertHandler = mock(), + swapClaimableHandler = SwapClaimableWakeHandler(Lazy { pubkySwapsRouteRepo }), + ) + + @Test + fun `a swap claimable wake whose claims went out is handled`() = test { + whenever(pubkySwapsRouteRepo.claimAfterWake()).thenReturn(Result.success(Unit)) + + assertEquals(WakeAckOutcome.HANDLED, sut.handle(wake(WakeHandlers.SWAP_CLAIMABLE_TOPIC))) + } + + @Test + fun `a swap claimable wake after which no claim went out failed`() = test { + whenever(pubkySwapsRouteRepo.claimAfterWake()) + .thenReturn(Result.failure(PubkySwapWakeUnclaimedException(listOf("swap")))) + + assertEquals(WakeAckOutcome.FAILED, sut.handle(wake(WakeHandlers.SWAP_CLAIMABLE_TOPIC))) + } + + @Test + fun `a wake of a topic the app does not handle gets no handler`() = test { + assertEquals(WakeAckOutcome.NO_HANDLER, sut.handle(wake("paykit.sync"))) + } + + private fun wake(topic: String) = WakeEnvelope( + version = 1u, + id = "wake-1", + topic = topic, + urgency = "background", + deadline = null, + payloadJson = null, + createdAt = null, + fallback = false, + ) +} diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index 2992250666..9c13865e9c 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -8,6 +8,7 @@ import com.synonym.bitkitcore.PubkySwapRouteStatus import com.synonym.bitkitcore.pubkySwapsAdvance import com.synonym.bitkitcore.pubkySwapsCommitRoute import com.synonym.bitkitcore.pubkySwapsRestore +import com.synonym.bitkitcore.pubkySwapsSendWakeCapability import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async @@ -18,6 +19,7 @@ import kotlinx.coroutines.flow.toList import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -28,6 +30,7 @@ import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus +import org.mockito.MockedStatic import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull @@ -46,6 +49,7 @@ import to.bitkit.models.PubkyProfile import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue import kotlin.time.Duration.Companion.minutes @@ -58,6 +62,11 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { private const val CLAIM_TXID = "claim" private const val CONFIRMED_CLAIM_TXID = "confirmed" private const val HOLD_HASH = "hold" + private const val GATEWAY_URL = "https://wake.bitkit.to" + private const val GRANT_ID = "grant" + private const val GRANT_TOKEN = "wkg_grant_token" + private const val GRANT_EXPIRES_AT = 1_790_172_800uL + private val GRANT = IssuedWakeGrant(GATEWAY_URL, GRANT_ID, GRANT_TOKEN, GRANT_EXPIRES_AT) /** The Kotlin facade holding bitkit-core's top-level functions, which Kotlin sources cannot name. */ private val CORE: Class<*> = Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt") @@ -70,6 +79,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { private val lightningRepo = mock { on { nodeEvents } doReturn nodeEvents } private val cacheData = MutableStateFlow(AppCacheData()) private val cacheStore = mock { on { data } doReturn cacheData } + private val wakeRepo = mock() private lateinit var sut: PubkySwapsRouteRepo @Before @@ -85,6 +95,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { pubkyRepo = pubkyRepo, lightningRepo = lightningRepo, cacheStore = cacheStore, + wakeRepo = wakeRepo, ) } @@ -203,6 +214,156 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + @Test + fun `commit hands a grant to a provider that takes a wake`() = test { + whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(GRANT)) + + committingWithWake(false) { core -> + core.verify { + runBlocking { + pubkySwapsSendWakeCapability( + eq(SWAP_ID), + eq(GATEWAY_URL), + eq(GRANT_TOKEN), + eq(GRANT_EXPIRES_AT), + any(), + anyOrNull(), + ) + } + } + } + + verify(wakeRepo).createGrant("swap.claimable", 2u) + assertEquals(mapOf(SWAP_ID to GRANT_ID), cacheData.value.pubkySwapWakeGrants) + verify(wakeRepo, never()).revokeGrant(any()) + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `commit hands no grant to a provider that takes no wake`() = test { + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsCommitRoute(any(), any(), any(), anyOrNull()) } } + .thenReturn(swapPayment(providerTakesWake = false)) + + sut.commit("quote").getOrThrow() + advanceUntilIdle() + } + + verify(wakeRepo, never()).createGrant(any(), any()) + } + + @Test + fun `an install not registered for wakes sends no capability`() = test { + whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(null)) + + committingWithWake(false) { core -> + core.verify( + { runBlocking { pubkySwapsSendWakeCapability(any(), any(), any(), any(), any(), anyOrNull()) } }, + never(), + ) + } + + assertEquals(emptyMap(), cacheData.value.pubkySwapWakeGrants) + } + + @Test + fun `a capability the provider refuses has its grant revoked`() = test { + whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(GRANT)) + whenever(wakeRepo.revokeGrant(any())).thenReturn(Result.success(Unit)) + + committingWithWake(PubkySwapException.Refused("invalid_request", "gateway not allowed")) + + verify(wakeRepo).revokeGrant(GRANT_ID) + assertEquals(emptyMap(), cacheData.value.pubkySwapWakeGrants) + assertEquals(listOf(SWAP_ID), cacheData.value.unfinishedPubkySwaps, "The swap goes on without a wake") + } + + @Test + fun `a swap already claimable is advanced now and its grant revoked`() = test { + whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(GRANT)) + whenever(wakeRepo.revokeGrant(any())).thenReturn(Result.success(Unit)) + + committingWithWake( + true, + PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID), + PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID), + ) { core -> core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, atLeast(1)) } + + verify(wakeRepo).revokeGrant(GRANT_ID) + assertEquals(emptyMap(), cacheData.value.pubkySwapWakeGrants) + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) + } + + @Test + fun `a swap that ends has its grant revoked`() = test { + whenever(wakeRepo.revokeGrant(any())).thenReturn(Result.success(Unit)) + cacheData.value = AppCacheData( + unfinishedPubkySwaps = listOf(SWAP_ID), + pubkySwapWakeGrants = mapOf(SWAP_ID to GRANT_ID), + ) + + sut.dropFailedSwap(SWAP_ID) + + verify(wakeRepo).revokeGrant(GRANT_ID) + assertEquals(emptyMap(), cacheData.value.pubkySwapWakeGrants) + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `a wake claims the unfinished swaps and leaves their claims to the background`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + val result = advancing( + PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u), + PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID), + PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID), + ) { + sut.claimAfterWake().also { advanceUntilIdle() } + } + + assertTrue(result.isSuccess) + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps, "The background advance saw the claim confirm") + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `a wake after which no claim went out fails`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + var isWakeOver = false + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }.thenAnswer { + when (isWakeOver) { + false -> status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u)) + true -> status(PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID)) + } + } + + val result = sut.claimAfterWake() + isWakeOver = true + advanceUntilIdle() + + assertIs(result.exceptionOrNull()) + // Advanced every 3 s for 2 minutes. + core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, atLeast(40)) + } + } + + @Test + fun `a wake with no unfinished swap is handled`() = test { + assertTrue(sut.claimAfterWake().isSuccess) + } + + @Test + fun `a wake treats a swap that failed as ended`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + + val result = advancing(PubkySwapRouteState.Failed("refunded")) { + sut.claimAfterWake().also { advanceUntilIdle() } + } + + assertTrue(result.isSuccess) + assertFalse(SWAP_ID in cacheData.value.unfinishedPubkySwaps) + } + @Test @OptIn(ExperimentalCoroutinesApi::class) fun `resumeUnfinishedSwaps advances a stored swap past an hour until its claim confirms`() = test { @@ -510,7 +671,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } - private fun swapPayment() = PubkySwapRoutePayment( + private fun swapPayment(providerTakesWake: Boolean = false) = PubkySwapRoutePayment( swapId = SWAP_ID, invoice = "invoice", debitSat = 20_100u, @@ -518,8 +679,41 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { destinationAddress = "address", htlcAddress = "htlc", timeoutBlockHeight = 0u, + providerTakesWake = providerTakesWake, ) + /** Commits a swap whose provider takes a wake, answering the wake capability with [capability]. */ + @OptIn(ExperimentalCoroutinesApi::class) + private suspend fun TestScope.committingWithWake( + capability: Any, + vararg advances: PubkySwapRouteState, + verifyCore: (MockedStatic<*>) -> Unit = {}, + ) = mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsCommitRoute(any(), any(), any(), anyOrNull()) } } + .thenReturn(swapPayment(providerTakesWake = true)) + val send = core.`when` { + runBlocking { + pubkySwapsSendWakeCapability( + eq(SWAP_ID), + eq(GATEWAY_URL), + eq(GRANT_TOKEN), + eq(GRANT_EXPIRES_AT), + any(), + anyOrNull(), + ) + } + } + if (capability is Throwable) send.thenAnswer { throw capability } else send.thenReturn(capability) + if (advances.isNotEmpty()) { + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(advances.first()), *advances.drop(1).map(::status).toTypedArray()) + } + + sut.commit("quote").getOrThrow() + advanceUntilIdle() + verifyCore(core) + } + private fun report( restored: List = emptyList(), incomplete: List = emptyList(), diff --git a/app/src/test/java/to/bitkit/repositories/WakeRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WakeRepoTest.kt index 2119cf34df..d4297a587b 100644 --- a/app/src/test/java/to/bitkit/repositories/WakeRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WakeRepoTest.kt @@ -4,6 +4,7 @@ import com.google.android.gms.tasks.Task import com.google.firebase.messaging.FirebaseMessaging import com.synonym.bitkitcore.WakeEnvironment import com.synonym.bitkitcore.WakeException +import com.synonym.bitkitcore.WakeGrant import com.synonym.bitkitcore.WakeIdentityProof import com.synonym.bitkitcore.WakePlatform import com.synonym.bitkitcore.WakeRegistration @@ -39,6 +40,7 @@ import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -61,6 +63,10 @@ class WakeRepoTest : BaseUnitTest() { private const val PK_SIGNATURE = "pk-signature" private const val LN_IDENTITY = "ln:$NODE_ID" private const val PK_IDENTITY = "pk:$PUBKY_KEY" + private const val SWAP_TOPIC = "swap.claimable" + private const val GRANT_ID = "6f9619ff-8b86-d011-b42d-00c04fc964ff" + private const val GRANT_TOKEN = "wkg_6f9619ff8b86d011b42d00c04fc964ff_token" + private const val GRANT_EXPIRES_AT = 1_790_172_800uL private val ACCEPTED = WakeRegistration( deviceId = "device-1", @@ -366,6 +372,64 @@ class WakeRepoTest : BaseUnitTest() { verify(wakeService).unregister(GATEWAY_URL, CREDENTIALS.deviceSecret) } + @Test + fun `a grant lets the pk identity of a registered install be woken`() = test { + whenever(pubkyRepo.wakeIdentity()).thenReturn(Result.success(PK_IDENTITY)) + sut.syncRegistration().getOrThrow() + whenever { wakeService.createGrant(any(), any(), any(), any(), any()) }.thenReturn(grant(PK_IDENTITY)) + + val issued = assertNotNull(sut.createGrant(SWAP_TOPIC, 2u).getOrThrow()) + + verify(wakeService).createGrant(GATEWAY_URL, CREDENTIALS.deviceSecret, PK_IDENTITY, listOf(SWAP_TOPIC), 2u) + assertEquals(GATEWAY_URL, issued.gatewayUrl) + assertEquals(GRANT_ID, issued.id) + assertEquals(GRANT_TOKEN, issued.token) + assertEquals(GRANT_EXPIRES_AT, issued.expiresAt) + assertFalse(GRANT_TOKEN in issued.toString(), "The token stays out of logs") + } + + @Test + fun `a grant goes to the ln identity of an install without a Pubky identity`() = test { + sut.syncRegistration().getOrThrow() + whenever { wakeService.createGrant(any(), any(), any(), any(), any()) }.thenReturn(grant(LN_IDENTITY)) + + sut.createGrant(SWAP_TOPIC, 2u).getOrThrow() + + verify(wakeService).createGrant(GATEWAY_URL, CREDENTIALS.deviceSecret, LN_IDENTITY, listOf(SWAP_TOPIC), 2u) + } + + @Test + fun `no grant is made without a registration or after an opt-out`() = test { + assertNull(sut.createGrant(SWAP_TOPIC, 2u).getOrThrow()) + + sut.syncRegistration().getOrThrow() + whenever(wakeConfig.isOptedIn()).thenReturn(false) + assertNull(sut.createGrant(SWAP_TOPIC, 2u).getOrThrow()) + + verify(wakeService, never()).createGrant(any(), any(), any(), any(), any()) + } + + @Test + fun `revokeGrant revokes the grant on the gateway`() = test { + sut.syncRegistration().getOrThrow() + whenever { wakeService.revokeGrant(any(), any(), any()) }.thenReturn(Unit) + + assertTrue(sut.revokeGrant(GRANT_ID).isSuccess) + + verify(wakeService).revokeGrant(GATEWAY_URL, CREDENTIALS.deviceSecret, GRANT_ID) + } + + private fun grant(recipient: String) = WakeGrant( + id = GRANT_ID, + token = GRANT_TOKEN, + recipient = recipient, + topics = listOf(SWAP_TOPIC), + perHour = 6u, + perDay = 24u, + createdAt = NOW_SECS.toULong(), + expiresAt = GRANT_EXPIRES_AT, + ) + @Test fun `a sync that failed for a transient reason is retried until it succeeds`() = test { var attempts = 0 diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 5b156caf60..54bec37a09 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -20884,6 +20884,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { destinationAddress = REGTEST_ADDRESS, htlcAddress = REGTEST_ADDRESS, timeoutBlockHeight = 0u, + providerTakesWake = false, ) private fun lightningInvoice( From 920c324edf58b12aa6d62f0f39031369bdaeaefd Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Fri, 20 Nov 2026 22:15:13 -0500 Subject: [PATCH 2/3] test: stop background swap loops before each test ends --- .../repositories/PubkySwapsRouteRepoTest.kt | 86 +++++++++++-------- 1 file changed, 52 insertions(+), 34 deletions(-) diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index 9c13865e9c..b5df9ffc41 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -23,6 +23,7 @@ import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.yield import org.junit.Before import org.junit.Test import org.lightningdevkit.ldknode.Event @@ -100,7 +101,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `awaitClaim finishes once the claim is broadcast`() = test { + fun `awaitClaim finishes once the claim is broadcast`() = swapTest { val txid = advancing( PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u), PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID), @@ -111,7 +112,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `awaitClaim keeps polling after a failed advance`() = test { + fun `awaitClaim keeps polling after a failed advance`() = swapTest { val txid = advancing( AppError("electrum unreachable"), PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID), @@ -123,7 +124,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `awaitClaim running out leaves the swap open and keeps advancing it`() = test { + fun `awaitClaim running out leaves the swap open and keeps advancing it`() = swapTest { mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) @@ -139,7 +140,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `awaitClaim keeps advancing the swap after its caller is cancelled`() = test { + fun `awaitClaim keeps advancing the swap after its caller is cancelled`() = swapTest { mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) @@ -157,7 +158,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `awaitClaim stops advancing the swap once its hold payment fails`() = test { + fun `awaitClaim stops advancing the swap once its hold payment fails`() = swapTest { mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) @@ -178,7 +179,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `awaitClaim keeps advancing the swap when its hold payment watch is cancelled`() = test { + fun `awaitClaim keeps advancing the swap when its hold payment watch is cancelled`() = swapTest { mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) @@ -197,7 +198,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `commit keeps the swap to resume until its claim confirms`() = test { + fun `commit keeps the swap to resume until its claim confirms`() = swapTest { mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsCommitRoute(any(), any(), any(), anyOrNull()) } } .thenReturn(swapPayment()) @@ -215,7 +216,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `commit hands a grant to a provider that takes a wake`() = test { + fun `commit hands a grant to a provider that takes a wake`() = swapTest { whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(GRANT)) committingWithWake(false) { core -> @@ -240,7 +241,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `commit hands no grant to a provider that takes no wake`() = test { + fun `commit hands no grant to a provider that takes no wake`() = swapTest { mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsCommitRoute(any(), any(), any(), anyOrNull()) } } .thenReturn(swapPayment(providerTakesWake = false)) @@ -253,7 +254,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `an install not registered for wakes sends no capability`() = test { + fun `an install not registered for wakes sends no capability`() = swapTest { whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(null)) committingWithWake(false) { core -> @@ -267,7 +268,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `a capability the provider refuses has its grant revoked`() = test { + fun `a capability the provider refuses has its grant revoked`() = swapTest { whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(GRANT)) whenever(wakeRepo.revokeGrant(any())).thenReturn(Result.success(Unit)) @@ -279,7 +280,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `a swap already claimable is advanced now and its grant revoked`() = test { + fun `a swap already claimable is advanced now and its grant revoked`() = swapTest { whenever(wakeRepo.createGrant(any(), any())).thenReturn(Result.success(GRANT)) whenever(wakeRepo.revokeGrant(any())).thenReturn(Result.success(Unit)) @@ -295,7 +296,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `a swap that ends has its grant revoked`() = test { + fun `a swap that ends has its grant revoked`() = swapTest { whenever(wakeRepo.revokeGrant(any())).thenReturn(Result.success(Unit)) cacheData.value = AppCacheData( unfinishedPubkySwaps = listOf(SWAP_ID), @@ -310,7 +311,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `a wake claims the unfinished swaps and leaves their claims to the background`() = test { + fun `a wake claims the unfinished swaps and leaves their claims to the background`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) val result = advancing( PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u), @@ -326,7 +327,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `a wake after which no claim went out fails`() = test { + fun `a wake after which no claim went out fails`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) var isWakeOver = false mockStatic(CORE).use { core -> @@ -339,21 +340,26 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { val result = sut.claimAfterWake() isWakeOver = true + // The wake's timeout resumes on the unconfined event loop, which starts the background advance only once + // the test yields. + yield() advanceUntilIdle() assertIs(result.exceptionOrNull()) - // Advanced every 3 s for 2 minutes. - core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, atLeast(40)) + // Advanced every 3 s for 2 minutes, then once in the background. + core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, times(41)) + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps, "The background advance took the swap over") } } @Test - fun `a wake with no unfinished swap is handled`() = test { + fun `a wake with no unfinished swap is handled`() = swapTest { assertTrue(sut.claimAfterWake().isSuccess) } @Test - fun `a wake treats a swap that failed as ended`() = test { + @OptIn(ExperimentalCoroutinesApi::class) + fun `a wake treats a swap that failed as ended`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) val result = advancing(PubkySwapRouteState.Failed("refunded")) { @@ -366,7 +372,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `resumeUnfinishedSwaps advances a stored swap past an hour until its claim confirms`() = test { + fun `resumeUnfinishedSwaps advances a stored swap past an hour until its claim confirms`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) mockStatic(CORE).use { core -> var calls = 0 @@ -389,7 +395,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `resumeUnfinishedSwaps drops a swap that failed`() = test { + fun `resumeUnfinishedSwaps drops a swap that failed`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } @@ -404,7 +410,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `resumeUnfinishedSwaps drops a swap bitkit-core has no record of`() = test { + fun `resumeUnfinishedSwaps drops a swap bitkit-core has no record of`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) mockStatic(CORE).use { core -> core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } @@ -419,7 +425,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } @Test - fun `restoredSwaps asks again only the providers it read in part`() = test { + fun `restoredSwaps asks again only the providers it read in part`() = swapTest { contacts.value = listOf(PubkyProfile.placeholder("provider-a"), PubkyProfile.placeholder("provider-b")) val asked = mutableListOf>() val swaps = restoring( @@ -434,7 +440,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `restoredSwaps asks the providers past bitkit-core's limit in another call`() = test { + fun `restoredSwaps asks the providers past bitkit-core's limit in another call`() = swapTest { val keys = (1..31).map { "provider-$it" } contacts.value = keys.map(PubkyProfile::placeholder) val asked = mutableListOf>() @@ -449,7 +455,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `restoredSwaps restores again for contacts that load later`() = test { + fun `restoredSwaps restores again for contacts that load later`() = swapTest { val asked = mutableListOf>() restoring(asked, report()) { backgroundScope.launch { sut.restoredSwaps().collect {} } @@ -463,7 +469,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `dropFailedSwap stops advancing a swap after its claim wait ran out`() = test { + fun `dropFailedSwap stops advancing a swap after its claim wait ran out`() = swapTest { cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) mockStatic(CORE).use { core -> var calls = 0 @@ -485,7 +491,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `restoredSwaps reveals one payout address for all its restores`() = test { + fun `restoredSwaps reveals one payout address for all its restores`() = swapTest { contacts.value = listOf(PubkyProfile.placeholder("provider-a")) val asked = mutableListOf>() restoring(asked, report(incomplete = listOf("provider-a"))) { @@ -501,7 +507,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `restoredSwaps after a wipe asks again the providers the wiped wallet read`() = test { + fun `restoredSwaps after a wipe asks again the providers the wiped wallet read`() = swapTest { contacts.value = listOf(PubkyProfile.placeholder("provider-a")) val asked = mutableListOf>() restoring(asked, report()) { @@ -520,7 +526,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `resumeUnfinishedSwaps drops a swap whose hold payment failed while the app was closed`() = test { + fun `resumeUnfinishedSwaps drops a swap whose hold payment failed while the app was closed`() = swapTest { cacheData.value = AppCacheData( unfinishedPubkySwaps = listOf(SWAP_ID), pubkySwapHoldHashes = mapOf(SWAP_ID to HOLD_HASH), @@ -539,7 +545,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `resumeUnfinishedSwaps drops a swap whose hold payment failed over spark`() = test { + fun `resumeUnfinishedSwaps drops a swap whose hold payment failed over spark`() = swapTest { cacheData.value = AppCacheData( unfinishedPubkySwaps = listOf(SWAP_ID), pubkySwapHoldHashes = mapOf(SWAP_ID to HOLD_HASH), @@ -558,7 +564,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `a hold payment failing stops its resumed swap`() = test { + fun `a hold payment failing stops its resumed swap`() = swapTest { cacheData.value = AppCacheData( unfinishedPubkySwaps = listOf(SWAP_ID), pubkySwapHoldHashes = mapOf(SWAP_ID to HOLD_HASH), @@ -587,7 +593,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `dropFailedSwap stops a running claim wait`() = test { + fun `dropFailedSwap stops a running claim wait`() = swapTest { mockStatic(CORE).use { core -> var calls = 0 core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }.thenAnswer { @@ -612,7 +618,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `resetForWipe stops a running claim wait`() = test { + fun `resetForWipe stops a running claim wait`() = swapTest { mockStatic(CORE).use { core -> var calls = 0 core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }.thenAnswer { @@ -635,7 +641,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `restoredSwaps leaves a swap dropped this session alone`() = test { + fun `restoredSwaps leaves a swap dropped this session alone`() = swapTest { contacts.value = listOf(PubkyProfile.placeholder("provider-a")) sut.dropFailedSwap(SWAP_ID) val asked = mutableListOf>() @@ -671,6 +677,18 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + /** + * Runs [block] as a test, then stops the swaps the repo advances in the background. Their loops run on the test + * scheduler outside the test scope, so one left running would keep the test from ever finishing. + */ + private fun swapTest(block: suspend TestScope.() -> Unit) = test { + try { + block() + } finally { + sut.resetForWipe() + } + } + private fun swapPayment(providerTakesWake: Boolean = false) = PubkySwapRoutePayment( swapId = SWAP_ID, invoice = "invoice", From eb27d5ecc0fd494f63c0007f942809569801bebd Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Fri, 20 Nov 2026 22:15:13 -0500 Subject: [PATCH 3/3] chore: bump bitkit-core to 0.8.0-swaps.12 --- gradle/libs.versions.toml | 2 +- gradle/verification-metadata.xml | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 8468eaa12a..eccebf2aae 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -23,7 +23,7 @@ activity-compose = { module = "androidx.activity:activity-compose", version = "1 appcompat = { module = "androidx.appcompat:appcompat", version = "1.8.0" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-beta01" } -bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc15" } +bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-swaps.12" } breez-sdk-spark = { module = "breez_sdk_spark:bindings-android", version = "0.28.3" } paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc9" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.86" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index e074e6d2ab..2b2d444117 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -4395,6 +4395,17 @@ + + + + + + + + + + +