-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPrivatePaykitRepo.kt
More file actions
2101 lines (1933 loc) · 93.9 KB
/
Copy pathPrivatePaykitRepo.kt
File metadata and controls
2101 lines (1933 loc) · 93.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package to.bitkit.repositories
import com.synonym.bitkitcore.Scanner
import com.synonym.paykit.FfiPaymentEntry
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
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.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.lightningdevkit.ldknode.PaymentDirection
import org.lightningdevkit.ldknode.PaymentKind
import org.lightningdevkit.ldknode.PaymentStatus
import to.bitkit.App
import to.bitkit.data.PrivatePaykitCacheStore
import to.bitkit.data.SettingsStore
import to.bitkit.data.keychain.Keychain
import to.bitkit.di.IoDispatcher
import to.bitkit.ext.toHex
import to.bitkit.models.PrivatePaykitContactLinkBackupV1
import to.bitkit.models.PubkyPublicKeyFormat
import to.bitkit.services.CoreService
import to.bitkit.services.PubkyService
import to.bitkit.utils.Logger
import java.util.UUID
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Clock
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
private data class PrivatePaymentAttempt(
val result: Result<PublicPaykitPaymentResult>,
val shouldDeferPublicFallback: Boolean,
)
@OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class)
@Singleton
@Suppress("TooManyFunctions", "LongParameterList", "LargeClass")
class PrivatePaykitRepo @Inject constructor(
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val pubkyService: PubkyService,
private val keychain: Keychain,
private val cacheStore: PrivatePaykitCacheStore,
private val settingsStore: SettingsStore,
private val addressReservationRepo: PrivatePaykitAddressReservationRepo,
private val lightningRepo: LightningRepo,
private val walletRepo: WalletRepo,
private val publicPaykitRepo: PublicPaykitRepo,
private val coreService: CoreService,
private val clock: Clock,
) {
companion object {
private const val TAG = "PrivatePaykitRepo"
private const val MAX_RECEIVED_INVOICE_HASHES_PER_CONTACT = 100
private const val STALE_LINK_FAILURE_THRESHOLD = 3
private const val HANDSHAKE_COMPLETE = "complete"
private const val RECOVERY_MARKER_STAGE_INIT = "init"
private const val RECOVERY_MARKER_STAGE_RESPONSE = "response"
private const val RECOVERY_MARKER_STAGE_FINAL = "final"
private const val FRESH_LINK_INITIAL_PUBLISH_DELAY_SECONDS = 8L
private const val PENDING_PUBLICATION_RETRY_ATTEMPTS = 60
private const val PRIVATE_PAYMENT_RECOVERY_RETRY_ATTEMPTS = 12
private val privateInvoiceExpiry = 24.hours
private val invoiceRefreshBuffer = 30.minutes
private val pendingPublicationRetryDelay = 5.seconds
private val privatePaymentRecoveryRetryDelay = 2.seconds
fun shouldInitiate(ownPublicKey: String, remotePublicKey: String): Boolean {
val own = PubkyPublicKeyFormat.normalized(ownPublicKey) ?: ownPublicKey
val remote = PubkyPublicKeyFormat.normalized(remotePublicKey) ?: remotePublicKey
return own > remote
}
fun isDuplicatePaymentError(error: Throwable): Boolean =
PrivatePaykitErrorClassifier.isDuplicatePaymentError(error)
}
private val stateStore = PrivatePaykitStateStore(keychain, cacheStore)
private val recoveryStore = PrivatePaykitRecoveryStore(pubkyService, keychain) { ensureState() }
private val activeHandlesByContact = mutableMapOf<String, ContactPaykitHandles>()
private val knownSavedContactKeys = mutableSetOf<String>()
private val linkEstablishmentMutex = Mutex()
private val publicationMutex = Mutex()
private val serializedDispatcher = ioDispatcher.limitedParallelism(1)
private val retryScope = CoroutineScope(SupervisorJob() + serializedDispatcher)
private val pendingPublicationRetryJobs = mutableMapOf<String, Job>()
private val stateGeneration = AtomicLong(0L)
private val _backupStateVersion = MutableStateFlow(0L)
val backupStateVersion: StateFlow<Long> = _backupStateVersion.asStateFlow()
suspend fun reconcileReservedReceiveIndexes(): Result<Unit> =
addressReservationRepo.reconcileReservedIndexesWithLdk()
suspend fun prepareSavedContacts(
publicKeys: Collection<String>,
requireImmediatePublication: Boolean = false,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
val keys = rememberSavedContacts(publicKeys, replacing = true)
if (!canPublishPrivateEndpoints()) {
if (requireImmediatePublication && keys.isNotEmpty()) throw PrivatePaykitError.PrivateUnavailable
return@runCatching
}
if (isProfileRecoveryPending() && keys.isNotEmpty()) {
recoverSavedContactsAfterProfileRecreation(
publicKeys = keys,
requireImmediatePublication = requireImmediatePublication,
).getOrThrow()
return@runCatching
}
addressReservationRepo.reconcileReservedIndexesWithLdk().getOrThrow()
publishLocalEndpoints(
publicKeys = keys,
maxAdvanceSteps = 3,
reason = "prepare",
requireImmediatePublication = requireImmediatePublication,
).getOrThrow()
}
}
private suspend fun recoverSavedContactsAfterProfileRecreation(
publicKeys: Collection<String>,
requireImmediatePublication: Boolean,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
val keys = rememberSavedContacts(publicKeys, replacing = true)
if (keys.isEmpty()) return@runCatching
if (!canPublishPrivateEndpoints()) return@runCatching
advanceStateGeneration()
resetInFlightWork()
val didPurgeStaleTransport = recoveryStore.purgePrivatePaymentOutboxForProfileRecovery("profile recovery")
if (!didPurgeStaleTransport) {
updateProfileRecoveryPending(true)
if (requireImmediatePublication) throw PrivatePaykitError.PrivateUnavailable
return@runCatching
}
markContactsForProfileRecovery(keys, clock.now().epochSeconds)
persistState(markWalletBackup = true)
updateProfileRecoveryPending(false)
addressReservationRepo.reconcileReservedIndexesWithLdk().getOrThrow()
publishLocalEndpoints(
publicKeys = keys,
maxAdvanceSteps = 3,
reason = "profile recovery",
forceLocalPublishWhenRemoteEmpty = true,
requireImmediatePublication = requireImmediatePublication,
).getOrThrow()
}
}
suspend fun enableSharingAndPrepareSavedContacts(
publicKeys: Collection<String>,
requireImmediatePublication: Boolean = false,
): Result<Unit> =
withContext(serializedDispatcher) {
runCatching {
val wasCleanupPending = isContactSharingCleanupPending()
if (wasCleanupPending && !canPublishPrivateEndpoints()) {
if (requireImmediatePublication) throw PrivatePaykitError.PrivateUnavailable
return@runCatching
}
updateContactSharingCleanupPending(false)
prepareSavedContacts(publicKeys, requireImmediatePublication).onFailure {
if (wasCleanupPending) {
runCatching { updateContactSharingCleanupPending(true) }
.onFailure(it::addSuppressed)
}
}.getOrThrow()
}
}
suspend fun refreshSavedContactEndpoints(publicKeys: Collection<String>): Result<Unit> =
withContext(serializedDispatcher) {
runCatching {
val keys = rememberSavedContacts(publicKeys, replacing = true)
if (!canPublishPrivateEndpoints()) return@runCatching
if (isProfileRecoveryPending() && keys.isNotEmpty()) {
recoverSavedContactsAfterProfileRecreation(keys, requireImmediatePublication = false).getOrThrow()
return@runCatching
}
publishLocalEndpoints(keys, maxAdvanceSteps = 1, reason = "refresh").getOrThrow()
}
}
suspend fun refreshKnownSavedContactEndpoints(
reason: String,
forceRefreshLightning: Boolean = false,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
if (!canPublishPrivateEndpoints()) return@runCatching
if (isProfileRecoveryPending() && knownSavedContactKeys.isNotEmpty()) {
recoverSavedContactsAfterProfileRecreation(
publicKeys = knownSavedContactKeys.toList(),
requireImmediatePublication = false,
).getOrThrow()
return@runCatching
}
publishLocalEndpoints(
publicKeys = knownSavedContactKeys.toList(),
maxAdvanceSteps = 1,
reason = reason,
forceRefreshLightning = forceRefreshLightning,
).getOrThrow()
}.onFailure {
Logger.warn("Failed to refresh private Paykit endpoints for '$reason'", it, context = TAG)
}
}
suspend fun retryPendingEndpointRemoval(
savedPublicKeys: Collection<String>,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
if (isContactSharingCleanupPending()) {
removePublishedEndpoints().getOrThrow()
clearUnsavedContactState(savedPublicKeys).getOrThrow()
updateContactSharingCleanupPending(false)
}
retryPendingDeletedContactEndpointRemoval(savedPublicKeys).getOrThrow()
}.onFailure {
Logger.warn("Failed to retry pending Paykit contact endpoint removal", it, context = TAG)
}
}
suspend fun pruneUnsavedContactState(
savedPublicKeys: Collection<String>,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
val savedKeys = rememberSavedContacts(savedPublicKeys, replacing = true).toSet()
val staleKeys = ensureState().contacts.keys.filter { it !in savedKeys }
staleKeys.forEach { removeSavedContact(it).getOrThrow() }
addressReservationRepo.clearContactAssignments(excludingPublicKeys = savedKeys)
}
}
suspend fun removeSavedContact(publicKey: String): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
val normalizedKey = normalizedPublicKey(publicKey) ?: return@runCatching
knownSavedContactKeys.remove(normalizedKey)
cancelPendingPublicationRetry(normalizedKey)
advanceStateGeneration()
removePublishedEndpoints(normalizedKey).onFailure {
updateDeletedContactCleanupPending(normalizedKey, true)
Logger.warn(
"Failed to tombstone private Paykit endpoints for '${redacted(normalizedKey)}'",
it,
context = TAG,
)
}.getOrThrow()
clearContactState(normalizedKey)
addressReservationRepo.clearContactAssignment(normalizedKey)
updateDeletedContactCleanupPending(normalizedKey, false)
}
}
suspend fun disableSharingAndPruneUnsavedContactState(savedPublicKeys: Collection<String>): Result<Unit> =
withContext(serializedDispatcher) {
runCatching {
resetInFlightWork()
val removalError = removePublishedEndpoints().exceptionOrNull()
if (removalError != null) {
updateContactSharingCleanupPending(true)
Logger.warn(
"Deferred private Paykit endpoint cleanup after disable failed",
removalError,
context = TAG,
)
throw removalError
} else {
clearUnsavedContactState(savedPublicKeys).getOrThrow()
updateContactSharingCleanupPending(false)
}
}
}
suspend fun setContactSharingCleanupPending(isPending: Boolean): Result<Unit> =
withContext(serializedDispatcher) {
runCatching {
updateContactSharingCleanupPending(isPending)
}
}
suspend fun removePublishedEndpointsBestEffort(context: String): Result<Unit> = withContext(serializedDispatcher) {
removePublishedEndpoints()
.onFailure {
Logger.warn("Failed to remove private Paykit endpoints during '$context'", it, context = TAG)
}
}
suspend fun closeAndClear(
markProfileRecoveryPending: Boolean = false,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
publicationMutex.withLock {
linkEstablishmentMutex.withLock {
val hadPrivateContactState =
ensureState().contacts.isNotEmpty()
val wasProfileRecoveryPending = isProfileRecoveryPending()
resetInFlightWork()
closeActiveHandles()
activeHandlesByContact.clear()
knownSavedContactKeys.clear()
stateStore.replaceState(PrivatePaykitState())
keychain.delete(Keychain.Key.PRIVATE_PAYKIT_SECRET_STATE.name)
cacheStore.reset()
if (markProfileRecoveryPending && (hadPrivateContactState || wasProfileRecoveryPending)) {
updateProfileRecoveryPending(true)
}
addressReservationRepo.clearContactAssignments(excludingPublicKeys = emptySet())
notifyBackupStateChanged()
}
}
}
}
suspend fun beginSavedContactPayment(publicKey: String): Result<PublicPaykitPaymentResult> =
withContext(serializedDispatcher) {
runCatching {
val normalizedKey = knownSavedContact(publicKey)
?: return@runCatching publicPaykitRepo.beginPayment(publicKey).getOrThrow()
if (!hasLocalSecretKeyForCurrentProfile()) {
return@runCatching publicPaykitRepo.beginPayment(normalizedKey).getOrThrow()
}
val privateAttempt = beginPrivatePaymentWithRecoveryRetry(normalizedKey)
val privateResult = privateAttempt.result
.onFailure {
if (it is CancellationException) throw it
}
.getOrNull()
if (privateResult is PublicPaykitPaymentResult.Opened) return@runCatching privateResult
if (
privateAttempt.shouldDeferPublicFallback ||
shouldDeferPublicFallbackForPrivateRecovery(normalizedKey)
) {
privateAttempt.result.exceptionOrNull()?.let {
Logger.warn(
"Deferring public Paykit fallback for '${redacted(normalizedKey)}' " +
"while private payment recovery completes",
it,
context = TAG,
)
}
return@runCatching privateResult ?: PublicPaykitPaymentResult.NoEndpoint
}
privateAttempt.result.exceptionOrNull()?.let {
Logger.warn(
"Falling back to public Paykit for '${redacted(normalizedKey)}'",
it,
context = TAG,
)
}
publicPaykitRepo.beginPayment(normalizedKey).getOrThrow()
}
}
suspend fun discardRemoteLightningEndpoints(
publicKey: String,
paymentHashes: Set<String>,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
if (paymentHashes.isEmpty()) return@runCatching
val normalizedKey = normalizedPublicKey(publicKey) ?: return@runCatching
val contactState = ensureState().contacts[normalizedKey] ?: return@runCatching
val normalizedHashes = paymentHashes.map { it.lowercase() }.toSet()
val filteredEntries = contactState.remoteEndpoints.filterNot {
shouldDiscardRemoteLightningEntry(it, normalizedHashes)
}
if (filteredEntries.size == contactState.remoteEndpoints.size) return@runCatching
contactState.remoteEndpoints = filteredEntries
persistState(markWalletBackup = true)
}
}
suspend fun discardRemoteOnchainEndpoints(
publicKey: String,
addresses: Set<String>,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
if (addresses.isEmpty()) return@runCatching
val normalizedKey = normalizedPublicKey(publicKey) ?: return@runCatching
val contactState = ensureState().contacts[normalizedKey] ?: return@runCatching
val filteredEntries = contactState.remoteEndpoints.filterNot {
shouldDiscardRemoteOnchainEntry(it, addresses)
}
if (filteredEntries.size == contactState.remoteEndpoints.size) return@runCatching
contactState.remoteEndpoints = filteredEntries
persistState(markWalletBackup = true)
}
}
suspend fun handleReceivedPayment(paymentHash: String): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
val matchingContacts = ensureState().contacts
.filter { (publicKey, contactState) ->
publicKey in knownSavedContactKeys && contactState.localInvoice?.paymentHash == paymentHash
}
.keys
if (matchingContacts.isEmpty()) return@runCatching
matchingContacts.forEach { rememberReceivedInvoicePaymentHash(paymentHash, it) }
if (!canPublishPrivateEndpoints()) return@runCatching
val generation = currentStateGeneration()
matchingContacts.forEach { publicKey ->
val linkId = establishedLinkId(publicKey, maxAdvanceSteps = 1, generation = generation)
.getOrNull() ?: return@forEach
publishLocalEndpoints(publicKey, linkId, force = true, generation = generation).onFailure {
schedulePendingPublicationRetry(publicKey)
Logger.warn(
"Failed to rotate private Paykit invoice for '${redacted(publicKey)}'",
it,
context = TAG,
)
}
}
}
}
suspend fun reconcileReceivedPayments(): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
settledPrivateInvoicePaymentHashes().forEach {
handleReceivedPayment(it).getOrThrow()
}
}
}
suspend fun handleOnchainActivity(receivedAddresses: Collection<String> = emptyList()): Result<Unit> =
withContext(serializedDispatcher) {
runCatching {
if (!canPublishPrivateEndpoints()) return@runCatching
val publicKeys = if (receivedAddresses.isEmpty()) {
addressReservationRepo.contactsWithUsedReservedAddresses()
} else {
receivedAddresses.mapNotNull {
addressReservationRepo.currentContactPublicKeyForReservedAddress(it)
}
}.filter { it in knownSavedContactKeys }.distinct()
if (publicKeys.isEmpty()) return@runCatching
publicKeys.forEach {
addressReservationRepo.rotateAddress(it).getOrThrow()
}
publishLocalEndpoints(publicKeys, maxAdvanceSteps = 1, reason = "on-chain rotation").getOrThrow()
}
}
suspend fun contactPublicKeyForPrivateInvoicePaymentHash(paymentHash: String): String? =
withContext(serializedDispatcher) {
if (paymentHash.isBlank()) return@withContext null
ensureState().contacts.firstNotNullOfOrNull { (publicKey, contactState) ->
publicKey.takeIf {
contactState.localInvoice?.paymentHash == paymentHash ||
paymentHash in contactState.receivedInvoicePaymentHashes
}
}
}
suspend fun contactPublicKeyForPrivateOnchainAddresses(addresses: Collection<String>): String? =
withContext(serializedDispatcher) {
addresses.firstNotNullOfOrNull {
addressReservationRepo.contactPublicKeyForReservedAddress(it)
}
}
suspend fun backupSnapshot(): Result<Map<String, PrivatePaykitContactLinkBackupV1>?> =
withContext(serializedDispatcher) {
runCatching {
ensureState().contacts.mapNotNull { (publicKey, contactState) ->
if (!contactState.hasBackupState) return@mapNotNull null
publicKey to PrivatePaykitContactLinkBackupV1(
publicKey = publicKey,
linkSnapshotHex = contactState.linkSnapshotHex,
handshakeSnapshotHex = contactState.handshakeSnapshotHex,
remoteEndpoints = contactState.remoteEndpoints.associate { it.methodId to it.endpointData },
linkCompletedAt = contactState.linkCompletedAt,
handshakeUpdatedAt = contactState.handshakeUpdatedAt,
recoveryStartedAt = contactState.recoveryStartedAt,
mainRecoveryAttemptId = contactState.mainRecoveryAttemptId,
responderRecoveryAttemptId = contactState.responderRecoveryAttemptId,
awaitingRecoveredRemoteEndpoints = contactState.awaitingRecoveredRemoteEndpoints,
)
}.toMap().takeIf { it.isNotEmpty() }
}
}
suspend fun restoreBackup(backup: Map<String, PrivatePaykitContactLinkBackupV1>?): Result<Unit> =
withContext(serializedDispatcher) {
runCatching {
publicationMutex.withLock {
linkEstablishmentMutex.withLock {
resetInFlightWork()
closeActiveHandles()
activeHandlesByContact.clear()
knownSavedContactKeys.clear()
if (backup == null) {
stateStore.replaceState(PrivatePaykitState())
persistState(preserveCleanupMarkers = false)
notifyBackupStateChanged()
return@runCatching
}
val contacts = backup.mapNotNull { (publicKey, contactBackup) ->
val normalizedKey = normalizedPublicKey(publicKey) ?: return@mapNotNull null
val linkSnapshotHex = validatedSnapshot(
contactBackup.linkSnapshotHex,
normalizedKey,
pubkyService::encryptedLinkSnapshotRecipient,
)
val handshakeSnapshotHex = validatedSnapshot(
contactBackup.handshakeSnapshotHex,
normalizedKey,
pubkyService::encryptedLinkHandshakeSnapshotRecipient,
)
normalizedKey to ContactState(
linkSnapshotHex = linkSnapshotHex,
handshakeSnapshotHex = handshakeSnapshotHex,
remoteEndpoints = PrivatePaykitPayloads.storedPaymentEntries(
contactBackup.remoteEndpoints,
),
linkCompletedAt = contactBackup.linkCompletedAt,
handshakeUpdatedAt = contactBackup.handshakeUpdatedAt,
recoveryStartedAt = contactBackup.recoveryStartedAt,
mainRecoveryAttemptId = contactBackup.mainRecoveryAttemptId,
responderRecoveryAttemptId = contactBackup.responderRecoveryAttemptId,
awaitingRecoveredRemoteEndpoints = contactBackup.awaitingRecoveredRemoteEndpoints,
)
}.toMap()
stateStore.replaceState(PrivatePaykitState(contacts = contacts.toMutableMap()))
}
}
persistState(preserveCleanupMarkers = false)
notifyBackupStateChanged()
}
}
private suspend fun beginPrivatePayment(publicKey: String): Result<PublicPaykitPaymentResult> =
withContext(serializedDispatcher) {
runCatching {
val generation = currentStateGeneration()
val linkId = establishedLinkId(publicKey, maxAdvanceSteps = 5, generation = generation).getOrThrow()
?: throw PrivatePaykitError.PrivateUnavailable
if (ensureState().contacts[publicKey]?.lastLocalPayloadHash == null) {
publishLocalEndpointsBestEffort(
publicKey = publicKey,
linkId = linkId,
fetchedRemoteCount = 0,
context = "payment",
generation = generation,
)
}
var staleFetchError: Throwable? = null
val fetchedCount = fetchRemoteEndpoints(publicKey, linkId, generation).getOrElse {
if (PrivatePaykitErrorClassifier.shouldCountAsStaleLinkFailure(it)) {
Logger.warn(
"Private Paykit link is stale for '${redacted(publicKey)}'; using cached private endpoints",
it,
context = TAG,
)
staleFetchError = it
schedulePendingPublicationRetry(publicKey)
} else {
Logger.warn(
"Failed to refresh private Paykit endpoints for '${redacted(publicKey)}'",
it,
context = TAG,
)
}
0
}
if (staleFetchError == null) {
val publishLinkId = activeHandlesByContact[publicKey]?.linkId ?: linkId
publishLocalEndpointsBestEffort(
publicKey = publicKey,
linkId = publishLinkId,
fetchedRemoteCount = fetchedCount,
context = "payment",
generation = generation,
respectInitialPublishDelay = false,
)
}
val cachedResult = cachedPrivatePaymentResult(publicKey)
if (cachedResult is PublicPaykitPaymentResult.Opened) {
clearAwaitingRecoveredRemoteEndpoints(publicKey)
return@runCatching cachedResult
}
staleFetchError?.let { throw it }
cachedResult
}
}
private suspend fun beginPrivatePaymentWithRecoveryRetry(publicKey: String): PrivatePaymentAttempt {
var shouldDeferPublicFallback = shouldDeferPublicFallbackForPrivateRecovery(publicKey)
var result = runCatching { beginPrivatePayment(publicKey).getOrThrow() }
repeat(PRIVATE_PAYMENT_RECOVERY_RETRY_ATTEMPTS) {
shouldDeferPublicFallback = shouldDeferPublicFallback ||
shouldDeferPublicFallbackForPrivateRecovery(publicKey)
if (!shouldRetryPrivatePaymentBeforePublicFallback(publicKey, result, shouldDeferPublicFallback)) {
return PrivatePaymentAttempt(result, shouldDeferPublicFallback)
}
delay(privatePaymentRecoveryRetryDelay)
result = runCatching { beginPrivatePayment(publicKey).getOrThrow() }
}
shouldDeferPublicFallback = shouldDeferPublicFallback ||
shouldDeferPublicFallbackForPrivateRecovery(publicKey)
return PrivatePaymentAttempt(result, shouldDeferPublicFallback)
}
private suspend fun shouldRetryPrivatePaymentBeforePublicFallback(
publicKey: String,
result: Result<PublicPaykitPaymentResult>,
shouldDeferPublicFallback: Boolean,
): Boolean {
if (result.getOrNull() is PublicPaykitPaymentResult.Opened) return false
result.exceptionOrNull()?.let {
if (it is CancellationException) throw it
if (it is PrivatePaykitError.PrivateUnavailable) {
return shouldDeferPublicFallback || shouldDeferPublicFallbackForPrivateRecovery(publicKey)
}
}
return shouldDeferPublicFallback || shouldDeferPublicFallbackForPrivateRecovery(publicKey)
}
private suspend fun shouldDeferPublicFallbackForPrivateRecovery(publicKey: String): Boolean {
val contactState = ensureState().contacts[publicKey] ?: return false
return contactState.recoveryStartedAt != null ||
contactState.mainRecoveryAttemptId != null ||
contactState.responderRecoveryAttemptId != null ||
contactState.awaitingRecoveredRemoteEndpoints
}
private suspend fun clearAwaitingRecoveredRemoteEndpoints(publicKey: String) {
val contactState = ensureState().contacts[publicKey] ?: return
if (!contactState.awaitingRecoveredRemoteEndpoints) return
contactState.awaitingRecoveredRemoteEndpoints = false
persistState(markWalletBackup = true)
}
private suspend fun cachedPrivatePaymentResult(publicKey: String): PublicPaykitPaymentResult {
val cachedEntries = ensureState().contacts[publicKey]?.remoteEndpoints.orEmpty()
val endpoints = cachedEntries.mapNotNull {
PublicPaykitRepo.parseEndpoint(it.methodId, it.endpointData)
}
val payable = privatePayableEndpoints(endpoints, publicKey)
if (payable.isEmpty()) {
return when {
cachedEntries.isEmpty() -> PublicPaykitPaymentResult.NoEndpoint
else -> PublicPaykitPaymentResult.NotOpened
}
}
return PublicPaykitPaymentResult.Opened(PublicPaykitRepo.paymentRequest(payable))
}
@Suppress("CyclomaticComplexMethod", "LongMethod")
private suspend fun publishLocalEndpoints(
publicKeys: Collection<String>,
maxAdvanceSteps: Int,
reason: String,
scheduleRetries: Boolean = true,
forceLocalPublishWhenRemoteEmpty: Boolean = false,
forceRefreshLightning: Boolean = false,
requireImmediatePublication: Boolean = false,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
val generation = currentStateGeneration()
var firstError: Throwable? = null
publicKeys.forEach { publicKey ->
val normalizedKey = knownSavedContact(publicKey) ?: return@forEach
val redactedKey = redacted(normalizedKey)
val linkId = establishedLinkIdForPublish(
publicKey = normalizedKey,
redactedKey = redactedKey,
maxAdvanceSteps = maxAdvanceSteps,
generation = generation,
scheduleRetries = scheduleRetries,
) ?: run {
if (firstError == null && requireImmediatePublication) {
firstError = PrivatePaykitError.PrivateUnavailable
}
return@forEach
}
if (publishLocalEndpointsBeforeFetch(normalizedKey, linkId, reason, scheduleRetries, generation)) {
return@forEach
}
val fetchedCount = fetchRemoteEndpointCountForPublish(
publicKey = normalizedKey,
linkId = linkId,
reason = reason,
scheduleRetries = scheduleRetries,
generation = generation,
) ?: run {
if (firstError == null && requireImmediatePublication) {
firstError = PrivatePaykitError.PrivateUnavailable
}
return@forEach
}
val contactState = ensureState().contacts[normalizedKey]
val shouldForcePublish = forceLocalPublishWhenRemoteEmpty &&
fetchedCount == 0 &&
contactState?.remoteEndpoints.isNullOrEmpty()
val publishLinkId = activeHandlesByContact[normalizedKey]?.linkId ?: linkId
val publishResult = publishLocalEndpoints(
publicKey = normalizedKey,
linkId = publishLinkId,
force = shouldForcePublish,
generation = generation,
forceRefreshLightning = forceRefreshLightning,
).onFailure {
if (scheduleRetries) schedulePendingPublicationRetry(normalizedKey)
Logger.warn(
"Failed to publish private Paykit endpoints during '$reason' for '$redactedKey'",
it,
context = TAG,
)
if (firstError == null && requireImmediatePublication) firstError = it
}
val updatedContactState = ensureState().contacts[normalizedKey]
val needsRetry = publishResult.isFailure ||
updatedContactState?.linkCompletedAt == null ||
updatedContactState.lastLocalPayloadHash == null ||
(fetchedCount == 0 && updatedContactState.remoteEndpoints.isEmpty()) ||
shouldRetryMissingPrivateLightningEndpoint(normalizedKey)
if (scheduleRetries && needsRetry) {
schedulePendingPublicationRetry(normalizedKey)
} else {
cancelPendingPublicationRetry(normalizedKey)
}
}
firstError?.let { throw it }
Unit
}
}
private suspend fun establishedLinkIdForPublish(
publicKey: String,
redactedKey: String,
maxAdvanceSteps: Int,
generation: Long,
scheduleRetries: Boolean,
): String? =
establishedLinkId(publicKey, maxAdvanceSteps, generation).fold(
onSuccess = {
if (it == null) {
if (scheduleRetries) schedulePendingPublicationRetry(publicKey)
Logger.debug(
"Deferred private Paykit endpoint publish for '$redactedKey'",
context = TAG,
)
}
it
},
onFailure = {
val shouldRetry = PrivatePaykitErrorClassifier.shouldRetryLinkEstablishmentFailure(it)
if (scheduleRetries && shouldRetry) schedulePendingPublicationRetry(publicKey)
Logger.debug(
if (shouldRetry) {
"Deferred private Paykit endpoint publish for '$redactedKey'"
} else {
"Skipped private Paykit endpoint publish for '$redactedKey'"
},
context = TAG,
)
null
},
)
private suspend fun publishLocalEndpointsBeforeFetch(
publicKey: String,
linkId: String,
reason: String,
scheduleRetries: Boolean,
generation: Long,
): Boolean {
if (!contactStateShouldPublishBeforeFetch(publicKey)) return false
val publishResult = publishLocalEndpoints(
publicKey = publicKey,
linkId = linkId,
generation = generation,
).onFailure {
if (scheduleRetries) schedulePendingPublicationRetry(publicKey)
Logger.warn(
"Failed to publish private Paykit endpoints during '$reason' for '${redacted(publicKey)}'",
it,
context = TAG,
)
}
if (publishResult.isFailure) return false
if (scheduleRetries) schedulePendingPublicationRetry(publicKey)
return true
}
private suspend fun fetchRemoteEndpointCountForPublish(
publicKey: String,
linkId: String,
reason: String,
scheduleRetries: Boolean,
generation: Long,
): Int? = fetchRemoteEndpoints(publicKey, linkId, generation).fold(
onSuccess = { it },
onFailure = {
if (scheduleRetries) {
schedulePendingPublicationRetry(publicKey)
}
Logger.warn(
"Failed to fetch private Paykit endpoints during '$reason' for '${redacted(publicKey)}'",
it,
context = TAG,
)
if (PrivatePaykitErrorClassifier.shouldCountAsStaleLinkFailure(it)) null else 0
},
)
private suspend fun publishLocalEndpointsBestEffort(
publicKey: String,
linkId: String,
fetchedRemoteCount: Int,
context: String,
generation: Long = currentStateGeneration(),
respectInitialPublishDelay: Boolean = true,
forceRefreshLightning: Boolean = false,
) {
if (!canPublishPrivateEndpoints()) return
if (!shouldPublishLocalEndpoints(publicKey, fetchedRemoteCount)) return
if (respectInitialPublishDelay && shouldDeferInitialLocalPublish(publicKey, fetchedRemoteCount)) return
publishLocalEndpoints(
publicKey = publicKey,
linkId = linkId,
generation = generation,
forceRefreshLightning = forceRefreshLightning,
).onFailure {
schedulePendingPublicationRetry(publicKey)
Logger.warn(
"Failed to publish private Paykit endpoints during '$context' for '${redacted(publicKey)}'",
it,
context = TAG,
)
}
}
private fun schedulePendingPublicationRetry(
publicKey: String,
remainingAttempts: Int = PENDING_PUBLICATION_RETRY_ATTEMPTS,
) {
if (remainingAttempts <= 0) return
if (publicKey !in knownSavedContactKeys) return
if (pendingPublicationRetryJobs[publicKey] != null) return
pendingPublicationRetryJobs[publicKey] = retryScope.launch {
delay(pendingPublicationRetryDelay)
pendingPublicationRetryJobs.remove(publicKey)
if (publicKey !in knownSavedContactKeys) return@launch
if (!canPublishPrivateEndpoints()) return@launch
publishLocalEndpoints(
publicKeys = listOf(publicKey),
maxAdvanceSteps = 3,
reason = "retry",
scheduleRetries = false,
forceLocalPublishWhenRemoteEmpty = true,
).onFailure {
Logger.warn(
"Failed to retry private Paykit endpoints for '${redacted(publicKey)}'",
it,
context = TAG,
)
}
val contactState = ensureState().contacts[publicKey]
val needsRetry = contactState?.linkCompletedAt == null ||
contactState.lastLocalPayloadHash == null ||
contactState.remoteEndpoints.isEmpty() ||
shouldRetryMissingPrivateLightningEndpoint(publicKey)
if (needsRetry) schedulePendingPublicationRetry(publicKey, remainingAttempts - 1)
}
}
private fun cancelPendingPublicationRetry(publicKey: String) {
pendingPublicationRetryJobs.remove(publicKey)?.cancel()
}
private fun resetInFlightWork() {
advanceStateGeneration()
pendingPublicationRetryJobs.values.forEach { it.cancel() }
pendingPublicationRetryJobs.clear()
}
private fun advanceStateGeneration() {
stateGeneration.incrementAndGet()
}
private fun currentStateGeneration(): Long = stateGeneration.get()
private fun ensureCurrentGeneration(generation: Long) {
if (stateGeneration.get() != generation) throw PrivatePaykitError.PrivateUnavailable
}
private suspend fun publishLocalEndpoints(
publicKey: String,
linkId: String,
force: Boolean = false,
generation: Long = currentStateGeneration(),
forceRefreshLightning: Boolean = false,
): Result<Unit> = withContext(serializedDispatcher) {
runCatching {
publicationMutex.withLock {
ensureCurrentGeneration(generation)
if (!canPublishPrivateEndpoints() || knownSavedContact(publicKey) == null) return@withLock
val endpoints = buildLocalEndpoints(publicKey, forceRefreshLightning).getOrThrow()
if (endpoints.isEmpty()) throw PublicPaykitError.NoSupportedEndpoint
ensureCurrentGeneration(generation)
val payloadSelection = PrivatePaykitPayloads.entriesWithinNoiseLimit(endpoints)
if (payloadSelection.droppedLightning) {
Logger.warn(
"Published private Paykit on-chain only for '${redacted(publicKey)}'",
context = TAG,
)
}
val entries = payloadSelection.entries
val payloadHash = PrivatePaykitPayloads.localPayloadHash(entries)
val contactState = ensureState().contacts.getOrPut(publicKey) { ContactState() }
if (!force && contactState.lastLocalPayloadHash == payloadHash) return@withLock
ensureCurrentGeneration(generation)
if (!canPublishPrivateEndpoints() || knownSavedContact(publicKey) == null) return@withLock
pubkyService.setPrivatePayments(linkId, entries.map { FfiPaymentEntry(it.methodId, it.endpointData) })
ensureCurrentGeneration(generation)
persistLinkSnapshot(linkId, publicKey, linkWasReplaced = false, generation = generation).getOrThrow()
contactState.lastLocalPayloadHash = payloadHash
persistState(markWalletBackup = false)
}
}.onFailure {
recordLinkFailure(publicKey, it, generation)
}
}
private suspend fun buildLocalEndpoints(
publicKey: String,
forceRefreshLightning: Boolean = false,
): Result<List<Endpoint>> =
withContext(serializedDispatcher) {
runCatching {
val settings = settingsStore.data.first()
val endpoints = mutableListOf<Endpoint>()
if (PublicPaykitRepo.isOnchainPaymentOptionEnabled(settings)) {
val reservedAddress = addressReservationRepo.currentOrRotatedAddress(publicKey).getOrThrow()
walletRepo.refreshReusableReceiveAddressIfReserved().getOrThrow()
endpoints += Endpoint(
methodId = PublicPaykitRepo.onchainMethodId(reservedAddress),
value = reservedAddress,
rawPayload = PublicPaykitRepo.serializePayload(reservedAddress),
)
}
if (PublicPaykitRepo.isLightningPaymentOptionEnabled(settings) && lightningRepo.canReceive()) {
currentOrRotatedInvoice(publicKey, forceRefresh = forceRefreshLightning).onSuccess { invoice ->
endpoints += Endpoint(
methodId = MethodId.Bolt11,
value = invoice.bolt11,
rawPayload = PublicPaykitRepo.serializePayload(invoice.bolt11),
)
}.onFailure {
if (it is PrivatePaykitError.RouteHintsUnavailable) {
schedulePendingPublicationRetry(publicKey)
}
Logger.warn(
"Failed to prepare private Paykit invoice for '${redacted(publicKey)}'",
it,