-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRoutingFeeEstimationTest.kt
More file actions
347 lines (298 loc) · 11.3 KB
/
RoutingFeeEstimationTest.kt
File metadata and controls
347 lines (298 loc) · 11.3 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
package to.bitkit.services
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.lightningdevkit.ldknode.Bolt11Invoice
import org.lightningdevkit.ldknode.NodeException
import to.bitkit.test.annotations.CoreServiceIntegrationTest
import to.bitkit.test.annotations.DeviceIntegrationTest
import to.bitkit.data.CacheStore
import to.bitkit.data.keychain.Keychain
import to.bitkit.env.Env
import to.bitkit.repositories.WalletRepo
import to.bitkit.utils.LdkError
import javax.inject.Inject
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
@DeviceIntegrationTest
@CoreServiceIntegrationTest
class RoutingFeeEstimationTest {
companion object {
private const val NODE_STARTUP_MAX_RETRIES = 10
private const val NODE_STARTUP_RETRY_DELAY_MS = 1000L
private const val DEFAULT_INVOICE_EXPIRY_SECS = 3600u
}
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var keychain: Keychain
@Inject
lateinit var lightningService: LightningService
@Inject
lateinit var walletRepo: WalletRepo
@Inject
lateinit var cacheStore: CacheStore
private val walletIndex = 0
private val appContext = ApplicationProvider.getApplicationContext<Context>()
@Before
fun setUp() {
// Use unique storage path per test to avoid DataStore conflicts
val testStoragePath = "${appContext.filesDir.absolutePath}/${System.currentTimeMillis()}"
Env.initAppStoragePath(testStoragePath)
hiltRule.inject()
println("Starting RoutingFeeEstimation test setup with storage: $testStoragePath")
runBlocking {
println("Wiping keychain before test")
keychain.wipe()
println("Keychain wiped successfully")
}
}
@After
fun tearDown() {
runBlocking {
println("Tearing down RoutingFeeEstimation test")
if (lightningService.status?.isRunning == true) {
try {
lightningService.stop()
} catch (e: Exception) {
println("Error stopping lightning service: ${e.message}")
}
}
try {
lightningService.wipeStorage(walletIndex = walletIndex)
} catch (e: Exception) {
println("Error wiping lightning storage: ${e.message}")
}
println("Resetting cache store to clear DataStore")
try {
cacheStore.reset()
println("Cache store reset successfully")
} catch (e: Exception) {
println("Error resetting cache store: ${e.message}")
}
println("Wiping keychain after test")
keychain.wipe()
println("Keychain wiped successfully")
}
}
@Test
fun testNewRoutingFeeMethodsExist() = runBlocking {
runNode()
val paymentAmountSats = 1000uL
val invoice = createInvoiceWithAmount(
amountSats = paymentAmountSats,
description = "Method existence test"
)
// Just test that the methods exist and can be called - don't worry about results
val bolt11Payment = lightningService.node!!.bolt11Payment()
println("Testing estimateRoutingFees method...")
runCatching {
bolt11Payment.estimateRoutingFees(invoice)
}.fold(
onSuccess = { fees ->
println("estimateRoutingFees returned: $fees msat")
assertTrue(true, "Method exists and returned a value")
},
onFailure = { error ->
println("estimateRoutingFees threw: ${error.message}")
// Method exists if it throws a specific error rather than NoSuchMethodError
assertTrue(
!(error.message?.contains("NoSuchMethodError") == true),
"Method should exist (got: ${error.message})"
)
}
)
val zeroInvoice = createZeroAmountInvoice("Zero amount method test")
println("Testing estimateRoutingFeesUsingAmount method...")
runCatching {
bolt11Payment.estimateRoutingFeesUsingAmount(zeroInvoice, 1_000_000uL)
}.fold(
onSuccess = { fees ->
println("estimateRoutingFeesUsingAmount returned: $fees msat")
assertTrue(true, "Method exists and returned a value")
},
onFailure = { error ->
println("estimateRoutingFeesUsingAmount threw: ${error.message}")
// Method exists if it throws a specific error rather than NoSuchMethodError
assertTrue(
!(error.message?.contains("NoSuchMethodError") == true),
"Method should exist (got: ${error.message})"
)
}
)
}
@Test
fun estimateRoutingFeesForVariableAmountInvoice() = runBlocking {
runNode()
val invoice = createZeroAmountInvoice("Variable amount fee estimation test")
val paymentAmountMsat = 5_000_000uL
runCatching {
lightningService.node!!.bolt11Payment()
.estimateRoutingFeesUsingAmount(invoice, paymentAmountMsat)
}.fold(
onSuccess = { estimatedFeesMsat ->
assertFeesAreReasonable(estimatedFeesMsat, paymentAmountMsat)
},
onFailure = { error ->
handleExpectedRoutingError(error as NodeException)
}
)
}
@Test
fun routeNotFoundErrorIsHandledProperly() = runBlocking {
runNode()
val largeAmountSats = 1_000_000uL
val invoiceToSelf = createInvoiceWithAmount(
amountSats = largeAmountSats,
description = "Route error handling test"
)
runCatching {
lightningService.node!!.bolt11Payment().estimateRoutingFees(invoiceToSelf)
}.fold(
onSuccess = { estimatedFeesMsat ->
assertTrue(
estimatedFeesMsat >= 0u,
"If routing unexpectedly succeeds, fees should be non-negative"
)
},
onFailure = { error ->
assertRoutingErrorOccurred(error as NodeException)
}
)
}
@Test
fun zeroAmountPaymentIsHandledGracefully() = runBlocking {
runNode()
val invoice = createZeroAmountInvoice("Zero amount validation test")
val zeroAmountMsat = 0uL
runCatching {
lightningService.node!!.bolt11Payment()
.estimateRoutingFeesUsingAmount(invoice, zeroAmountMsat)
}.fold(
onSuccess = { estimatedFeesMsat ->
assertEquals(
0uL,
estimatedFeesMsat,
"Zero amount should result in zero fees"
)
},
onFailure = {
assertTrue(
true,
"Zero amount payment throwing an error is acceptable"
)
}
)
}
@Test
fun routingFeesScaleWithPaymentAmount() = runBlocking {
runNode()
val invoice = createZeroAmountInvoice("Fee scaling test")
val smallAmountMsat = 1_000_000uL
val largeAmountMsat = 10_000_000uL
runCatching {
val smallAmountFeesMsat = lightningService.node!!.bolt11Payment()
.estimateRoutingFeesUsingAmount(invoice, smallAmountMsat)
val largeAmountFeesMsat = lightningService.node!!.bolt11Payment()
.estimateRoutingFeesUsingAmount(invoice, largeAmountMsat)
Pair(smallAmountFeesMsat, largeAmountFeesMsat)
}.fold(
onSuccess = { (smallAmountFeesMsat, largeAmountFeesMsat) ->
assertFeesScaleProperly(
smallAmountFeesMsat,
largeAmountFeesMsat,
smallAmountMsat,
largeAmountMsat
)
},
onFailure = { error ->
handleExpectedRoutingError(error as NodeException)
}
)
}
// region utils
private suspend fun runNode() {
println("Creating new wallet")
walletRepo.createWallet(bip39Passphrase = null)
println("Setting up lightning service")
lightningService.setup(walletIndex = walletIndex)
println("Starting lightning node")
lightningService.start()
println("Lightning node started successfully")
waitForNodeInitialization()
println("Syncing wallet")
lightningService.sync()
println("Wallet sync complete")
}
private suspend fun waitForNodeInitialization() {
repeat(NODE_STARTUP_MAX_RETRIES) {
if (lightningService.node != null) return
delay(NODE_STARTUP_RETRY_DELAY_MS)
}
assertNotNull(lightningService.node, "Node should be initialized within timeout")
}
private suspend fun createInvoiceWithAmount(amountSats: ULong, description: String): Bolt11Invoice {
val invoiceString = lightningService.receive(
sat = amountSats,
description = description,
expirySecs = DEFAULT_INVOICE_EXPIRY_SECS
)
return Bolt11Invoice.fromStr(invoiceString)
}
private suspend fun createZeroAmountInvoice(description: String): Bolt11Invoice {
val invoiceString = lightningService.receive(
sat = null,
description = description,
expirySecs = DEFAULT_INVOICE_EXPIRY_SECS
)
return Bolt11Invoice.fromStr(invoiceString)
}
private fun assertFeesAreReasonable(estimatedFeesMsat: ULong, paymentAmountMsat: ULong) {
assertTrue(
estimatedFeesMsat >= 0u,
"Estimated fees should be non-negative, got: $estimatedFeesMsat"
)
assertTrue(
estimatedFeesMsat < paymentAmountMsat,
"Estimated fees should be less than payment amount. Fees: $estimatedFeesMsat, Amount: $paymentAmountMsat msat"
)
}
private fun handleExpectedRoutingError(error: NodeException) {
when (error) {
is NodeException.RouteNotFound -> {
assertTrue(true, "RouteNotFound error is acceptable in test environment")
}
else -> throw LdkError(error)
}
}
private fun assertRoutingErrorOccurred(error: NodeException) {
assertIs<NodeException.RouteNotFound>(error)
}
private fun assertFeesScaleProperly(
smallFees: ULong,
largeFees: ULong,
smallAmount: ULong,
largeAmount: ULong,
) {
assertTrue(
largeFees >= smallFees,
"Fees for larger amounts should be >= fees for smaller amounts. Small: $smallFees, Large: $largeFees"
)
assertFeesAreReasonable(smallFees, smallAmount)
assertFeesAreReasonable(largeFees, largeAmount)
}
// endregion
}