Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ data class AppCacheData(
val unfinishedPubkySwaps: List<String> = listOf(),
/** The hold payment hash of each unfinished Pubky Swaps route by swap id, so its failure stops the swap. */
val pubkySwapHoldHashes: Map<String, String> = 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<String, String> = mapOf(),
/** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */
val sparkSendHashes: List<String> = listOf(),
/** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */
Expand Down
20 changes: 19 additions & 1 deletion app/src/main/java/to/bitkit/fcm/WakeHandlers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -36,10 +38,16 @@ class WakeHandlers internal constructor(private val byTopic: Map<String, WakeHan

/** The gateway's self-test, which it sends only to the device that asked for it. */
const val TEST_TOPIC = "wake.test"

/** A Pubky Swaps provider's wake once a swap's lockup can be claimed, through a grant the swap handed it. */
const val SWAP_CLAIMABLE_TOPIC = "swap.claimable"
}

@Inject
constructor(alertHandler: WakeAlertHandler) : this(mapOf(TEST_TOPIC to alertHandler))
constructor(
alertHandler: WakeAlertHandler,
swapClaimableHandler: SwapClaimableWakeHandler,
) : this(mapOf(TEST_TOPIC to alertHandler, SWAP_CLAIMABLE_TOPIC to swapClaimableHandler))

/** Runs the handler of the wake's topic, and maps what became of it to the outcome to acknowledge. */
suspend fun handle(wake: WakeEnvelope): WakeAckOutcome {
Expand All @@ -54,6 +62,16 @@ class WakeHandlers internal constructor(private val byTopic: Map<String, WakeHan
}
}

/**
* Claims the swaps a `swap.claimable` wake is for. Resolves the swaps repository only for such a wake, so other wakes
* do not build the wallet graph.
*/
class SwapClaimableWakeHandler @Inject constructor(
private val pubkySwapsRouteRepo: Lazy<PubkySwapsRouteRepo>,
) : 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.
Expand Down
107 changes: 107 additions & 0 deletions app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand All @@ -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)
Expand Down Expand Up @@ -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<Unit> = 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 {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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<String>) :
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)
Expand Down
43 changes: 43 additions & 0 deletions app/src/main/java/to/bitkit/repositories/WakeRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<IssuedWakeGrant?> =
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<Unit> = 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
Expand Down Expand Up @@ -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. */
Expand Down
26 changes: 26 additions & 0 deletions app/src/main/java/to/bitkit/services/WakeService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -128,6 +131,29 @@ class WakeService @Inject constructor() {
suspend fun listTopics(gatewayUrl: String): List<WakeTopic> = ServiceQueue.CORE.background {
wakeListTopics(gatewayUrl = gatewayUrl)
}

suspend fun createGrant(
gatewayUrl: String,
deviceSecret: String,
recipient: String,
topics: List<String>,
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)
}
}

/**
Expand Down
52 changes: 52 additions & 0 deletions app/src/test/java/to/bitkit/fcm/WakeHandlersTest.kt
Original file line number Diff line number Diff line change
@@ -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<PubkySwapsRouteRepo>()

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,
)
}
Loading