-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLightningRepo.kt
More file actions
1429 lines (1252 loc) · 57.9 KB
/
LightningRepo.kt
File metadata and controls
1429 lines (1252 loc) · 57.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 androidx.compose.runtime.Stable
import com.google.firebase.messaging.FirebaseMessaging
import com.synonym.bitkitcore.AddressType
import com.synonym.bitkitcore.ClosedChannelDetails
import com.synonym.bitkitcore.FeeRates
import com.synonym.bitkitcore.LightningInvoice
import com.synonym.bitkitcore.PreActivityMetadata
import com.synonym.bitkitcore.Scanner
import com.synonym.bitkitcore.createChannelRequestUrl
import com.synonym.bitkitcore.createWithdrawCallbackUrl
import com.synonym.bitkitcore.lnurlAuth
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.lightningdevkit.ldknode.Address
import org.lightningdevkit.ldknode.BalanceDetails
import org.lightningdevkit.ldknode.BestBlock
import org.lightningdevkit.ldknode.ChannelConfig
import org.lightningdevkit.ldknode.ChannelDataMigration
import org.lightningdevkit.ldknode.ChannelDetails
import org.lightningdevkit.ldknode.ClosureReason
import org.lightningdevkit.ldknode.Event
import org.lightningdevkit.ldknode.NodeStatus
import org.lightningdevkit.ldknode.PaymentDetails
import org.lightningdevkit.ldknode.PaymentId
import org.lightningdevkit.ldknode.PeerDetails
import org.lightningdevkit.ldknode.SpendableUtxo
import org.lightningdevkit.ldknode.Txid
import to.bitkit.data.CacheStore
import to.bitkit.data.SettingsData
import to.bitkit.data.SettingsStore
import to.bitkit.data.backup.VssBackupClientLdk
import to.bitkit.data.keychain.Keychain
import to.bitkit.di.BgDispatcher
import to.bitkit.env.Env
import to.bitkit.ext.getSatsPerVByteFor
import to.bitkit.ext.nowTimestamp
import to.bitkit.ext.toPeerDetailsList
import to.bitkit.models.ALL_ADDRESS_TYPE_STRINGS
import to.bitkit.models.CoinSelectionPreference
import to.bitkit.models.NATIVE_WITNESS_TYPES
import to.bitkit.models.NodeLifecycleState
import to.bitkit.models.OpenChannelResult
import to.bitkit.models.TransactionSpeed
import to.bitkit.models.safe
import to.bitkit.models.toAddressType
import to.bitkit.models.toCoinSelectAlgorithm
import to.bitkit.models.toCoreNetwork
import to.bitkit.models.toSettingsString
import to.bitkit.services.CoreService
import to.bitkit.services.LightningService
import to.bitkit.services.LnurlChannelResponse
import to.bitkit.services.LnurlService
import to.bitkit.services.LnurlWithdrawResponse
import to.bitkit.services.LspNotificationsService
import to.bitkit.services.NodeEventHandler
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import to.bitkit.utils.ServiceError
import to.bitkit.utils.UrlValidator
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
@Singleton
@Suppress("LongParameterList", "TooManyFunctions", "LargeClass")
class LightningRepo @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val lightningService: LightningService,
private val settingsStore: SettingsStore,
private val coreService: CoreService,
private val lspNotificationsService: LspNotificationsService,
private val firebaseMessaging: FirebaseMessaging,
private val keychain: Keychain,
private val lnurlService: LnurlService,
private val cacheStore: CacheStore,
private val preActivityMetadataRepo: PreActivityMetadataRepo,
private val connectivityRepo: ConnectivityRepo,
private val vssBackupClientLdk: VssBackupClientLdk,
private val urlValidator: UrlValidator,
) {
private val _lightningState = MutableStateFlow(LightningState())
val lightningState = _lightningState.asStateFlow()
private val _nodeEvents = MutableSharedFlow<Event>(extraBufferCapacity = 64)
val nodeEvents = _nodeEvents.asSharedFlow()
private val scope = CoroutineScope(bgDispatcher + SupervisorJob())
private val _eventHandlers = ConcurrentHashMap.newKeySet<NodeEventHandler>()
private val _isRecoveryMode = MutableStateFlow(false)
val isRecoveryMode = _isRecoveryMode.asStateFlow()
private val channelCache = ConcurrentHashMap<String, ChannelDetails>()
private val syncMutex = Mutex()
private val syncPending = AtomicBoolean(false)
private val syncRetryJob = AtomicReference<Job?>(null)
private val lifecycleMutex = Mutex()
private val isChangingAddressType = AtomicBoolean(false)
init {
observeConnectivityForSyncRetry()
}
private fun observeConnectivityForSyncRetry() {
scope.launch {
connectivityRepo.isOnline
.map { it == ConnectivityState.CONNECTED }
.distinctUntilChanged()
.collect { isConnected ->
if (!isConnected) {
// Cancel any pending retry when disconnected
syncRetryJob.getAndSet(null)?.cancel()
return@collect
}
// Start retry loop if sync is failing
startSyncRetryLoopIfNeeded()
}
}
}
private fun startSyncRetryLoopIfNeeded() {
val state = _lightningState.value
if (!state.nodeLifecycleState.isRunning() || state.lastSyncError == null) {
return
}
// Don't start if already retrying
if (syncRetryJob.get()?.isActive == true) {
return
}
val job = scope.launch {
// Don't start retry loop if offline
if (connectivityRepo.isOnline.first() != ConnectivityState.CONNECTED) {
return@launch
}
while (isActive) {
val currentState = _lightningState.value
// Stop if no longer running or sync is now healthy
if (!currentState.nodeLifecycleState.isRunning() || currentState.isSyncHealthy) {
Logger.debug("Sync retry loop stopped: node not running or sync healthy", context = TAG)
break
}
delay(SYNC_RETRY_DELAY_MS)
Logger.info("Retrying sync after failure", context = TAG)
sync().onSuccess {
Logger.info("Sync retry succeeded", context = TAG)
}.onFailure {
Logger.warn("Sync retry failed, will retry in ${SYNC_RETRY_DELAY_MS / 1000}s", it, context = TAG)
}
}
}
syncRetryJob.set(job)
}
/**
* Executes the provided operation only if the node is running.
* If the node is not running, waits for it to be running for a specified timeout.
*
* @param operationName Name of the operation for logging
* @param waitTimeout Duration to wait for the node to be running
* @param operation Lambda to execute when the node is running
* @return Result of the operation, or failure if node isn't running or operation fails
*/
suspend fun <T> executeWhenNodeRunning(
operationName: String,
waitTimeout: Duration = 1.minutes,
operation: suspend () -> Result<T>,
): Result<T> = withContext(bgDispatcher) {
Logger.verbose("Operation called: '$operationName'", context = TAG)
val nodeLifecycleState = _lightningState.value.nodeLifecycleState
if (nodeLifecycleState.isRunning()) {
return@withContext executeOperation(operationName, operation)
}
// If node is not in a state that can become running, fail fast
if (!nodeLifecycleState.canRun()) {
return@withContext Result.failure(
AppError("Cannot execute '$operationName': node is '$nodeLifecycleState' and not starting")
)
}
val nodeRunning = withTimeoutOrNull(waitTimeout) {
if (nodeLifecycleState.isRunning()) return@withTimeoutOrNull true
// Otherwise, wait for it to transition to running state
Logger.verbose("Waiting for node to run before executing '$operationName'", context = TAG)
_lightningState.first { it.nodeLifecycleState.isRunning() }
Logger.debug("Operation executed: '$operationName'", context = TAG)
true
} ?: false
if (!nodeRunning) return@withContext Result.failure(NodeRunTimeoutError(operationName))
return@withContext executeOperation(operationName, operation)
}
private suspend fun <T> executeOperation(
operationName: String,
operation: suspend () -> Result<T>,
): Result<T> = runCatching {
operation().getOrThrow()
}.onFailure {
// Cancellation is expected during pull-to-refresh, rethrow per Kotlin best practices
if (it is CancellationException) throw it
Logger.error("Error executing '$operationName'", it, context = TAG)
}
private suspend fun setup(
walletIndex: Int,
customServerUrl: String? = null,
customRgsServerUrl: String? = null,
channelMigration: ChannelDataMigration? = null,
) = withContext(bgDispatcher) {
runCatching {
val trustedPeers = fetchTrustedPeers()
lightningService.setup(
walletIndex,
customServerUrl,
customRgsServerUrl,
trustedPeers,
channelMigration,
)
}.onFailure {
Logger.error("Node setup error", it, context = TAG)
}
}
private suspend fun fetchTrustedPeers(): List<PeerDetails>? = runCatching {
val info = coreService.blocktank.info(refresh = false)
?: coreService.blocktank.info(refresh = true)
info?.nodes?.toPeerDetailsList()?.also {
Logger.info("Fetched ${it.size} trusted peers from remote", context = TAG)
}
}.onFailure {
Logger.warn("fetchTrustedPeers error", it, context = TAG)
}.getOrNull()
@Suppress("LongMethod", "LongParameterList")
suspend fun start(
walletIndex: Int = 0,
timeout: Duration? = null,
shouldRetry: Boolean = true,
customServerUrl: String? = null,
customRgsServerUrl: String? = null,
eventHandler: NodeEventHandler? = null,
channelMigration: ChannelDataMigration? = null,
shouldValidateGraph: Boolean = true,
): Result<Unit> = withContext(bgDispatcher) {
if (_isRecoveryMode.value) {
return@withContext Result.failure(RecoveryModeError())
}
eventHandler?.let { _eventHandlers.add(it) }
// Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant)
var shouldRetryStart = false
var shouldRestartForGraphReset = false
var initialLifecycleState: NodeLifecycleState
val result = lifecycleMutex.withLock {
initialLifecycleState = _lightningState.value.nodeLifecycleState
if (initialLifecycleState.isRunningOrStarting()) {
Logger.info("LDK node start skipped, lifecycle state: $initialLifecycleState", context = TAG)
lightningService.startEventListener(::onEvent)
return@withLock Result.success(Unit)
}
runCatching {
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Starting) }
// Setup if needed
if (lightningService.node == null) {
val setupResult = setup(walletIndex, customServerUrl, customRgsServerUrl, channelMigration)
if (setupResult.isFailure) {
_lightningState.update {
it.copy(
nodeLifecycleState = NodeLifecycleState.ErrorStarting(
setupResult.exceptionOrNull() ?: NodeSetupError()
)
)
}
return@withLock setupResult
}
}
if (getStatus()?.isRunning == true) {
Logger.info("LDK node already running", context = TAG)
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
lightningService.startEventListener(::onEvent).onFailure {
Logger.warn("Failed to start event listener", it, context = TAG)
return@withLock Result.failure(it)
}
return@withLock Result.success(Unit)
}
lightningService.start(timeout, ::onEvent)
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
// Initial state sync
syncState()
updateGeoBlockState()
refreshChannelCache()
if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) {
Logger.warn("Network graph is stale, resetting and restarting...", context = TAG)
lightningService.stop()
lightningService.resetNetworkGraph(walletIndex)
runCatching {
vssBackupClientLdk.setup(walletIndex).getOrThrow()
vssBackupClientLdk.deleteObject("network_graph").getOrThrow()
Logger.info("Cleared stale network graph from VSS (first delete)", context = TAG)
}.onFailure {
Logger.warn("Failed to clear graph from VSS (first delete)", it, context = TAG)
}
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) }
shouldRestartForGraphReset = true
return@withLock Result.success(Unit)
}
// Post-startup tasks (non-blocking)
connectToTrustedPeers().onFailure {
Logger.error("Failed to connect to trusted peers", it, context = TAG)
}
sync().onFailure { e ->
Logger.warn("Initial sync failed, event-driven sync will retry", e, context = TAG)
}
scope.launch { registerForNotifications() }
Result.success(Unit)
}.getOrElse { e ->
val currentState = _lightningState.value.nodeLifecycleState
if (currentState.isRunning()) {
Logger.warn("Start error but node is $currentState, skipping retry", e, context = TAG)
return@withLock Result.success(Unit)
}
if (shouldRetry) {
Logger.warn("Start error, will retry...", e, context = TAG)
_lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) }
shouldRetryStart = true
Result.failure(e)
} else {
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) }
Result.failure(e)
}
}
}
// Retry OUTSIDE the mutex to avoid deadlock (Kotlin Mutex is non-reentrant)
if (shouldRetryStart) {
delay(2.seconds)
return@withContext start(
walletIndex = walletIndex,
timeout = timeout,
shouldRetry = false,
customServerUrl = customServerUrl,
customRgsServerUrl = customRgsServerUrl,
channelMigration = channelMigration,
shouldValidateGraph = shouldValidateGraph,
)
}
// Restart after graph reset OUTSIDE the mutex to avoid deadlock
if (shouldRestartForGraphReset) {
return@withContext start(
walletIndex = walletIndex,
timeout = timeout,
shouldRetry = shouldRetry,
customServerUrl = customServerUrl,
customRgsServerUrl = customRgsServerUrl,
eventHandler = eventHandler,
channelMigration = channelMigration,
shouldValidateGraph = false, // Prevent infinite loop
)
}
result
}
private suspend fun onEvent(event: Event) {
handleLdkEvent(event)
_eventHandlers.toList().forEach {
runCatching { it.invoke(event) }
}
_nodeEvents.emit(event)
}
fun setRecoveryMode(enabled: Boolean) = _isRecoveryMode.update { enabled }
suspend fun updateGeoBlockState() = withContext(bgDispatcher) {
_lightningState.update {
it.copy(isGeoBlocked = coreService.isGeoBlocked())
}
}
fun setInitNodeLifecycleState() {
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Initializing) }
}
suspend fun stop(): Result<Unit> = withContext(bgDispatcher) {
lifecycleMutex.withLock {
if (_lightningState.value.nodeLifecycleState.isStoppedOrStopping()) {
return@withLock Result.success(Unit)
}
runCatching {
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopping) }
lightningService.stop()
_lightningState.update { LightningState(nodeLifecycleState = NodeLifecycleState.Stopped) }
}.onFailure {
Logger.error("Node stop error", it, context = TAG)
// On failure, check actual node state and update accordingly
// If node is still running, revert to Running state to allow retry
if (lightningService.node != null && lightningService.status?.isRunning == true) {
Logger.warn("Stop failed but node is still running, reverting to Running state", context = TAG)
_lightningState.update { s -> s.copy(nodeLifecycleState = NodeLifecycleState.Running) }
} else {
// Node appears stopped, update state
_lightningState.update { LightningState(nodeLifecycleState = NodeLifecycleState.Stopped) }
}
}
}
}
@Suppress("TooGenericExceptionCaught")
suspend fun sync(): Result<Unit> = executeWhenNodeRunning("sync") {
// If sync is in progress, mark pending and skip
if (!syncMutex.tryLock()) {
syncPending.set(true)
Logger.verbose("Sync in progress, pending sync marked", context = TAG)
return@executeWhenNodeRunning Result.success(Unit)
}
runCatching {
do {
syncPending.set(false)
_lightningState.update { it.copy(isSyncingWallet = true) }
lightningService.sync()
refreshChannelCache()
syncState()
_lightningState.update {
it.copy(
lastSyncError = null,
lastSuccessfulSyncAt = System.currentTimeMillis(),
)
}
if (syncPending.get()) delay(MS_SYNC_LOOP_DEBOUNCE)
} while (syncPending.getAndSet(false))
}.also {
_lightningState.update { state -> state.copy(isSyncingWallet = false) }
syncMutex.unlock()
}.onFailure {
_lightningState.update { state -> state.copy(lastSyncError = it) }
startSyncRetryLoopIfNeeded()
}
}
fun syncAsync() = scope.launch {
sync().onFailure {
Logger.warn("Sync failed", it, context = TAG)
}
}
private suspend fun ensureSyncedBeforeSend(): Result<Unit> {
Logger.debug("Ensuring wallet is synced before send", context = TAG)
return sync().fold(
onSuccess = { Result.success(Unit) },
onFailure = {
Result.failure(SyncUnhealthyError())
},
)
}
/** Clear pending sync flag. Called when manual pull-to-refresh takes priority. */
fun clearPendingSync() = syncPending.set(false)
private suspend fun refreshChannelCache() = withContext(bgDispatcher) {
lightningService.channels?.forEach {
channelCache[it.channelId] = it
}
}
private fun handleLdkEvent(event: Event) {
when (event) {
is Event.ChannelPending, is Event.ChannelReady -> scope.launch { refreshChannelCache() }
is Event.ChannelClosed -> scope.launch { registerClosedChannel(event.channelId, event.reason) }
else -> Unit
}
}
private suspend fun registerClosedChannel(channelId: String, reason: ClosureReason?) = withContext(bgDispatcher) {
runCatching {
val channel = channelCache[channelId] ?: run {
Logger.error("Could not find details for closed channel: channelId='$channelId'", context = TAG)
return@withContext
}
val fundingTxo = channel.fundingTxo
if (fundingTxo == null) {
Logger.error(
"Channel has no funding transaction, cannot persist closed channel: channelId='$channelId'",
context = TAG,
)
return@withContext
}
val channelName = channel.inboundScidAlias?.toString()
?: (channel.channelId.take(LENGTH_CHANNEL_ID_PREVIEW) + "…")
val closedAt = (System.currentTimeMillis() / 1000L).toULong()
val closedChannel = ClosedChannelDetails(
channelId = channel.channelId,
counterpartyNodeId = channel.counterpartyNodeId,
fundingTxoTxid = fundingTxo.txid,
fundingTxoIndex = fundingTxo.vout,
channelValueSats = channel.channelValueSats,
closedAt = closedAt,
outboundCapacityMsat = channel.outboundCapacityMsat,
inboundCapacityMsat = channel.inboundCapacityMsat,
counterpartyUnspendablePunishmentReserve = channel.counterpartyUnspendablePunishmentReserve,
unspendablePunishmentReserve = channel.unspendablePunishmentReserve ?: 0u,
forwardingFeeProportionalMillionths = channel.config.forwardingFeeProportionalMillionths,
forwardingFeeBaseMsat = channel.config.forwardingFeeBaseMsat,
channelName = channelName,
channelClosureReason = reason?.toString().orEmpty(),
)
coreService.activity.upsertClosedChannelList(listOf(closedChannel))
channelCache.remove(channelId)
Logger.info("Registered closed channel: ${channel.userChannelId}", context = TAG)
}.onFailure {
Logger.error("Failed to register closed channel", it, context = TAG)
}
}
suspend fun wipeStorage(walletIndex: Int): Result<Unit> = withContext(bgDispatcher) {
Logger.debug("wipeStorage called, stopping node first", context = TAG)
stop().mapCatching {
Logger.debug("node stopped, calling wipeStorage", context = TAG)
lightningService.wipeStorage(walletIndex)
_lightningState.update {
LightningState(
nodeStatus = it.nodeStatus,
nodeLifecycleState = it.nodeLifecycleState,
)
}
setRecoveryMode(false)
}.onFailure {
Logger.error("wipeStorage error", it, context = TAG)
}
}
suspend fun restartWithElectrumServer(newServerUrl: String): Result<Unit> = withContext(bgDispatcher) {
Logger.info("Changing ldk-node electrum server to: '$newServerUrl'", context = TAG)
waitForNodeToStop().onFailure { return@withContext Result.failure(it) }
stop().onFailure {
Logger.error("Failed to stop node during electrum server change", it, context = TAG)
return@withContext Result.failure(it)
}
Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG)
start(
shouldRetry = false,
customServerUrl = newServerUrl,
).onFailure {
Logger.warn("Failed ldk-node config change, attempting recovery…", context = TAG)
restartWithPreviousConfig()
}.onSuccess {
settingsStore.update { it.copy(electrumServer = newServerUrl) }
Logger.info("Successfully changed electrum server", context = TAG)
}
}
suspend fun restartWithRgsServer(newRgsUrl: String): Result<Unit> = withContext(bgDispatcher) {
Logger.info("Changing ldk-node RGS server to: '$newRgsUrl'", context = TAG)
validateRgsUrl(newRgsUrl).onFailure {
Logger.warn("RGS server unreachable at '$newRgsUrl'", it, context = TAG)
return@withContext Result.failure(it)
}
waitForNodeToStop().onFailure { return@withContext Result.failure(it) }
stop().onFailure {
Logger.error("Failed to stop node during RGS server change", it, context = TAG)
return@withContext Result.failure(it)
}
Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG)
start(
shouldRetry = false,
customRgsServerUrl = newRgsUrl,
).onFailure {
Logger.warn("Failed ldk-node config change, attempting recovery…", context = TAG)
restartWithPreviousConfig()
}.onSuccess {
settingsStore.update { it.copy(rgsServerUrl = newRgsUrl) }
Logger.info("Successfully changed RGS server", context = TAG)
}
}
private suspend fun validateRgsUrl(url: String): Result<Unit> = withContext(bgDispatcher) {
val initialTimestamp = 0
val testUrl = "${url.trimEnd('/')}/$initialTimestamp"
urlValidator.validate(testUrl)
}
suspend fun getBalanceForAddressType(addressType: AddressType): Result<ULong> = withContext(bgDispatcher) {
executeWhenNodeRunning("getBalanceForAddressType") {
runCatching {
lightningService.getBalanceForAddressType(addressType).totalSats
}
}
}
suspend fun getChannelFundableBalance(): ULong = withContext(bgDispatcher) {
val settings = settingsStore.data.first()
val selectedType = settings.selectedAddressType.toAddressType()
val monitoredTypes = settings.addressTypesToMonitor.mapNotNull { it.toAddressType() }
val typesToSum = (listOfNotNull(selectedType) + monitoredTypes).distinct().filter { it != AddressType.P2PKH }
if (typesToSum.isEmpty()) {
return@withContext getBalancesAsync().getOrNull()?.spendableOnchainBalanceSats ?: 0uL
}
var total = 0uL
for (type in typesToSum) {
val balance = executeWhenNodeRunning("getBalanceForAddressType") {
runCatching { lightningService.getBalanceForAddressType(type).spendableSats }
}.getOrNull()
if (balance == null) {
return@withContext getBalancesAsync().getOrNull()?.spendableOnchainBalanceSats ?: 0uL
}
total = total.safe() + balance.safe()
}
total
}
suspend fun updateAddressType(
selectedType: String,
monitoredTypes: List<String>,
): Result<Unit> = withContext(bgDispatcher) {
if (!isChangingAddressType.compareAndSet(false, true)) {
return@withContext Result.failure(AppError("Address type change already in progress"))
}
val previousSettings = settingsStore.data.first()
val oldSelected = previousSettings.selectedAddressType
val oldMonitored = previousSettings.addressTypesToMonitor
val addressType = selectedType.toAddressType() ?: AddressType.P2WPKH
suspend fun rollback() =
settingsStore.update { it.copy(selectedAddressType = oldSelected, addressTypesToMonitor = oldMonitored) }
runCatching {
settingsStore.update {
it.copy(selectedAddressType = selectedType, addressTypesToMonitor = monitoredTypes)
}
lightningService.setPrimaryAddressType(addressType)
syncMonitoredTypesFromNode()
sync().onFailure { Logger.warn("Sync after address type change failed", it, context = TAG) }
Unit
}.onFailure {
rollback()
Logger.error("updateAddressType failed", it, context = TAG)
}.also {
isChangingAddressType.set(false)
}
}
suspend fun setMonitoring(addressType: AddressType, enabled: Boolean): Result<Unit> = withContext(bgDispatcher) {
if (!isChangingAddressType.compareAndSet(false, true)) {
return@withContext Result.failure(AppError("Address type change already in progress"))
}
val previousSettings = settingsStore.data.first()
val oldMonitored = previousSettings.addressTypesToMonitor.toList()
if (!enabled) {
val validationError = validateDisableMonitoring(addressType, previousSettings, oldMonitored)
if (validationError != null) {
isChangingAddressType.set(false)
return@withContext Result.failure(validationError)
}
}
val typeStr = addressType.toSettingsString()
val newMonitored = if (enabled) (oldMonitored + typeStr).distinct() else oldMonitored.filter { it != typeStr }
suspend fun rollback() = settingsStore.update { it.copy(addressTypesToMonitor = oldMonitored) }
runCatching {
settingsStore.update { it.copy(addressTypesToMonitor = newMonitored) }
if (enabled) {
lightningService.addAddressTypeToMonitor(addressType)
} else {
lightningService.removeAddressTypeFromMonitor(addressType)
}
sync().onFailure { Logger.warn("Sync after monitoring change failed", it, context = TAG) }
Unit
}.onFailure {
rollback()
Logger.error("setMonitoring failed", it, context = TAG)
}.also {
isChangingAddressType.set(false)
}
}
private suspend fun validateDisableMonitoring(
addressType: AddressType,
settings: SettingsData,
monitoredTypes: List<String>,
): AppError? {
if (addressType == settings.selectedAddressType.toAddressType()) {
return AppError("Cannot disable monitoring: address type is currently selected")
}
if (isLastRequiredNativeWitnessWallet(addressType, monitoredTypes)) {
return AppError(
"Cannot disable monitoring: at least one Native SegWit or Taproot wallet required for Lightning"
)
}
val balance = getBalanceForAddressType(addressType).getOrElse {
return AppError("Cannot disable monitoring: failed to verify balance")
}
if (balance > 0uL) {
return AppError("Cannot disable monitoring: address type has balance")
}
return null
}
private suspend fun syncMonitoredTypesFromNode() {
runCatching {
val nodeMonitored = lightningService.listMonitoredAddressTypes()
val settings = settingsStore.data.first()
val selectedType = settings.selectedAddressType.toAddressType() ?: AddressType.P2WPKH
val combined = (nodeMonitored + selectedType).distinct()
val allOrdered = ALL_ADDRESS_TYPE_STRINGS
val newMonitored = allOrdered.filter { typeStr ->
typeStr.toAddressType() in combined
}
settingsStore.update { it.copy(addressTypesToMonitor = newMonitored) }
}.onFailure {
Logger.warn("syncMonitoredTypesFromNode failed", it, context = TAG)
}
}
fun isChangingAddressType(): Boolean = isChangingAddressType.get()
suspend fun pruneEmptyAddressTypesAfterRestore(): Result<Unit> = withContext(bgDispatcher) {
if (isChangingAddressType.get()) return@withContext Result.success(Unit)
val settings = settingsStore.data.first()
val selectedType = settings.selectedAddressType.toAddressType() ?: AddressType.P2WPKH
val monitored = settings.addressTypesToMonitor.toMutableList()
val toRemove = monitored.filter { typeStr ->
if (typeStr == settings.selectedAddressType) return@filter false
val type = typeStr.toAddressType() ?: return@filter false
val balance = getBalanceForAddressType(type).getOrNull() ?: return@filter false
if (balance != 0uL) return@filter false
val wouldLeaveNativeWitness = (selectedType in NATIVE_WITNESS_TYPES) ||
monitored.any { it != typeStr && it.toAddressType() in NATIVE_WITNESS_TYPES }
wouldLeaveNativeWitness
}
if (toRemove.isEmpty()) return@withContext Result.success(Unit)
val newMonitored = monitored.filter { it !in toRemove }
settingsStore.update { it.copy(addressTypesToMonitor = newMonitored) }
for (typeStr in toRemove) {
val type = typeStr.toAddressType() ?: continue
runCatching { lightningService.removeAddressTypeFromMonitor(type) }.onFailure {
Logger.error("Failed to remove address type $typeStr from monitor", it, context = TAG)
}
}
sync().onFailure { Logger.warn("Sync after prune failed", it, context = TAG) }
Result.success(Unit)
}
private fun isLastRequiredNativeWitnessWallet(addressType: AddressType, monitoredTypes: List<String>): Boolean {
if (addressType !in NATIVE_WITNESS_TYPES) return false
val monitored = monitoredTypes.mapNotNull { it.toAddressType() }
val remaining = monitored.filter { it != addressType && it in NATIVE_WITNESS_TYPES }
return remaining.isEmpty()
}
private suspend fun restartWithPreviousConfig(): Result<Unit> = withContext(bgDispatcher) {
Logger.debug("Stopping node for recovery attempt", context = TAG)
stop().onFailure { e ->
Logger.error("Failed to stop node during recovery", e, context = TAG)
return@withContext Result.failure(e)
}
Logger.debug("Starting node with previous config for recovery", context = TAG)
start(
shouldRetry = false,
).onSuccess {
Logger.debug("Successfully started node with previous config", context = TAG)
}.onFailure {
Logger.error("Failed starting node with previous config", it, context = TAG)
}
}
private suspend fun waitForNodeToStop(): Result<Unit> = withContext(bgDispatcher) {
if (_lightningState.value.nodeLifecycleState == NodeLifecycleState.Stopping) {
Logger.debug("Waiting for node to stop…", context = TAG)
val stopped = withTimeoutOrNull(30.seconds) {
_lightningState.first { it.nodeLifecycleState == NodeLifecycleState.Stopped }
}
if (stopped == null) {
val error = NodeStopTimeoutError()
Logger.warn(error.message, context = TAG)
return@withContext Result.failure(error)
}
}
return@withContext Result.success(Unit)
}
suspend fun connectToTrustedPeers(): Result<Unit> = executeWhenNodeRunning("connectToTrustedPeers") {
runCatching { lightningService.connectToTrustedPeers() }.also {
syncState()
}
}
suspend fun connectPeer(peer: PeerDetails): Result<Unit> = executeWhenNodeRunning("connectPeer") {
lightningService.connectPeer(peer).map {
syncState()
}
}
suspend fun disconnectPeer(peer: PeerDetails): Result<Unit> = executeWhenNodeRunning("disconnectPeer") {
lightningService.disconnectPeer(peer).map {
syncState()
}
}
suspend fun newAddress(): Result<String> = executeWhenNodeRunning("newAddress") {
runCatching { lightningService.newAddress() }
}
suspend fun createInvoice(
amountSats: ULong? = null,
description: String,
expirySeconds: UInt = 86_400u,
): Result<String> = executeWhenNodeRunning("createInvoice") {
updateGeoBlockState()
runCatching { lightningService.receive(amountSats, description, expirySeconds) }
}
@Suppress("ForbiddenComment")
suspend fun fetchLnurlInvoice(
callbackUrl: String,
amountSats: ULong,
comment: String? = null,
): Result<LightningInvoice> {
return runCatching {
// TODO use bitkit-core getLnurlInvoice if it works with callbackUrl
val bolt11 = lnurlService.fetchLnurlInvoice(callbackUrl, amountSats, comment).getOrThrow().pr
val decoded = (coreService.decode(bolt11) as Scanner.Lightning).invoice
return@runCatching decoded
}.onFailure {
Logger.error(
"fetchLnurlInvoice error, url: $callbackUrl, amount: $amountSats, comment: $comment",
it,
context = TAG,
)
}
}
suspend fun requestLnurlWithdraw(
k1: String,
callback: String,
paymentRequest: String,
): Result<LnurlWithdrawResponse> = executeWhenNodeRunning("requestLnurlWithdraw") {
val callbackUrl = createWithdrawCallbackUrl(k1, callback, paymentRequest)
Logger.debug("handleLnurlWithdraw callbackUrl generated: '$callbackUrl'", context = TAG)
lnurlService.requestLnurlWithdraw(callbackUrl)
}
suspend fun requestLnurlChannel(
k1: String,
callback: String,
nodeId: String,
): Result<LnurlChannelResponse> = executeWhenNodeRunning("requestLnurlChannel") {
val url = createChannelRequestUrl(
k1 = k1,
callback = callback,
localNodeId = nodeId,
isPrivate = true,
cancel = false,
)
lnurlService.requestLnurlChannel(url)
}
suspend fun requestLnurlAuth(
k1: String,
callback: String,
domain: String,
): Result<String> = runCatching {
val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound()
val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)
lnurlAuth(
k1 = k1,
callback = callback,
domain = domain,
network = Env.network.toCoreNetwork(),
bip32Mnemonic = mnemonic,
bip39Passphrase = passphrase,
).also {
Logger.debug("LNURL auth result: '$it'", context = TAG)
}
}.onFailure {
Logger.error("requestLnurlAuth error, k1: $k1, callback: $callback, domain: $domain", it, context = TAG)
}
suspend fun payInvoice(
bolt11: String,
sats: ULong? = null,
): Result<PaymentId> = executeWhenNodeRunning("payInvoice") {
waitForUsableChannels()
runCatching { lightningService.send(bolt11, sats) }.also {
syncState()
}
}
private suspend fun waitForUsableChannels() {
if (lightningService.channels?.any { it.isUsable } == true) return
Logger.info("Waiting for usable channels before sending payment", context = TAG)
syncState()
withTimeoutOrNull(CHANNELS_USABLE_TIMEOUT_MS) {
_lightningState.first { state -> state.channels.any { it.isUsable } }
} ?: Logger.warn("Timeout waiting for usable channels", context = TAG)
}
@Suppress("LongParameterList")
suspend fun sendOnChain(
address: Address,
sats: ULong,
speed: TransactionSpeed? = null,
utxosToSpend: List<SpendableUtxo>? = null,
feeRates: FeeRates? = null,
isTransfer: Boolean = false,
channelId: String? = null,
isMaxAmount: Boolean = false,
tags: List<String> = emptyList(),
): Result<Txid> = executeWhenNodeRunning("sendOnChain") {
require(address.isNotEmpty()) { "Send address cannot be empty" }