-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLightningService.swift
More file actions
1499 lines (1280 loc) · 59.5 KB
/
LightningService.swift
File metadata and controls
1499 lines (1280 loc) · 59.5 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
import BitkitCore
import Combine
import Foundation
import LDKNode
// TODO: catch all errors and pass a readable error message to the UI
class LightningService {
private var node: Node?
var currentWalletIndex: Int = 0
// MARK: - Stale monitor recovery (one-time recovery for channel monitor desync)
private static let staleMonitorRecoveryAttemptedKey = "staleMonitorRecoveryAttempted"
/// Whether we've already attempted stale monitor recovery (prevents infinite retry).
/// Persisted so the retry only happens once, even across app restarts.
private static var staleMonitorRecoveryAttempted: Bool {
get { UserDefaults.standard.bool(forKey: staleMonitorRecoveryAttemptedKey) }
set { UserDefaults.standard.set(newValue, forKey: staleMonitorRecoveryAttemptedKey) }
}
private let syncStatusChangedSubject = PassthroughSubject<UInt64, Never>()
private var channelCache: [String: ChannelDetails] = [:]
// Cached values to avoid blocking LDK calls on main thread
// MainActor isolated to prevent data races between background writes and UI reads
@MainActor private var cachedStatus: NodeStatus?
@MainActor private var cachedBalances: BalanceDetails?
@MainActor private var cachedPeers: [PeerDetails]?
@MainActor private var cachedChannels: [ChannelDetails]?
private var storedEventCallback: ((Event) -> Void)?
var syncStatusChangedPublisher: AnyPublisher<UInt64, Never> {
syncStatusChangedSubject.eraseToAnyPublisher()
}
static var shared = LightningService()
private init() {}
/// Flag and lock to prevent concurrent setup calls
private var isSettingUp = false
private let setupLock = NSLock()
func setup(
walletIndex: Int,
electrumServerUrl: String? = nil,
rgsServerUrl: String? = nil,
channelMigration: ChannelDataMigration? = nil
) async throws {
// Guard against concurrent setup calls
let shouldProceed: Bool = setupLock.withLock {
guard !isSettingUp && node == nil else {
Logger.debug("Node already setting up or already set up, skipping")
return false
}
isSettingUp = true
return true
}
guard shouldProceed else { return }
defer { setupLock.withLock { isSettingUp = false } }
Logger.debug("Checking lightning process lock...")
try await StateLocker.lock(.lightning, wait: 30) // Wait 30 seconds to lock because maybe extension is still running
guard var mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: walletIndex)) else {
throw CustomServiceError.mnemonicNotFound
}
// Normalize empty strings to nil - empty passphrase should be treated as no passphrase
let passphraseRaw = try Keychain.loadString(key: .bip39Passphrase(index: walletIndex))
var passphrase = passphraseRaw?.isEmpty == true ? nil : passphraseRaw
currentWalletIndex = walletIndex
var config = defaultConfig()
let ldkStoragePath = Env.ldkStorage(walletIndex: walletIndex).path
config.storageDirPath = ldkStoragePath
config.network = Env.network
Logger.debug("Using LDK storage path: \(ldkStoragePath)")
let trustedPeersIds = Env.trustedLnPeers.map(\.nodeId)
config.trustedPeers0conf = trustedPeersIds
config.anchorChannelsConfig = .init(
trustedPeersNoReserve: trustedPeersIds,
perChannelReserveSats: 1
)
config.includeUntrustedPendingInSpendable = true
let (selectedAddressType, monitoredTypes) = Self.addressTypeStateFromUserDefaults()
config.addressType = selectedAddressType
config.addressTypesToMonitor = monitoredTypes.filter { $0 != selectedAddressType }
let builder = Builder.fromConfig(config: config)
builder.setCustomLogger(logWriter: LdkLogWriter())
let resolvedElectrumServerUrl = electrumServerUrl ?? Env.electrumServerUrl
let electrumConfig = ElectrumSyncConfig(
backgroundSyncConfig: .init(
onchainWalletSyncIntervalSecs: Env.walletSyncIntervalSecs,
lightningWalletSyncIntervalSecs: Env.walletSyncIntervalSecs,
feeRateCacheUpdateIntervalSecs: Env.walletSyncIntervalSecs
)
)
builder.setChainSourceElectrum(serverUrl: resolvedElectrumServerUrl, config: electrumConfig)
// Set pathfinding scores source from external scorer
if let scorerUrl = Env.ldkScorerUrl {
Logger.info("Setting pathfinding scores source from scorer url: \(scorerUrl)")
builder.setPathfindingScoresSource(url: scorerUrl)
}
// Configure gossip source from current settings
configureGossipSource(builder: builder, rgsServerUrl: rgsServerUrl)
Logger.debug("Building node...")
let storeId = try await VssStoreIdProvider.shared.getVssStoreId(walletIndex: walletIndex)
let vssUrl = Env.vssServerUrl
let lnurlAuthServerUrl = Env.lnurlAuthServerUrl
Logger.debug("Building ldk-node with vssUrl: '\(vssUrl)'")
Logger.debug("Building ldk-node with lnurlAuthServerUrl: '\(lnurlAuthServerUrl)'")
if let channelMigration {
builder.setChannelDataMigration(migration: channelMigration)
Logger.info("Applied channel migration: \(channelMigration.channelMonitors.count) monitors", context: "Migration")
}
builder.setEntropyBip39Mnemonic(mnemonic: mnemonic, passphrase: passphrase)
try await ServiceQueue.background(.ldk) {
do {
if !lnurlAuthServerUrl.isEmpty {
self.node = try builder.buildWithVssStore(
vssUrl: vssUrl,
storeId: storeId,
lnurlAuthServerUrl: lnurlAuthServerUrl,
fixedHeaders: [:]
)
} else {
self.node = try builder.buildWithVssStoreAndFixedHeaders(
vssUrl: vssUrl,
storeId: storeId,
fixedHeaders: [:]
)
}
} catch let error as BuildError {
guard case .ReadFailed = error, !Self.staleMonitorRecoveryAttempted else {
throw error
}
// Build failed with ReadFailed — likely a stale ChannelMonitor (DangerousValue).
// Retry once with accept_stale_channel_monitors to recover.
Logger.warn(
"Build failed with ReadFailed. Retrying with accept_stale_channel_monitors for one-time recovery.",
context: "Recovery"
)
Self.staleMonitorRecoveryAttempted = true
builder.setAcceptStaleChannelMonitors(accept: true)
if !lnurlAuthServerUrl.isEmpty {
self.node = try builder.buildWithVssStore(
vssUrl: vssUrl,
storeId: storeId,
lnurlAuthServerUrl: lnurlAuthServerUrl,
fixedHeaders: [:]
)
} else {
self.node = try builder.buildWithVssStoreAndFixedHeaders(
vssUrl: vssUrl,
storeId: storeId,
fixedHeaders: [:]
)
}
Logger.info("Stale monitor recovery: build succeeded with accept_stale", context: "Recovery")
}
}
// Mark recovery as attempted after any successful build (whether recovery was needed or not).
// This ensures unaffected users never trigger the retry path on future startups.
if !Self.staleMonitorRecoveryAttempted {
Self.staleMonitorRecoveryAttempted = true
}
Logger.info("LDK node setup")
// Clear memory
mnemonic = ""
passphrase = nil
}
func restart(electrumServerUrl: String? = nil, rgsServerUrl: String? = nil) async throws {
Logger.info("Restarting node with current configuration")
// Stop the current node if it exists, ignore errors if already stopped
if node != nil {
do {
try await stop()
} catch {
Logger.debug("Node was already stopped or failed to stop: \(error)")
// Clear the node reference anyway
node = nil
try? StateLocker.unlock(.lightning)
}
}
// Restart the node with the current configuration
do {
try await setup(walletIndex: currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl)
try await start()
Logger.info("Node restarted successfully")
} catch {
Logger.warn("Failed ldk-node config change, attempting recovery…")
// Attempt to restart with previous config
// If recovery fails, log it but still throw the original error
do {
try await restartWithPreviousConfig()
} catch {
Logger.error("Recovery attempt also failed: \(error)")
}
// Always re-throw the original error that caused the restart failure
throw error
}
}
/// Restarts the node with the previous stored configuration (recovery method)
/// This is called when a config change fails to restore the node to a working state
private func restartWithPreviousConfig() async throws {
Logger.debug("Stopping node for recovery attempt")
// Stop the current node if it exists
if node != nil {
do {
try await stop()
} catch {
Logger.error("Failed to stop node during recovery: \(error)")
node = nil
try? StateLocker.unlock(.lightning)
}
}
Logger.debug("Starting node with previous config for recovery")
do {
// Restart with nil URLs to use stored/default configuration
try await setup(walletIndex: currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil)
try await start()
Logger.debug("Successfully started node with previous config")
} catch {
Logger.error("Failed starting node with previous config: \(error)")
throw error
}
}
/// Pass onEvent when being used in the background to listen for payments, channels, closes, etc
/// - Parameter onEvent: Triggered on any LDK node event
func start(onEvent: ((Event) -> Void)? = nil) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
if let onEvent {
storedEventCallback = onEvent
}
listenForEvents(onEvent: storedEventCallback)
Logger.debug("Starting node...")
try await ServiceQueue.background(.ldk) {
try node.start()
}
await refreshChannelCache()
await refreshCache()
Logger.info("Node started")
}
private func refreshChannelCache() async {
guard let node else { return }
let channels = try? await ServiceQueue.background(.ldk) {
node.listChannels()
}
await MainActor.run {
let newChannels = Dictionary(uniqueKeysWithValues: (channels ?? []).map { ($0.channelId.description, $0) })
for (key, value) in newChannels {
channelCache[key] = value
}
}
}
func stop(clearEventCallback: Bool = false) async throws {
defer {
// Always try to unlock, even if stopping fails
try? StateLocker.unlock(.lightning)
}
guard let node else {
Logger.warn("Node not started, nothing to stop")
return
}
Logger.debug("Stopping node...")
try await ServiceQueue.background(.ldk) {
try node.stop()
}
self.node = nil
if clearEventCallback {
storedEventCallback = nil
}
await MainActor.run {
channelCache.removeAll()
}
Logger.info("Node stopped")
}
func wipeStorage(walletIndex: Int) async throws {
guard node == nil else {
throw AppError(serviceError: .nodeNotSetup)
}
let directory = Env.ldkStorage(walletIndex: walletIndex)
guard FileManager.default.fileExists(atPath: directory.path) else {
Logger.warn("No directory found to wipe: \(directory.path)")
return
}
Logger.warn("Wiping on lighting wallet...")
try FileManager.default.removeItem(at: directory)
await MainActor.run {
clearCache()
channelCache.removeAll()
}
Logger.info("Lightning wallet wiped")
}
func deleteNetworkGraph() async throws {
let graphPath = Env.ldkStorage(walletIndex: currentWalletIndex).appendingPathComponent("network_graph_cache")
guard FileManager.default.fileExists(atPath: graphPath.path) else {
Logger.warn("Network graph cache not found at: \(graphPath.path)")
return
}
try FileManager.default.removeItem(at: graphPath)
Logger.info("Deleted network graph cache at: \(graphPath.path)")
}
func connectToTrustedPeers(remotePeers: [LnPeer]? = nil) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
let peers: [LnPeer]
let usingRemotePeers: Bool
if let remotePeers, !remotePeers.isEmpty {
Logger.info("Using \(remotePeers.count) trusted peers from Blocktank API")
peers = remotePeers
usingRemotePeers = true
} else {
Logger.warn("No remote peers available, falling back to preconfigured env peers")
peers = Env.trustedLnPeers
usingRemotePeers = false
}
try await ServiceQueue.background(.ldk) {
for peer in peers {
do {
try node.connect(nodeId: peer.nodeId, address: peer.address, persist: true)
Logger.info("Connected to trusted peer: \(peer.nodeId)")
} catch {
Logger.error(error, context: "Peer: \(peer.nodeId)")
}
}
if usingRemotePeers {
self.verifyTrustedPeersOrFallback(node: node, trustedPeers: peers)
}
}
}
private func verifyTrustedPeersOrFallback(node: Node, trustedPeers: [LnPeer]) {
let connectedPeerIds = Set(node.listPeers().filter(\.isConnected).map(\.nodeId))
let trustedConnected = trustedPeers.filter { connectedPeerIds.contains($0.nodeId) }.count
let trustedPeerIds = Set(trustedPeers.map(\.nodeId))
if trustedConnected == 0, !trustedPeers.isEmpty {
let fallbackPeers = Env.trustedLnPeers.filter { !trustedPeerIds.contains($0.nodeId) }
if fallbackPeers.isEmpty {
Logger.warn("No trusted peers connected. All preconfigured env peers overlap with API peers (not retrying with stale addresses).")
} else {
Logger.warn("No trusted peers connected, trying \(fallbackPeers.count) preconfigured env peer(s) not in API list")
for peer in fallbackPeers {
do {
try node.connect(nodeId: peer.nodeId, address: peer.address, persist: true)
Logger.info("Connected to fallback peer: \(peer.nodeId)")
} catch {
Logger.error(error, context: "Fallback peer: \(peer.nodeId)")
}
}
}
} else {
Logger.info("Connected to \(trustedConnected)/\(trustedPeers.count) trusted peers")
}
}
func connectPeer(peer: LnPeer, persist: Bool = true) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
do {
try await ServiceQueue.background(.ldk) {
try node.connect(nodeId: peer.nodeId, address: peer.address, persist: persist)
}
Logger.info("Connected to peer: \(peer.nodeId)@\(peer.address)")
} catch {
Logger.error(error, context: "Failed to connect peer: \(peer.nodeId)@\(peer.address)")
throw error
}
}
/// Temp fix for regtest where nodes might not agree on current fee rates
private func setMaxDustHtlcExposureForCurrentChannels() throws {
guard Env.network == .regtest else {
Logger.debug("Not updating channel config for non-regtest network")
return
}
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
for channel in node.listChannels() {
var config = channel.config
config.maxDustHtlcExposure = .fixedLimit(limitMsat: 999_999 * 1000)
try? node.updateChannelConfig(userChannelId: channel.userChannelId, counterpartyNodeId: channel.counterpartyNodeId, channelConfig: config)
Logger.info("Updated channel config for: \(channel.userChannelId)")
}
}
func sync() async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
Logger.debug("Syncing LDK...")
try await ServiceQueue.background(.ldk) {
try node.syncWallets()
// try? self.setMaxDustHtlcExposureForCurrentChannels()
}
Logger.info("LDK synced")
await refreshChannelCache()
await refreshCache()
// Emit state change with sync timestamp from node status
let nodeStatus = node.status()
if let latestSyncTimestamp = nodeStatus.latestLightningWalletSyncTimestamp {
let syncTimestamp = UInt64(latestSyncTimestamp)
syncStatusChangedSubject.send(syncTimestamp)
} else {
let syncTimestamp = UInt64(Date().timeIntervalSince1970)
syncStatusChangedSubject.send(syncTimestamp)
}
}
func newAddress() async throws -> String {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
return try await ServiceQueue.background(.ldk) {
try node.onchainPayment().newAddress()
}
}
func newAddressForType(_ addressType: LDKNode.AddressType) async throws -> String {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
return try await ServiceQueue.background(.ldk) {
try node.onchainPayment().newAddressForType(addressType: addressType)
}
}
func receive(amountSats: UInt64? = nil, description: String, expirySecs: UInt32 = 3600) async throws -> String {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
let bolt11 = try await ServiceQueue.background(.ldk) {
if let amountSats {
try node
.bolt11Payment()
.receive(
amountMsat: amountSats * 1000,
description: Bolt11InvoiceDescription.direct(description: description),
expirySecs: expirySecs
)
} else {
try node
.bolt11Payment()
.receiveVariableAmount(
description: Bolt11InvoiceDescription.direct(description: description),
expirySecs: expirySecs
)
}
}
return bolt11.description
}
/// Checks if we have the correct outbound capacity to send the amount
/// - Parameter amountSats: Amount to send in satoshis
/// - Returns: True if we can send the amount
/// Note: Uses cached channels for fast, non-blocking checks
@MainActor
func canSend(amountSats: UInt64) -> Bool {
guard let channels else {
return false
}
let usableChannels = channels.filter(\.isUsable)
guard !usableChannels.isEmpty else {
return false
}
let totalNextOutboundHtlcLimitSats = usableChannels
.map(\.nextOutboundHtlcLimitMsat)
.reduce(0, +) / 1000
guard totalNextOutboundHtlcLimitSats > amountSats else {
Logger.warn("canSend: insufficient capacity: \(totalNextOutboundHtlcLimitSats) < \(amountSats)", context: "LightningService")
return false
}
return true
}
private static func convertVByteToKwu(satsPerVByte: UInt32) -> FeeRate {
// 1 vbyte = 4 weight units, so 1 sats/vbyte = 250 sats/kwu
let satPerKwu = UInt64(satsPerVByte * 250)
// Ensure we're above the minimum relay fee
return .fromSatPerKwu(satKwu: max(satPerKwu, 253)) // FEERATE_FLOOR_SATS_PER_KW is 253 in LDK
}
func send(
address: String,
sats: UInt64,
satsPerVbyte: UInt32,
utxosToSpend: [SpendableUtxo]? = nil,
isMaxAmount: Bool = false
) async throws -> Txid {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
Logger.info("Sending \(sats) sats to \(address) with fee rate \(satsPerVbyte) sats/vbyte (isMaxAmount: \(isMaxAmount))")
do {
return try await ServiceQueue.background(.ldk) {
if isMaxAmount {
// For max amount sends, use sendAllToAddress to send all available funds
try node.onchainPayment().sendAllToAddress(
address: address,
retainReserve: true,
feeRate: Self.convertVByteToKwu(satsPerVByte: satsPerVbyte)
)
} else {
// For normal sends, use sendToAddress with specific amount
try node.onchainPayment().sendToAddress(
address: address,
amountSats: sats,
feeRate: Self.convertVByteToKwu(satsPerVByte: satsPerVbyte),
utxosToSpend: utxosToSpend
)
}
}
} catch {
dumpLdkLogs()
throw error
}
}
func send(bolt11: String, sats: UInt64? = nil, params: RouteParametersConfig? = nil) async throws -> PaymentHash {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
Logger.info("Paying bolt11: \(bolt11)")
do {
return try await ServiceQueue.background(.ldk) {
if let sats {
try node.bolt11Payment().sendUsingAmount(
invoice: .fromStr(invoiceStr: bolt11), amountMsat: sats * 1000, routeParameters: params
)
} else {
try node.bolt11Payment().send(invoice: .fromStr(invoiceStr: bolt11), routeParameters: params)
}
}
} catch {
dumpLdkLogs()
dumpNetworkGraphInfo(bolt11: bolt11)
throw error
}
}
func closeChannel(userChannelId: ChannelId, counterpartyNodeId: PublicKey, force: Bool = false, forceCloseReason: String? = nil) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotStarted)
}
return try await ServiceQueue.background(.ldk) {
Logger.debug("Initiating channel close (force=\(force)): userChannelId=\(userChannelId)", context: "LightningService")
if force {
try node.forceCloseChannel(
userChannelId: userChannelId,
counterpartyNodeId: counterpartyNodeId,
reason: forceCloseReason ?? ""
)
} else {
try node.closeChannel(
userChannelId: userChannelId,
counterpartyNodeId: counterpartyNodeId
)
}
}
}
func closeChannel(_ channel: ChannelDetails, force: Bool = false, forceCloseReason: String? = nil) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotStarted)
}
Logger.debug("closeChannel called to channel=\(channel), force=\(force)", context: "LightningService")
// Prevent force closing channels with trusted peers (LSP nodes)
if force {
let trustedPeerIds = Set(getLspPeerNodeIds())
if trustedPeerIds.contains(channel.counterpartyNodeId.description) {
throw AppError(
message: "Cannot force close channel with trusted peer",
debugMessage: "Force close is disabled for Blocktank LSP channels. Please use cooperative close instead."
)
}
}
return try await closeChannel(
userChannelId: channel.userChannelId,
counterpartyNodeId: channel.counterpartyNodeId,
force: force,
forceCloseReason: forceCloseReason
)
}
func disconnectPeer(peer: PeerDetails) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
let uri = "\(peer.nodeId)@\(peer.address)"
Logger.debug("Disconnecting peer: \(uri)")
do {
try await ServiceQueue.background(.ldk) {
try node.disconnect(nodeId: peer.nodeId)
}
Logger.info("Peer disconnected: \(uri)")
} catch {
Logger.warn("Peer disconnect error: \(uri)")
throw error
}
}
func sign(message: String) async throws -> String {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
guard let msg = message.data(using: .utf8) else {
throw AppError(serviceError: .invalidNodeSigningMessage)
}
return try await ServiceQueue.background(.ldk) {
node.signMessage(msg: [UInt8](msg))
}
}
func openChannel(peer: LnPeer, channelAmountSats: UInt64, pushToCounterpartySats: UInt64? = nil, channelConfig: ChannelConfig? = nil) async throws
-> UserChannelId
{
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
return try await ServiceQueue.background(.ldk) {
try node.openChannel(
nodeId: peer.nodeId,
address: peer.address,
channelAmountSats: channelAmountSats,
pushToCounterpartyMsat: pushToCounterpartySats == nil ? nil : pushToCounterpartySats! * 1000,
channelConfig: channelConfig
)
}
}
func dumpLdkLogs() {
let logFilePath = Logger.sessionLogFile
let fileURL = URL(fileURLWithPath: logFilePath)
do {
let text = try String(contentsOf: fileURL, encoding: .utf8)
let lines = text.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
print("*****LDK-NODE LOG******")
for line in lines.suffix(20) {
print(line)
}
} catch {
Logger.error(error, context: "failed to load ldk log file: \(logFilePath)")
}
}
func dumpNetworkGraphInfo(bolt11: String) {
guard let node else {
Logger.error("Node not available for network graph dump", context: "LightningService")
return
}
let nodeIdPreviewLength = 20
var sb = ""
sb += "\n\n=== NETWORK GRAPH DUMP ===\n"
// 1. Invoice Info
do {
let invoice = try Bolt11Invoice.fromStr(invoiceStr: bolt11)
sb += "\nInvoice Info:\n"
sb += " - Payment Hash: \(invoice.paymentHash())\n"
sb += " - Invoice: \(bolt11)\n"
} catch {
sb += "\nFailed to parse bolt11 invoice: \(error)\n"
}
// 2. Our Node Info
sb += "\nOur Node Info:\n"
sb += " - Node ID: \(node.nodeId())\n"
// 3. Our Channels
sb += "\nOur Channels:\n"
let channels = node.listChannels()
sb += " Total channels: \(channels.count)\n"
var totalOutboundMsat: UInt64 = 0
var totalInboundMsat: UInt64 = 0
var usableChannels = 0
var announcedChannels = 0
for (index, channel) in channels.enumerated() {
totalOutboundMsat += channel.outboundCapacityMsat
totalInboundMsat += channel.inboundCapacityMsat
if channel.isUsable { usableChannels += 1 }
if channel.isAnnounced { announcedChannels += 1 }
sb += " Channel \(index + 1):\n"
sb += " - Channel ID: \(channel.channelId)\n"
sb += " - Counterparty: \(channel.counterpartyNodeId)\n"
sb += " - Ready: \(channel.isChannelReady), Usable: \(channel.isUsable), Announced: \(channel.isAnnounced)\n"
sb += " - Outbound: \(channel.outboundCapacityMsat) msat, Inbound: \(channel.inboundCapacityMsat) msat\n"
}
sb += "\n Channel Summary:\n"
sb += " - Usable channels: \(usableChannels)/\(channels.count)\n"
sb += " - Announced channels: \(announcedChannels)/\(channels.count)\n"
sb += " - Total Outbound: \(totalOutboundMsat) msat\n"
sb += " - Total Inbound: \(totalInboundMsat) msat\n"
// 4. Our Peers
sb += "\nOur Peers:\n"
let peers = node.listPeers()
sb += " Total peers: \(peers.count)\n"
for (index, peer) in peers.enumerated() {
let nodeIdPreview = String(peer.nodeId.prefix(nodeIdPreviewLength))
sb += " Peer \(index + 1): \(nodeIdPreview)... @ \(peer.address)\n"
}
// 5. RGS Configuration
sb += "\nRGS Configuration:\n"
sb += " - RGS Server URL: \(Env.ldkRgsServerUrl ?? "Not configured")\n"
let nodeStatus = node.status()
if let rgsTimestamp = nodeStatus.latestRgsSnapshotTimestamp {
let date = Date(timeIntervalSince1970: TimeInterval(rgsTimestamp))
let timeAgo = Date().timeIntervalSince(date)
let hoursAgo = Int(timeAgo / 3600)
let minutesAgo = Int((timeAgo.truncatingRemainder(dividingBy: 3600)) / 60)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(abbreviation: "UTC")
sb += " - Last RGS Snapshot: \(formatter.string(from: date))\n"
if hoursAgo > 0 {
sb += " - Time since update: \(hoursAgo)h \(minutesAgo)m ago\n"
} else {
sb += " - Time since update: \(minutesAgo)m ago\n"
}
sb += " - Timestamp: \(rgsTimestamp)\n"
} else {
sb += " - Last RGS Snapshot: Never synced\n"
sb += " - WARNING: Network graph may be empty or stale!\n"
}
// 6. Network Graph Data
sb += "\nRGS Network Graph Data:\n"
let networkGraph = node.networkGraph()
let allNodes = networkGraph.listNodes()
let allChannels = networkGraph.listChannels()
sb += " Total nodes: \(allNodes.count)\n"
sb += " Total channels: \(allChannels.count)\n"
// Check for trusted peers in graph
sb += "\n Checking for trusted peers in network graph:\n"
let trustedPeers = Env.trustedLnPeers
var foundTrustedNodes = 0
let allNodeStrings = allNodes.map(\.description)
for peer in trustedPeers {
let nodeId = peer.nodeId
if allNodeStrings.contains(nodeId) {
foundTrustedNodes += 1
let nodeIdPreview = String(nodeId.prefix(nodeIdPreviewLength))
sb += " OK: \(nodeIdPreview)... found in graph\n"
} else {
let nodeIdPreview = String(nodeId.prefix(nodeIdPreviewLength))
sb += " MISSING: \(nodeIdPreview)... NOT in graph\n"
}
}
sb += " Summary: \(foundTrustedNodes)/\(trustedPeers.count) trusted peers found in graph\n"
// Show first 10 nodes
let nodesToShow = min(10, allNodes.count)
sb += "\n First \(nodesToShow) nodes:\n"
for (index, nodeId) in allNodes.prefix(nodesToShow).enumerated() {
sb += " \(index + 1). \(nodeId.description)\n"
}
if allNodes.count > nodesToShow {
sb += " ... and \(allNodes.count - nodesToShow) more nodes\n"
}
sb += "\n=== END NETWORK GRAPH DUMP ===\n"
Logger.info(sb, context: "LightningService")
}
func logNetworkGraphInfo() async throws -> String {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
let nodeStatus = node.status()
let networkGraph = node.networkGraph()
let allNodes = networkGraph.listNodes()
let lastRgsSync = nodeStatus.latestRgsSnapshotTimestamp
var lastRgsSyncString = "Never"
if let lastRgsSync {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
lastRgsSyncString = dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(lastRgsSync)))
}
return "Nodes: \(allNodes.count), Last Synced: \(lastRgsSyncString)"
}
// MARK: - Configuration Helpers
private func configureGossipSource(builder: Builder, rgsServerUrl: String?) {
let rgsUrl = rgsServerUrl ?? Env.ldkRgsServerUrl
if let rgsUrl, !rgsUrl.isEmpty {
Logger.info("Using gossip source rgs url: \(rgsUrl)")
builder.setGossipSourceRgs(rgsServerUrl: rgsUrl)
} else {
Logger.info("Using gossip source p2p")
builder.setGossipSourceP2p()
}
}
}
// MARK: UI Helpers (Published via WalletViewModel)
extension LightningService {
var nodeId: String? { node?.nodeId() }
// Use cached values to avoid blocking LDK calls on main thread
@MainActor var balances: BalanceDetails? { cachedBalances }
@MainActor var status: NodeStatus? { cachedStatus }
@MainActor var peers: [PeerDetails]? { cachedPeers }
@MainActor var channels: [ChannelDetails]? { cachedChannels }
var payments: [PaymentDetails]? { node?.listPayments() }
/// Refresh all cached values asynchronously
/// Fetches from LDK on background queue, updates cache on main actor
func refreshCache() async {
// Skip if node isn't set up yet - don't block on the LDK queue
guard node != nil else { return }
do {
// Fetch all values in a single background queue call
let (newStatus, newBalances, newPeers, newChannels) = try await ServiceQueue.background(.ldk) { [self] in
(
node?.status(),
node?.listBalances(),
node?.listPeers(),
node?.listChannels()
)
}
// Update cache on main actor
await MainActor.run {
cachedStatus = newStatus
cachedBalances = newBalances
cachedPeers = newPeers
cachedChannels = newChannels
}
} catch {
Logger.error("Failed to refresh cache: \(error)", context: "LightningService")
}
}
/// Clear cached values - only call when wiping storage or resetting the wallet.
@MainActor
func clearCache() {
cachedStatus = nil
cachedBalances = nil
cachedPeers = nil
cachedChannels = nil
}
/// Get balance for a specific address in satoshis
/// - Parameter address: The Bitcoin address to check
/// - Returns: The current balance in satoshis
/// - Throws: AppError if node is not setup
func getAddressBalance(address: String) async throws -> UInt64 {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
return try await ServiceQueue.background(.ldk) {
try node.getAddressBalance(addressStr: address)
}
}
func getBalanceForAddressType(_ addressType: LDKNode.AddressType) async throws -> AddressTypeBalance {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
return try await ServiceQueue.background(.ldk) {
try node.getBalanceForAddressType(addressType: addressType)
}
}
func addAddressTypeToMonitor(_ addressType: LDKNode.AddressType) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
guard let mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: currentWalletIndex)) else {
throw CustomServiceError.mnemonicNotFound
}
let passphraseRaw = try? Keychain.loadString(key: .bip39Passphrase(index: currentWalletIndex))
let passphrase = passphraseRaw?.isEmpty == true ? nil : passphraseRaw
try await ServiceQueue.background(.ldk) {
try node.addAddressTypeToMonitorWithMnemonic(addressType: addressType, mnemonic: mnemonic, passphrase: passphrase)
}
}
func removeAddressTypeFromMonitor(_ addressType: LDKNode.AddressType) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}