Repository navigation
feat: pay contacts via pubky swaps #1732
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+1,849
−43
Merged
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
8bb27fd
feat: pay contacts through pubky swaps
ovitrif 46ad2a9
chore: add changelog fragment
ovitrif 0336ee0
docs: pay the journey's contact from the contact list
ovitrif 9bb81f8
chore: use bitkit-core 0.8.0-swaps.1
ovitrif 97749ce
chore: move to bitkit-core 0.8.0-swaps.3
ovitrif f6f8ad3
feat: return swap routes to savings after a wallet restore
ovitrif 257190c
fix: keep the swap restore notice until dismissed
ovitrif 718fcbd
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif 79dd345
chore: move to bitkit-core 0.8.0-swaps.9
ovitrif 9f6ec3b
test: expect the restore's failed categories
ovitrif de29463
fix: finish a swap-routed send once, with its tags
ovitrif 3435c0e
fix: finish a swap-routed send when the claim is broadcast
ovitrif 5548350
fix: keep a swap quote matched to the amount and fee shown
ovitrif 712cc05
fix: keep a late swap result on its own payment
ovitrif 4b8c8df
fix: retry a failed swap payment with a fresh quote
ovitrif 47aff38
fix: keep swap sends on their own payment
ovitrif bc8f3e8
fix: wait for a swap claim outside the send submission
ovitrif de7b78f
fix: wait on a swap's hold payment on the pending screen
ovitrif 8d40a8b
fix: keep a swap hold failed before its send returns on error
ovitrif c59a089
fix: open the error for a swap hold failure handled late
ovitrif 490bdb4
fix: retry a refused swap from amount and keep its claim running
ovitrif 19f575c
fix: release a refused swap's private payment list
ovitrif cd13b13
chore: move to bitkit-core 0.8.0-swaps.11
ovitrif 7c56d7a
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif 9a7eebe
chore: build on the bitkit-core 0.8.0-rc14 release
ovitrif 46948b6
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif c22b8f6
fix: keep a swap hold with an unknown spark outcome pending
ovitrif c866eb5
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif 098c355
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif a786e34
Merge remote-tracking branch 'origin/master' into feat/pubky-swaps-route
ovitrif File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
219 changes: 219 additions & 0 deletions
219
app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| package to.bitkit.repositories | ||
|
|
||
| import com.synonym.bitkitcore.PaykitEndpoint | ||
| import com.synonym.bitkitcore.PaykitRoute | ||
| import com.synonym.bitkitcore.PaykitRouteRequest | ||
| import com.synonym.bitkitcore.PubkySwapRoutePayment | ||
| import com.synonym.bitkitcore.PubkySwapRouteState | ||
| import com.synonym.bitkitcore.PubkySwapSentPayment | ||
| import com.synonym.bitkitcore.ServiceRouteLeg | ||
| import com.synonym.bitkitcore.pubkySwapsAdvance | ||
| import com.synonym.bitkitcore.pubkySwapsCommitRoute | ||
| import com.synonym.bitkitcore.pubkySwapsRestore | ||
| import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment | ||
| import kotlinx.coroutines.CoroutineDispatcher | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.delay | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.coroutines.withContext | ||
| import kotlinx.coroutines.withTimeoutOrNull | ||
| import org.lightningdevkit.ldknode.PaymentDirection | ||
| import org.lightningdevkit.ldknode.PaymentKind | ||
| import org.lightningdevkit.ldknode.PaymentStatus | ||
| import to.bitkit.async.appScope | ||
| import to.bitkit.data.keychain.Keychain | ||
| import to.bitkit.di.IoDispatcher | ||
| import to.bitkit.env.Env | ||
| import to.bitkit.ext.runSuspendCatching | ||
| import to.bitkit.models.PubkyProfile | ||
| import to.bitkit.models.PubkyPublicKeyFormat | ||
| import to.bitkit.models.toCoreNetwork | ||
| import to.bitkit.utils.AppError | ||
| import to.bitkit.utils.Logger | ||
| import to.bitkit.utils.ServiceError | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
| import kotlin.time.Duration | ||
| import kotlin.time.Duration.Companion.minutes | ||
| import kotlin.time.Duration.Companion.seconds | ||
|
|
||
| /** | ||
| * Routes a Paykit payment through a Pubky Swaps provider when no balance the wallet holds reaches an endpoint the | ||
| * contact published. bitkit-core picks the provider and checks its quote, contract and hold invoice; the wallet pays | ||
| * the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. | ||
| */ | ||
| @Singleton | ||
| class PubkySwapsRouteRepo @Inject constructor( | ||
| @IoDispatcher private val ioDispatcher: CoroutineDispatcher, | ||
| private val keychain: Keychain, | ||
| private val pubkyRepo: PubkyRepo, | ||
| private val lightningRepo: LightningRepo, | ||
| ) { | ||
| companion object { | ||
| private const val TAG = "PubkySwapsRouteRepo" | ||
| private const val CLAIM_FEE_RATE_SAT_VB = 2uL | ||
| private val POLL_INTERVAL = 2.seconds | ||
| private val CLAIM_TIMEOUT = 10.minutes | ||
|
|
||
| /** How often a broadcast claim is advanced, so bitkit-core rebroadcasts it until it confirms. */ | ||
| private val CONFIRMATION_POLL_INTERVAL = 30.seconds | ||
|
|
||
| /** How long a broadcast claim is advanced in the background before polling stops. */ | ||
| private val CONFIRMATION_TIMEOUT = 60.minutes | ||
| } | ||
|
|
||
| private val scope = appScope(ioDispatcher, TAG) | ||
|
|
||
| val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled | ||
|
|
||
| /** The contact behind a provider's pubky, so the review shows who routes the payment. */ | ||
| fun providerContact(pubky: String): PubkyProfile? = | ||
| pubkyRepo.contacts.value.firstOrNull { PubkyPublicKeyFormat.matches(it.publicKey, pubky) } | ||
|
|
||
| suspend fun route( | ||
| amountSats: ULong, | ||
| endpoints: List<PaykitEndpoint>, | ||
| lightningSpendableSats: ULong, | ||
| onchainSpendableSats: ULong, | ||
| serviceLegs: List<ServiceRouteLeg> = emptyList(), | ||
| ): Result<PaykitRoute> = withSecrets { mnemonic, passphrase -> | ||
| val candidates = candidates() | ||
| Logger.debug("Routing Paykit payment via '${candidates.map(PubkyPublicKeyFormat::redacted)}'", context = TAG) | ||
| pubkySwapsRoutePaykitPayment( | ||
| request = PaykitRouteRequest( | ||
| amountSat = amountSats, | ||
| contactEndpoints = endpoints, | ||
| lightningSpendableSat = lightningSpendableSats, | ||
| onchainSpendableSat = onchainSpendableSats, | ||
| providers = candidates, | ||
| feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, | ||
| serviceLegs = serviceLegs, | ||
| ), | ||
| network = Env.network.toCoreNetwork(), | ||
| mnemonic = mnemonic, | ||
| bip39Passphrase = passphrase, | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed. The listing | ||
| * does not carry the contact's address, so a restored swap claims to a fresh Savings address. bitkit-core checks | ||
| * each listed lockup against the Lightning payment this node sent for its hash. Swaps already on record keep the | ||
| * destination they were committed with. | ||
| */ | ||
| suspend fun restoreSwaps(): Result<RestoredPubkySwaps> = withSecrets { mnemonic, passphrase -> | ||
| val payoutAddress = lightningRepo.newAddress().getOrThrow() | ||
| val report = pubkySwapsRestore( | ||
| providers = candidates(), | ||
| sentPayments = sentPayments(), | ||
| electrumUrl = Env.electrumServerUrl, | ||
| payoutAddress = payoutAddress, | ||
| feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, | ||
| network = Env.network.toCoreNetwork(), | ||
| mnemonic = mnemonic, | ||
| bip39Passphrase = passphrase, | ||
| ) | ||
| if (report.incompleteProviders.isNotEmpty()) { | ||
| Logger.warn("Swap lists incomplete from '${report.incompleteProviders}'", context = TAG) | ||
| } | ||
| RestoredPubkySwaps(restored = report.restored, known = report.known) | ||
| } | ||
|
|
||
| /** The Lightning payments this node sent, pending or settled, by hash and the amount paid to the payee. */ | ||
| private suspend fun sentPayments(): List<PubkySwapSentPayment> = | ||
| lightningRepo.getPayments().getOrThrow().mapNotNull { payment -> | ||
| val kind = payment.kind as? PaymentKind.Bolt11 ?: return@mapNotNull null | ||
| val amountMsat = payment.amountMsat ?: return@mapNotNull null | ||
| if (payment.direction != PaymentDirection.OUTBOUND || payment.status == PaymentStatus.FAILED) { | ||
| return@mapNotNull null | ||
| } | ||
| PubkySwapSentPayment( | ||
| paymentHashHex = kind.hash, | ||
| amountSat = amountMsat / 1000u, | ||
| settled = payment.status == PaymentStatus.SUCCEEDED, | ||
| ) | ||
| } | ||
|
|
||
| /** Providers come from the user's own graph: every contact is asked for its swap offer. */ | ||
| private fun candidates(): List<String> = | ||
| (Env.pubkySwapsProviders + pubkyRepo.contacts.value.map { it.publicKey }).distinct() | ||
|
|
||
| suspend fun commit(quoteId: String): Result<PubkySwapRoutePayment> = withSecrets { mnemonic, passphrase -> | ||
| pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase) | ||
| } | ||
|
|
||
| /** | ||
| * Advance the swap until bitkit-core broadcasts the claim to the contact, returning the claim txid. The provider | ||
| * settles the hold invoice once it sees the claim, so the payment is done; the claim is still advanced in the | ||
| * background so bitkit-core rebroadcasts it until it confirms. | ||
| */ | ||
| // Runs on the app scope: the swap keeps advancing towards its claim when the caller, such as a cleared screen, | ||
| // stops waiting. | ||
| suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result<String> = scope.async { | ||
| var lastFailure: Throwable? = null | ||
| withTimeoutOrNull(timeout) { | ||
| pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } | ||
| }?.onSuccess { advanceInBackground(swapId) } ?: run { | ||
| // The provider may still settle the hold payment, so the swap keeps advancing towards its claim. | ||
| advanceInBackground(swapId) | ||
| Result.failure(PubkySwapClaimTimeoutException(swapId, lastFailure)) | ||
| } | ||
| }.await() | ||
|
|
||
| private fun advanceInBackground(swapId: String) { | ||
| scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } | ||
| } | ||
|
|
||
| private suspend fun awaitConfirmation(swapId: String) { | ||
| pollClaim(swapId, CONFIRMATION_POLL_INTERVAL, untilConfirmed = true) {} | ||
| .onSuccess { Logger.info("Confirmed Pubky Swaps claim '$it' for '$swapId'", context = TAG) } | ||
| .onFailure { Logger.warn("Failed to confirm Pubky Swaps claim for '$swapId'", it, context = TAG) } | ||
| } | ||
|
|
||
| private suspend fun pollClaim( | ||
| swapId: String, | ||
| interval: Duration, | ||
| untilConfirmed: Boolean, | ||
| onPending: (Throwable) -> Unit, | ||
| ): Result<String> { | ||
| while (true) { | ||
| // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. | ||
| val state = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } | ||
| .onFailure { | ||
| Logger.warn("Failed to advance Pubky Swaps route '$swapId'", it, context = TAG) | ||
| onPending(it) | ||
| } | ||
| .getOrNull()?.state | ||
| when (state) { | ||
| is PubkySwapRouteState.Claimed -> return Result.success(state.txid) | ||
|
ovitrif marked this conversation as resolved.
Resolved
ovitrif marked this conversation as resolved.
Resolved
|
||
| is PubkySwapRouteState.ClaimBroadcast if !untilConfirmed -> return Result.success(state.txid) | ||
| is PubkySwapRouteState.Failed -> return Result.failure(AppError(state.reason)) | ||
| null -> Unit | ||
| else -> { | ||
| Logger.debug("Pubky Swaps route '$swapId': $state", context = TAG) | ||
| onPending(AppError("Swap '$swapId' not claimed yet: '$state'")) | ||
| } | ||
| } | ||
| delay(interval) | ||
| } | ||
| } | ||
|
|
||
| private suspend fun <T> withSecrets(block: suspend (String, String?) -> T): Result<T> = withContext(ioDispatcher) { | ||
| runSuspendCatching { | ||
| val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) | ||
| ?: throw ServiceError.MnemonicNotFound() | ||
| val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) | ||
| block(mnemonic, passphrase) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** The swaps a restore found: those rebuilt now claim to Savings, those already on record keep their destination. */ | ||
| data class RestoredPubkySwaps( | ||
| val restored: List<String>, | ||
| val known: List<String>, | ||
| ) | ||
|
|
||
| /** 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) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.