-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLightningRepoTest.kt
More file actions
1164 lines (977 loc) · 43.2 KB
/
LightningRepoTest.kt
File metadata and controls
1164 lines (977 loc) · 43.2 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 app.cash.turbine.test
import com.google.firebase.messaging.FirebaseMessaging
import com.synonym.bitkitcore.AddressType
import com.synonym.bitkitcore.FeeRates
import com.synonym.bitkitcore.IBtInfo
import com.synonym.bitkitcore.ILspNode
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.lightningdevkit.ldknode.AddressTypeBalance
import org.lightningdevkit.ldknode.BalanceDetails
import org.lightningdevkit.ldknode.ChannelDetails
import org.lightningdevkit.ldknode.NodeStatus
import org.lightningdevkit.ldknode.PaymentDetails
import org.lightningdevkit.ldknode.PeerDetails
import org.lightningdevkit.ldknode.SpendableUtxo
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argThat
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.eq
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.isNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyBlocking
import org.mockito.kotlin.whenever
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.ext.createChannelDetails
import to.bitkit.ext.of
import to.bitkit.models.CoinSelectionPreference
import to.bitkit.models.NodeLifecycleState
import to.bitkit.models.OpenChannelResult
import to.bitkit.models.TransactionSpeed
import to.bitkit.services.BlocktankService
import to.bitkit.services.CoreService
import to.bitkit.services.LightningService
import to.bitkit.services.LnurlService
import to.bitkit.services.LspNotificationsService
import to.bitkit.test.BaseUnitTest
import to.bitkit.utils.UrlValidator
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
@Suppress("LargeClass")
class LightningRepoTest : BaseUnitTest() {
private lateinit var sut: LightningRepo
private val lightningService = mock<LightningService>()
private val settingsStore = mock<SettingsStore>()
private val coreService = mock<CoreService>()
private val lspNotificationsService = mock<LspNotificationsService>()
private val firebaseMessaging = mock<FirebaseMessaging>()
private val keychain = mock<Keychain>()
private val cacheStore = mock<CacheStore>()
private val preActivityMetadataRepo = mock<PreActivityMetadataRepo>()
private val lnurlService = mock<LnurlService>()
private val connectivityRepo = mock<ConnectivityRepo>()
private val vssBackupClientLdk = mock<VssBackupClientLdk>()
private val urlValidator = UrlValidator { Result.success(Unit) }
@Before
fun setUp() = runBlocking {
whenever(lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(Unit)
whenever(lightningService.start(anyOrNull(), any())).thenReturn(Unit)
whenever(coreService.isGeoBlocked()).thenReturn(false)
whenever(connectivityRepo.isOnline).thenReturn(MutableStateFlow(ConnectivityState.CONNECTED))
whenever(settingsStore.data).thenReturn(flowOf(SettingsData()))
whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(true)
sut = LightningRepo(
bgDispatcher = testDispatcher,
lightningService = lightningService,
settingsStore = settingsStore,
coreService = coreService,
lspNotificationsService = lspNotificationsService,
firebaseMessaging = firebaseMessaging,
keychain = keychain,
lnurlService = lnurlService,
cacheStore = cacheStore,
preActivityMetadataRepo = preActivityMetadataRepo,
connectivityRepo = connectivityRepo,
vssBackupClientLdk = vssBackupClientLdk,
urlValidator = urlValidator,
)
}
private suspend fun startNodeForTesting() {
sut.setInitNodeLifecycleState()
whenever(lightningService.node).thenReturn(mock())
whenever(lightningService.sync()).thenReturn(Unit)
val blocktank = mock<BlocktankService>()
whenever(coreService.blocktank).thenReturn(blocktank)
whenever(blocktank.info(any())).thenReturn(null)
val result = sut.start()
assertTrue(result.isSuccess)
// Simulate successful sync to set isSyncHealthy = true
sut.sync()
}
@Test
fun `start should transition through correct states`() = test {
sut.setInitNodeLifecycleState()
whenever(lightningService.node).thenReturn(mock())
val blocktank = mock<BlocktankService>()
whenever(coreService.blocktank).thenReturn(blocktank)
whenever(blocktank.info(any())).thenReturn(null)
sut.lightningState.test {
assertEquals(NodeLifecycleState.Initializing, awaitItem().nodeLifecycleState)
sut.start()
assertEquals(NodeLifecycleState.Starting, awaitItem().nodeLifecycleState)
assertEquals(NodeLifecycleState.Running, awaitItem().nodeLifecycleState)
cancelAndIgnoreRemainingEvents()
}
}
@Test
fun `stop should transition to stopped state`() = test {
startNodeForTesting()
sut.lightningState.test {
// Verify initial state is Running (from startNodeForTesting)
assertEquals(NodeLifecycleState.Running, awaitItem().nodeLifecycleState)
sut.stop()
assertEquals(NodeLifecycleState.Stopping, awaitItem().nodeLifecycleState)
assertEquals(NodeLifecycleState.Stopped, awaitItem().nodeLifecycleState)
cancelAndIgnoreRemainingEvents()
}
}
@Test
fun `newAddress should fail when node is not running`() = test {
val result = sut.newAddress()
assertTrue(result.isFailure)
}
@Test
fun `newAddress should succeed when node is running`() = test {
startNodeForTesting()
val testAddress = "test_address"
whenever(lightningService.newAddress()).thenReturn(testAddress)
val result = sut.newAddress()
assertTrue(result.isSuccess)
assertEquals(testAddress, result.getOrNull())
}
@Test
fun `createInvoice should fail when node is not running`() = test {
val result = sut.createInvoice(description = "test")
assertTrue(result.isFailure)
}
@Test
fun `createInvoice should succeed when node is running`() = test {
startNodeForTesting()
val testInvoice = "testInvoice"
whenever(
lightningService.receive(
sat = 100uL,
description = "test",
expirySecs = 3600u
)
).thenReturn(testInvoice)
val result = sut.createInvoice(amountSats = 100uL, description = "test", expirySeconds = 3600u)
assertTrue(result.isSuccess)
assertEquals(testInvoice, result.getOrNull())
}
@Test
fun `payInvoice should fail when node is not running`() = test {
val result = sut.payInvoice("bolt11", 1000uL)
assertTrue(result.isFailure)
}
@Test
fun `payInvoice should succeed when node is running and channels are usable`() = test {
startNodeForTesting()
val usableChannel = createChannelDetails().copy(isUsable = true)
whenever(lightningService.channels).thenReturn(listOf(usableChannel))
val testPaymentId = "testPaymentId"
whenever(lightningService.send("bolt11", 1000uL)).thenReturn(testPaymentId)
val result = sut.payInvoice("bolt11", 1000uL)
assertTrue(result.isSuccess)
assertEquals(testPaymentId, result.getOrNull())
}
@Test
fun `payInvoice should proceed after timeout when channels are not usable`() = test {
startNodeForTesting()
val testPaymentId = "testPaymentId"
whenever(lightningService.send("bolt11", 1000uL)).thenReturn(testPaymentId)
// Channels are ready but not usable (peer disconnected)
val readyButNotUsable = createChannelDetails().copy(isChannelReady = true, isUsable = false)
whenever(lightningService.channels).thenReturn(listOf(readyButNotUsable))
// payInvoice should wait, timeout, then still attempt to send
val result = sut.payInvoice("bolt11", 1000uL)
assertTrue(result.isSuccess)
assertEquals(testPaymentId, result.getOrNull())
}
@Test
fun `getPayments should fail when node is not running`() = test {
val result = sut.getPayments()
assertTrue(result.isFailure)
}
@Test
fun `getPayments should succeed when node is running`() = test {
startNodeForTesting()
val testPayments = listOf(mock<PaymentDetails>())
whenever(lightningService.payments).thenReturn(testPayments)
val result = sut.getPayments()
assertTrue(result.isSuccess)
assertEquals(testPayments, result.getOrNull())
}
@Test
fun `openChannel should fail when node is not running`() = test {
val testPeer = PeerDetails.of("nodeId", "host", "9735")
val result = sut.openChannel(testPeer, 100000uL)
assertTrue(result.isFailure)
}
@Test
fun `openChannel should succeed when node is running`() = test {
startNodeForTesting()
val peer = PeerDetails.of("nodeId", "host", "9735")
val userChannelId = "testChannelId"
val channelAmountSats = 100_000uL
whenever(lightningService.openChannel(peer, channelAmountSats, null, null))
.thenReturn(Result.success(OpenChannelResult(userChannelId, peer, channelAmountSats)))
val result = sut.openChannel(peer, channelAmountSats, null)
assertTrue(result.isSuccess)
assertEquals(userChannelId, result.getOrNull()?.userChannelId)
}
@Test
fun `closeChannel should fail when node is not running`() = test {
val result = sut.closeChannel(createChannelDetails())
assertTrue(result.isFailure)
}
@Test
fun `closeChannel should succeed when node is running`() = test {
startNodeForTesting()
whenever(lightningService.closeChannel(any(), any(), anyOrNull())).thenReturn(Unit)
val result = sut.closeChannel(createChannelDetails())
assertTrue(result.isSuccess)
}
@Test
fun `getNodeId should return null when node is not running`() = test {
assertNull(sut.getNodeId())
}
@Test
fun `getNodeId should return value when node is running`() = test {
startNodeForTesting()
val testNodeId = "test_node_id"
whenever(lightningService.nodeId).thenReturn(testNodeId)
assertEquals(testNodeId, sut.getNodeId())
}
@Test
fun `getBalances should return null when node is not running`() = test {
assertNull(sut.getBalances())
}
@Test
fun `canReceive should return false when node is not running`() = test {
assertFalse(sut.canReceive())
}
@Test
fun `canReceive should return false when node is running but cannot receive`() = test {
startNodeForTesting()
whenever(lightningService.canReceive()).thenReturn(false)
assertFalse(sut.canReceive())
}
@Test
fun `canReceive should return true when node can receive`() = test {
startNodeForTesting()
whenever(lightningService.canReceive()).thenReturn(true)
assertTrue(sut.canReceive())
}
@Test
fun `syncState should update state with current values`() = test {
startNodeForTesting()
val testNodeId = "test_node_id"
val testStatus = mock<NodeStatus>()
val testPeers = listOf(mock<PeerDetails>())
val testChannels = listOf(mock<ChannelDetails>())
whenever(lightningService.nodeId).thenReturn(testNodeId)
whenever(lightningService.status).thenReturn(testStatus)
whenever(lightningService.peers).thenReturn(testPeers)
whenever(lightningService.channels).thenReturn(testChannels)
sut.syncState()
assertEquals(testNodeId, sut.lightningState.value.nodeId)
assertEquals(testStatus, sut.lightningState.value.nodeStatus)
assertEquals(testPeers, sut.lightningState.value.peers)
assertEquals(testChannels, sut.lightningState.value.channels)
}
@Test
fun `canSend should return false when node is stopped`() = test {
assertFalse(sut.canSend(1000uL, fallbackToCachedBalance = true))
}
@Test
fun `canSend should return service value when node is running`() = test {
startNodeForTesting()
whenever(lightningService.canSend(any())).thenReturn(true)
assertTrue(sut.canSend(1000uL))
}
@Test
fun `wipeStorage should stop node and call service wipe`() = test {
startNodeForTesting()
whenever(lightningService.stop()).thenReturn(Unit)
val result = sut.wipeStorage(0)
assertTrue(result.isSuccess)
verify(lightningService).stop()
verify(lightningService).wipeStorage(0)
}
@Test
fun `connectToTrustedPeers should fail when node is not running`() = test {
val result = sut.connectToTrustedPeers()
assertTrue(result.isFailure)
}
@Test
fun `connectToTrustedPeers should succeed when node is running`() = test {
startNodeForTesting()
whenever(lightningService.connectToTrustedPeers()).thenReturn(Unit)
val result = sut.connectToTrustedPeers()
assertTrue(result.isSuccess)
}
@Test
fun `disconnectPeer should fail when node is not running`() = test {
val testPeer = PeerDetails.of("nodeId", "host", "9735")
val result = sut.disconnectPeer(testPeer)
assertTrue(result.isFailure)
}
@Test
fun `disconnectPeer should succeed when node is running`() = test {
startNodeForTesting()
val testPeer = PeerDetails.of("nodeId", "host", "9735")
whenever(lightningService.disconnectPeer(any())).thenReturn(Result.success(Unit))
val result = sut.disconnectPeer(testPeer)
assertTrue(result.isSuccess)
}
@Test
fun `sendOnChain should fail when node is not running`() = test {
val result = sut.sendOnChain("address", 1000uL)
assertTrue(result.isFailure)
}
@Test
fun `sendOnChain should fail when sync is unhealthy`() = test {
// Start node but make sync fail (isSyncHealthy = false)
// Mock connectivity as disconnected to prevent retry loop from running indefinitely
whenever(connectivityRepo.isOnline).thenReturn(MutableStateFlow(ConnectivityState.DISCONNECTED))
sut.setInitNodeLifecycleState()
whenever(lightningService.node).thenReturn(mock())
whenever(lightningService.sync()).thenThrow(RuntimeException("Sync failed"))
val blocktank = mock<BlocktankService>()
whenever(coreService.blocktank).thenReturn(blocktank)
whenever(blocktank.info(any())).thenReturn(null)
sut.start()
// Sync failed during start(), so isSyncHealthy should be false
val result = sut.sendOnChain("address", 1000uL)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull() is SyncUnhealthyError)
}
@Test
fun `sendOnChain should cache activity meta data`() = test {
val mockSettingsData = SettingsData(
defaultTransactionSpeed = TransactionSpeed.Fast,
coinSelectAuto = false // Disable auto coin selection to simplify the test
)
whenever(settingsStore.data).thenReturn(flowOf(mockSettingsData))
whenever(preActivityMetadataRepo.addPreActivityMetadata(any())).thenReturn(Result.success(Unit))
whenever(coreService.activity).thenReturn(mock())
whenever(
lightningService.send(
address = any(),
sats = any(),
satsPerVByte = any(),
utxosToSpend = anyOrNull(),
isMaxAmount = any()
)
).thenReturn("testPaymentId")
startNodeForTesting()
// Create a spy to mock the getFeeRateForSpeed method
val spySut = spy(sut)
doReturn(Result.success(10uL)).whenever(spySut).getFeeRateForSpeed(any(), anyOrNull())
val result = spySut.sendOnChain(
address = "test_address",
sats = 1000uL,
speed = TransactionSpeed.Fast,
utxosToSpend = null,
feeRates = null,
isTransfer = true,
channelId = "test_channel_id"
)
// Verify the result is successful
assertTrue(result.isSuccess)
assertEquals("testPaymentId", result.getOrNull())
// Verify pre-activity metadata was saved
verifyBlocking(preActivityMetadataRepo) {
addPreActivityMetadata(any())
}
}
@Test
fun `registerForNotifications should fail when node is not running`() = test {
val result = sut.registerForNotifications()
assertTrue(result.isFailure)
}
@Test
fun `restartWithElectrumServer should setup with new server`() = test {
startNodeForTesting()
val customServerUrl = "ssl://test.example.com:50002"
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
val result = sut.restartWithElectrumServer(customServerUrl)
assertTrue(result.isSuccess)
val inOrder = inOrder(lightningService)
inOrder.verify(lightningService).stop()
inOrder.verify(lightningService).setup(any(), eq(customServerUrl), anyOrNull(), anyOrNull(), anyOrNull())
inOrder.verify(lightningService).start(anyOrNull(), any())
assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}
@Test
fun `restartWithElectrumServer should handle stop failure`() = test {
startNodeForTesting()
val customServerUrl = "ssl://test.example.com:50002"
whenever(lightningService.stop()).thenThrow(RuntimeException("Stop failed"))
val result = sut.restartWithElectrumServer(customServerUrl)
assertTrue(result.isFailure)
}
@Test
fun `restartWithRgsServer should setup with new rgs server`() = test {
startNodeForTesting()
val customRgsUrl = "https://rgs.example.com/snapshot"
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
val result = sut.restartWithRgsServer(customRgsUrl)
assertTrue(result.isSuccess)
val inOrder = inOrder(lightningService)
inOrder.verify(lightningService).stop()
inOrder.verify(lightningService).setup(any(), isNull(), eq(customRgsUrl), anyOrNull(), anyOrNull())
inOrder.verify(lightningService).start(anyOrNull(), any())
assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}
@Test
fun `restartWithRgsServer should handle stop failure`() = test {
startNodeForTesting()
whenever(lightningService.stop()).thenThrow(RuntimeException("Stop failed"))
val result = sut.restartWithRgsServer("https://rgs.example.com/snapshot")
assertTrue(result.isFailure)
}
@Test
fun `restartWithRgsServer should handle start failure and recover`() = test {
startNodeForTesting()
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
whenever(lightningService.setup(any(), isNull(), eq("https://bad.rgs/snapshot"), anyOrNull(), anyOrNull()))
.thenThrow(RuntimeException("Failed to start node"))
val result = sut.restartWithRgsServer("https://bad.rgs/snapshot")
assertTrue(result.isFailure)
}
@Test
fun `restartWithRgsServer should fail when url is unreachable`() = test {
val failingValidator = UrlValidator { Result.failure(Exception("DNS resolution failed")) }
val sutWithFailingValidator = LightningRepo(
bgDispatcher = testDispatcher,
lightningService = lightningService,
settingsStore = settingsStore,
coreService = coreService,
lspNotificationsService = lspNotificationsService,
firebaseMessaging = firebaseMessaging,
keychain = keychain,
lnurlService = lnurlService,
cacheStore = cacheStore,
preActivityMetadataRepo = preActivityMetadataRepo,
connectivityRepo = connectivityRepo,
vssBackupClientLdk = vssBackupClientLdk,
urlValidator = failingValidator,
)
sutWithFailingValidator.setInitNodeLifecycleState()
whenever(lightningService.node).thenReturn(mock())
whenever(lightningService.sync()).thenReturn(Unit)
val blocktank = mock<BlocktankService>()
whenever(coreService.blocktank).thenReturn(blocktank)
whenever(blocktank.info(any())).thenReturn(null)
sutWithFailingValidator.start()
val result = sutWithFailingValidator.restartWithRgsServer("https://rapidsync.lightningdevkit/snapshot")
assertTrue(result.isFailure)
assertEquals("DNS resolution failed", result.exceptionOrNull()?.message)
}
@Test
fun `getFeeRateForSpeed should use provided feeRates`() = test {
val mockFeeRates = mock<FeeRates>()
whenever(mockFeeRates.mid).thenReturn(20u)
val result = sut.getFeeRateForSpeed(TransactionSpeed.Medium, mockFeeRates)
assertTrue(result.isSuccess)
assertEquals(20uL, result.getOrNull())
}
@Test
fun `getFeeRateForSpeed should fetch from blocktank when feeRates is null`() = test {
val mockFeeRates = mock<FeeRates>()
whenever(mockFeeRates.fast).thenReturn(30u)
val blocktank = mock<BlocktankService>()
whenever(blocktank.getFees()).thenReturn(Result.success(mockFeeRates))
whenever(coreService.blocktank).thenReturn(blocktank)
val result = sut.getFeeRateForSpeed(TransactionSpeed.Fast, null)
assertTrue(result.isSuccess)
assertEquals(30uL, result.getOrNull())
}
@Test
fun `determineUtxosToSpend should return null when coinSelectAuto is false`() = test {
val mockSettingsData = SettingsData(coinSelectAuto = false)
whenever(settingsStore.data).thenReturn(flowOf(mockSettingsData))
val result = sut.determineUtxosToSpend(1000uL, 10u)
assertNull(result)
}
@Test
fun `determineUtxosToSpend should return all UTXOs when preference is Consolidate`() = test {
val mockSettingsData = SettingsData(
coinSelectAuto = true,
coinSelectPreference = CoinSelectionPreference.Consolidate
)
whenever(settingsStore.data).thenReturn(flowOf(mockSettingsData))
val mockUtxos = listOf(
mock<SpendableUtxo>(),
mock<SpendableUtxo>(),
mock<SpendableUtxo>()
)
whenever(lightningService.listSpendableOutputs()).thenReturn(Result.success(mockUtxos))
val result = sut.determineUtxosToSpend(1000uL, 10u)
assertNotNull(result)
assertEquals(3, result.size)
assertEquals(mockUtxos, result)
}
@Test
fun `estimateRoutingFees should fail when node is not running`() = test {
val result = sut.estimateRoutingFees("lnbc1u1p0abcde")
assertTrue(result.isFailure)
}
@Test
fun `estimateRoutingFees should succeed when node is running`() = test {
startNodeForTesting()
val testBolt11 = "lnbc1u1p0abcde"
val expectedFeesSats = 50uL
whenever(lightningService.estimateRoutingFees(testBolt11))
.thenReturn(Result.success(expectedFeesSats))
val result = sut.estimateRoutingFees(testBolt11)
assertTrue(result.isSuccess)
assertEquals(expectedFeesSats, result.getOrNull())
verify(lightningService).estimateRoutingFees(testBolt11)
}
@Test
fun `estimateRoutingFees should handle service failure`() = test {
startNodeForTesting()
val testBolt11 = "lnbc1u1p0abcde"
val serviceError = RuntimeException("Service error")
whenever(lightningService.estimateRoutingFees(testBolt11))
.thenReturn(Result.failure(serviceError))
val result = sut.estimateRoutingFees(testBolt11)
assertTrue(result.isFailure)
assertEquals(serviceError, result.exceptionOrNull())
}
@Test
fun `estimateRoutingFeesForAmount should fail when node is not running`() = test {
val result = sut.estimateRoutingFeesForAmount("lnbc1u1p0abcde", 1000uL)
assertTrue(result.isFailure)
}
@Test
fun `estimateRoutingFeesForAmount should succeed when node is running`() = test {
startNodeForTesting()
val testBolt11 = "lnbc1u1p0abcde"
val testAmount = 1000uL
val expectedFeesSats = 25uL
whenever(lightningService.estimateRoutingFeesForAmount(testBolt11, testAmount))
.thenReturn(Result.success(expectedFeesSats))
val result = sut.estimateRoutingFeesForAmount(testBolt11, testAmount)
assertTrue(result.isSuccess)
assertEquals(expectedFeesSats, result.getOrNull())
verify(lightningService).estimateRoutingFeesForAmount(testBolt11, testAmount)
}
@Test
fun `estimateRoutingFeesForAmount should handle service failure`() = test {
startNodeForTesting()
val testBolt11 = "lnbc1u1p0abcde"
val testAmount = 1000uL
val serviceError = RuntimeException("Service error")
whenever(lightningService.estimateRoutingFeesForAmount(testBolt11, testAmount))
.thenReturn(Result.failure(serviceError))
val result = sut.estimateRoutingFeesForAmount(testBolt11, testAmount)
assertTrue(result.isFailure)
assertEquals(serviceError, result.exceptionOrNull())
}
@Test
fun `start should load trusted peers from blocktank info`() = test {
sut.setInitNodeLifecycleState()
whenever(lightningService.node).thenReturn(null)
val blocktank = mock<BlocktankService>()
whenever(coreService.blocktank).thenReturn(blocktank)
val mockNodes = listOf(
ILspNode(
alias = "LSP1",
pubkey = "node1pubkey",
connectionStrings = listOf("node1pubkey@node1.example.com:9735"),
readonly = null,
),
ILspNode(
alias = "LSP2",
pubkey = "node2pubkey",
connectionStrings = listOf("node2pubkey@node2.example.com:9735"),
readonly = null,
),
)
val mockInfo = mock<IBtInfo> { on { nodes } doReturn mockNodes }
whenever(blocktank.info(refresh = false)).thenReturn(mockInfo)
val result = sut.start()
assertTrue(result.isSuccess)
verify(lightningService).setup(
any(),
anyOrNull(),
anyOrNull(),
argThat { peers ->
peers?.size == 2 &&
peers.any { it.nodeId == "node1pubkey" && it.address == "node1.example.com:9735" } &&
peers.any { it.nodeId == "node2pubkey" && it.address == "node2.example.com:9735" }
},
anyOrNull(),
)
}
@Test
fun `start should pass null trusted peers when blocktank returns null`() = test {
sut.setInitNodeLifecycleState()
whenever(lightningService.node).thenReturn(null)
val blocktank = mock<BlocktankService>()
whenever(coreService.blocktank).thenReturn(blocktank)
whenever(blocktank.info(refresh = false)).thenReturn(null)
whenever(blocktank.info(refresh = true)).thenReturn(null)
val result = sut.start()
assertTrue(result.isSuccess)
verify(lightningService).setup(any(), anyOrNull(), anyOrNull(), isNull(), anyOrNull())
}
@Test
fun `getBalanceForAddressType should succeed when node is running`() = test {
startNodeForTesting()
whenever(lightningService.getBalanceForAddressType(AddressType.P2WPKH))
.thenReturn(AddressTypeBalance(totalSats = 50_000uL, spendableSats = 50_000uL))
val result = sut.getBalanceForAddressType(AddressType.P2WPKH)
assertTrue(result.isSuccess)
assertEquals(50_000uL, result.getOrNull())
}
@Test
fun `getBalanceForAddressType should fail when node is not running`() = test {
val result = sut.getBalanceForAddressType(AddressType.P2WPKH)
assertTrue(result.isFailure)
}
@Test
fun `getChannelFundableBalance should return aggregate spendable when per-type fails`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(SettingsData(selectedAddressType = "nativeSegwit", addressTypesToMonitor = listOf("nativeSegwit")))
)
whenever(lightningService.getBalanceForAddressType(any()))
.thenThrow(UnsupportedOperationException("per-type not supported"))
whenever(lightningService.balances).thenReturn(
BalanceDetails(
totalOnchainBalanceSats = 100_000uL,
spendableOnchainBalanceSats = 80_000uL,
totalAnchorChannelsReserveSats = 0uL,
totalLightningBalanceSats = 0uL,
lightningBalances = emptyList(),
pendingBalancesFromChannelClosures = emptyList(),
),
)
val result = sut.getChannelFundableBalance()
assertEquals(80_000uL, result)
}
@Test
fun `updateAddressType should fail when already in progress`() = test {
startNodeForTesting()
val settingsFlow = MutableSharedFlow<SettingsData>(replay = 1)
whenever(settingsStore.data).thenReturn(settingsFlow)
whenever { settingsStore.update(any()) }.thenReturn(Unit)
val scope = CoroutineScope(testDispatcher)
val job1 = scope.async {
sut.updateAddressType("taproot", listOf("taproot", "nativeSegwit"))
}
testScheduler.advanceUntilIdle()
val job2 = scope.async { sut.updateAddressType("legacy", listOf("legacy")) }
val result2 = job2.await()
settingsFlow.emit(
SettingsData(
selectedAddressType = "nativeSegwit",
addressTypesToMonitor = listOf("nativeSegwit"),
),
)
val result1 = job1.await()
assertTrue(result2.isFailure)
assertTrue(result2.exceptionOrNull()?.message?.contains("already in progress") == true)
assertTrue(result1.isSuccess)
}
@Test
fun `setMonitoring should fail when disabling currently selected type`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(
SettingsData(
selectedAddressType = "taproot",
addressTypesToMonitor = listOf("nativeSegwit", "taproot")
)
)
)
val result = sut.setMonitoring(AddressType.P2TR, enabled = false)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull()?.message?.contains("currently selected") == true)
verify(lightningService, times(0)).removeAddressTypeFromMonitor(any())
}
@Test
fun `setMonitoring should fail when disabling last required native witness`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(
SettingsData(
selectedAddressType = "legacy",
addressTypesToMonitor = listOf("taproot")
)
)
)
whenever(lightningService.getBalanceForAddressType(AddressType.P2TR))
.thenReturn(AddressTypeBalance(totalSats = 0uL, spendableSats = 0uL))
val result = sut.setMonitoring(AddressType.P2TR, enabled = false)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull()?.message?.contains("Native SegWit or Taproot") == true)
verify(lightningService, times(0)).removeAddressTypeFromMonitor(any())
}
@Test
fun `setMonitoring should fail when balance verification fails`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(
SettingsData(
selectedAddressType = "nativeSegwit",
addressTypesToMonitor = listOf("nativeSegwit", "taproot")
)
)
)
whenever(lightningService.getBalanceForAddressType(AddressType.P2TR))
.thenThrow(RuntimeException("balance check failed"))
val result = sut.setMonitoring(AddressType.P2TR, enabled = false)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull()?.message?.contains("verify") == true)
verify(lightningService, times(0)).removeAddressTypeFromMonitor(any())
}
@Test
fun `setMonitoring should fail when disabling with balance greater than zero`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(
SettingsData(
selectedAddressType = "nativeSegwit",
addressTypesToMonitor = listOf("nativeSegwit", "taproot")
)
)
)
whenever(lightningService.getBalanceForAddressType(AddressType.P2TR))
.thenReturn(AddressTypeBalance(totalSats = 1_000uL, spendableSats = 1_000uL))
val result = sut.setMonitoring(AddressType.P2TR, enabled = false)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull()?.message?.contains("has balance") == true)
verify(lightningService, times(0)).removeAddressTypeFromMonitor(any())
}
@Test
fun `setMonitoring should succeed when enabling a type`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(
SettingsData(
selectedAddressType = "nativeSegwit",
addressTypesToMonitor = listOf("nativeSegwit")
)
)
)
whenever { settingsStore.update(any()) }.thenReturn(Unit)
val result = sut.setMonitoring(AddressType.P2TR, enabled = true)
assertTrue(result.isSuccess)
verify(lightningService).addAddressTypeToMonitor(AddressType.P2TR)
}
@Test
fun `setMonitoring should succeed when disabling when allowed`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(
SettingsData(
selectedAddressType = "nativeSegwit",
addressTypesToMonitor = listOf("nativeSegwit", "taproot")
)
)
)
whenever(lightningService.getBalanceForAddressType(AddressType.P2TR))
.thenReturn(AddressTypeBalance(totalSats = 0uL, spendableSats = 0uL))
whenever { settingsStore.update(any()) }.thenReturn(Unit)
val result = sut.setMonitoring(AddressType.P2TR, enabled = false)
assertTrue(result.isSuccess)
verify(lightningService).removeAddressTypeFromMonitor(AddressType.P2TR)
}
@Test
fun `updateAddressType should succeed`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(SettingsData(selectedAddressType = "nativeSegwit", addressTypesToMonitor = listOf("nativeSegwit")))
)
whenever { settingsStore.update(any()) }.thenReturn(Unit)
val result = sut.updateAddressType("taproot", listOf("taproot", "nativeSegwit"))
assertTrue(result.isSuccess)
verify(lightningService).setPrimaryAddressType(AddressType.P2TR)
}
@Test
fun `updateAddressType should fail when setPrimaryAddressType fails`() = test {
startNodeForTesting()
whenever(
settingsStore.data
).thenReturn(
flowOf(SettingsData(selectedAddressType = "nativeSegwit", addressTypesToMonitor = listOf("nativeSegwit")))
)
whenever { settingsStore.update(any()) }.thenReturn(Unit)
whenever(lightningService.setPrimaryAddressType(any()))
.thenThrow(RuntimeException("setPrimaryAddressType failed"))
val result = sut.updateAddressType("taproot", listOf("taproot", "nativeSegwit"))