-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBlocktankRepo.kt
More file actions
512 lines (436 loc) · 18.5 KB
/
BlocktankRepo.kt
File metadata and controls
512 lines (436 loc) · 18.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
package to.bitkit.repositories
import com.synonym.bitkitcore.BtOrderState2
import com.synonym.bitkitcore.ChannelLiquidityOptions
import com.synonym.bitkitcore.ChannelLiquidityParams
import com.synonym.bitkitcore.CreateCjitOptions
import com.synonym.bitkitcore.CreateOrderOptions
import com.synonym.bitkitcore.DefaultLspBalanceParams
import com.synonym.bitkitcore.IBtEstimateFeeResponse2
import com.synonym.bitkitcore.IBtInfo
import com.synonym.bitkitcore.IBtOrder
import com.synonym.bitkitcore.IcJitEntry
import com.synonym.bitkitcore.calculateChannelLiquidityOptions
import com.synonym.bitkitcore.getDefaultLspBalance
import com.synonym.bitkitcore.giftOrder
import com.synonym.bitkitcore.giftPay
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lightningdevkit.ldknode.ChannelDetails
import to.bitkit.async.ServiceQueue
import to.bitkit.data.CacheStore
import to.bitkit.di.BgDispatcher
import to.bitkit.env.Env
import to.bitkit.ext.calculateRemoteBalance
import to.bitkit.ext.nowTimestamp
import to.bitkit.models.BlocktankBackupV1
import to.bitkit.models.EUR_CURRENCY
import to.bitkit.services.CoreService
import to.bitkit.services.LightningService
import to.bitkit.utils.Logger
import to.bitkit.utils.ServiceError
import java.math.BigDecimal
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlin.math.ceil
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@Singleton
@Suppress("LongParameterList")
class BlocktankRepo @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val coreService: CoreService,
private val lightningService: LightningService,
private val currencyRepo: CurrencyRepo,
private val cacheStore: CacheStore,
@Named("enablePolling") private val enablePolling: Boolean,
private val lightningRepo: LightningRepo,
) {
private val repoScope = CoroutineScope(bgDispatcher + SupervisorJob())
private val _blocktankState = MutableStateFlow(BlocktankState())
val blocktankState: StateFlow<BlocktankState> = _blocktankState.asStateFlow()
@Volatile
private var isRefreshing = false
init {
startPolling()
observePaidOrders()
repoScope.launch {
refreshInfo()
refreshOrders()
}
}
private fun startPolling() {
if (!enablePolling) return
flow {
while (currentCoroutineContext().isActive) {
emit(Unit)
delay(Env.lspOrderRefreshInterval)
}
}.flowOn(bgDispatcher)
.onEach { refreshOrders() }
.launchIn(repoScope)
}
private fun observePaidOrders() {
repoScope.launch {
cacheStore.data
.map { it.paidOrders }
.distinctUntilChanged()
.map { it.keys }
.collect { paidOrderIds ->
_blocktankState.update { state ->
state.copy(
paidOrders = state.orders.filter { order -> order.id in paidOrderIds },
)
}
}
}
}
suspend fun getCjitEntry(channel: ChannelDetails): IcJitEntry? = withContext(bgDispatcher) {
return@withContext _blocktankState.value.cjitEntries.firstOrNull { order ->
order.channelSizeSat == channel.channelValueSats &&
order.lspNode.pubkey == channel.counterpartyNodeId
}
}
suspend fun refreshInfo() = withContext(bgDispatcher) {
try {
// Load from cache first
val cachedInfo = coreService.blocktank.info(refresh = false)
_blocktankState.update { it.copy(info = cachedInfo) }
// Then refresh from server
val info = coreService.blocktank.info(refresh = true)
_blocktankState.update { it.copy(info = info) }
Logger.debug("Blocktank info refreshed", context = TAG)
} catch (e: Throwable) {
Logger.error("Failed to refresh blocktank info", e, context = TAG)
}
}
suspend fun refreshOrders() = withContext(bgDispatcher) {
if (isRefreshing) return@withContext
isRefreshing = true
try {
Logger.verbose("Refreshing blocktank orders…", context = TAG)
val paidOrderIds = cacheStore.data.first().paidOrders.keys
// Sync instantly from cache
val cachedOrders = coreService.blocktank.orders(refresh = false)
val cachedCjitEntries = coreService.blocktank.cjitEntries(refresh = false)
_blocktankState.update { state ->
state.copy(
orders = cachedOrders,
cjitEntries = cachedCjitEntries,
paidOrders = cachedOrders.filter { order -> order.id in paidOrderIds },
)
}
// Then refresh from server
val orders = coreService.blocktank.orders(refresh = true)
val cjitEntries = coreService.blocktank.cjitEntries(refresh = true)
_blocktankState.update { state ->
state.copy(
orders = orders,
cjitEntries = cjitEntries,
paidOrders = orders.filter { order -> order.id in paidOrderIds },
)
}
Logger.debug(
"Orders refreshed: ${orders.size} orders, " +
"${cjitEntries.size} cjit entries, " +
"${_blocktankState.value.paidOrders.size} paid orders",
context = TAG
)
openChannelWithPaidOrders()
} catch (e: Throwable) {
Logger.error("Failed to refresh orders", e, context = TAG)
} finally {
isRefreshing = false
}
}
suspend fun refreshMinCjitSats() = withContext(bgDispatcher) {
try {
val lspBalance = getDefaultLspBalance(clientBalance = 0u)
val fees = estimateOrderFee(
spendingBalanceSats = 0u,
receivingBalanceSats = lspBalance,
).getOrThrow()
val minimum = (ceil(fees.feeSat.toDouble() * 1.1 / 1000) * 1000).toInt()
_blocktankState.update { it.copy(minCjitSats = minimum) }
Logger.debug("Updated minCjitSats to: $minimum", context = TAG)
} catch (e: Throwable) {
Logger.error("Failed to refresh minCjitSats", e, context = TAG)
}
}
suspend fun createCjit(
amountSats: ULong,
description: String = Env.DEFAULT_INVOICE_MESSAGE,
): Result<IcJitEntry> = withContext(bgDispatcher) {
try {
if (coreService.isGeoBlocked()) throw ServiceError.GeoBlocked
val nodeId = lightningService.nodeId ?: throw ServiceError.NodeNotStarted
val lspBalance = getDefaultLspBalance(clientBalance = amountSats)
val channelSizeSat = amountSats + lspBalance
val cjitEntry = coreService.blocktank.createCjit(
channelSizeSat = channelSizeSat,
invoiceSat = amountSats,
invoiceDescription = description,
nodeId = nodeId,
channelExpiryWeeks = DEFAULT_CHANNEL_EXPIRY_WEEKS,
options = CreateCjitOptions(source = DEFAULT_SOURCE, discountCode = null)
)
repoScope.launch { refreshOrders() }
Result.success(cjitEntry)
} catch (e: Throwable) {
Logger.error("Failed to create CJIT", e, context = TAG)
Result.failure(e)
}
}
suspend fun createOrder(
spendingBalanceSats: ULong,
receivingBalanceSats: ULong = spendingBalanceSats * 2u,
channelExpiryWeeks: UInt = DEFAULT_CHANNEL_EXPIRY_WEEKS,
): Result<IBtOrder> = withContext(bgDispatcher) {
try {
if (coreService.isGeoBlocked()) throw ServiceError.GeoBlocked
val options = defaultCreateOrderOptions(clientBalanceSat = spendingBalanceSats)
Logger.info(
"Buying channel with lspBalanceSat: $receivingBalanceSats, channelExpiryWeeks: $channelExpiryWeeks, options: $options",
context = TAG,
)
val order = coreService.blocktank.newOrder(
lspBalanceSat = receivingBalanceSats,
channelExpiryWeeks = channelExpiryWeeks,
options = options,
)
repoScope.launch { refreshOrders() }
Result.success(order)
} catch (e: Throwable) {
Logger.error("Failed to create order", e, context = TAG)
Result.failure(e)
}
}
suspend fun estimateOrderFee(
spendingBalanceSats: ULong,
receivingBalanceSats: ULong,
channelExpiryWeeks: UInt = DEFAULT_CHANNEL_EXPIRY_WEEKS,
): Result<IBtEstimateFeeResponse2> = withContext(bgDispatcher) {
Logger.info("Estimating order fee for spendingSats=$spendingBalanceSats, receivingSats=$receivingBalanceSats")
try {
val options = defaultCreateOrderOptions(clientBalanceSat = spendingBalanceSats)
val estimate = coreService.blocktank.estimateFee(
lspBalanceSat = receivingBalanceSats,
channelExpiryWeeks = channelExpiryWeeks,
options = options,
)
Logger.debug("Estimated order fee: '$estimate'")
Result.success(estimate)
} catch (e: Throwable) {
Logger.error("Failed to estimate order fee", e, context = TAG)
Result.failure(e)
}
}
suspend fun openChannel(orderId: String): Result<IBtOrder> = withContext(bgDispatcher) {
try {
Logger.debug("Opening channel for order: '$orderId'", context = TAG)
val order = coreService.blocktank.open(orderId)
// Update the order in state
val updatedOrders = _blocktankState.value.orders.toMutableList()
val index = updatedOrders.indexOfFirst { it.id == order.id }
if (index != -1) {
updatedOrders[index] = order
}
_blocktankState.update { state -> state.copy(orders = updatedOrders) }
Result.success(order)
} catch (e: Throwable) {
Logger.error("Failed to open channel for order: $orderId", e, context = TAG)
Result.failure(e)
}
}
suspend fun getOrder(
orderId: String,
refresh: Boolean = false,
): Result<IBtOrder?> = withContext(bgDispatcher) {
try {
if (refresh) {
refreshOrders()
}
val order = _blocktankState.value.orders.find { it.id == orderId }
Result.success(order)
} catch (e: Throwable) {
Logger.error("Failed to get order: $orderId", e, context = TAG)
Result.failure(e)
}
}
private suspend fun openChannelWithPaidOrders() = withContext(bgDispatcher) {
_blocktankState.value.paidOrders.filter { it.state2 == BtOrderState2.PAID }.forEach { order ->
openChannel(order.id)
}
}
private suspend fun defaultCreateOrderOptions(clientBalanceSat: ULong): CreateOrderOptions {
val nodeId = lightningService.nodeId ?: throw ServiceError.NodeNotStarted
val timestamp = nowTimestamp().toString()
val signature = lightningService.sign("channelOpen-$timestamp")
return CreateOrderOptions(
clientBalanceSat = clientBalanceSat,
lspNodeId = null,
couponCode = "",
source = DEFAULT_SOURCE,
discountCode = null,
zeroConf = true,
zeroConfPayment = false,
zeroReserve = true,
clientNodeId = nodeId,
signature = signature,
timestamp = timestamp,
refundOnchainAddress = null,
announceChannel = false,
)
}
suspend fun getDefaultLspBalance(clientBalance: ULong): ULong = withContext(bgDispatcher) {
if (_blocktankState.value.info == null) {
refreshInfo()
}
val satsPerEur = getSatsPerEur()
?: throw ServiceError.CurrencyRateUnavailable
val params = DefaultLspBalanceParams(
clientBalanceSat = clientBalance,
maxChannelSizeSat = _blocktankState.value.info?.options?.maxChannelSizeSat ?: 0uL,
satsPerEur = satsPerEur
)
return@withContext getDefaultLspBalance(params)
}
fun calculateLiquidityOptions(clientBalanceSat: ULong): Result<ChannelLiquidityOptions> {
val blocktankInfo = blocktankState.value.info
?: return Result.failure(ServiceError.BlocktankInfoUnavailable)
val satsPerEur = getSatsPerEur()
?: return Result.failure(ServiceError.CurrencyRateUnavailable)
val existingChannelsTotalSat = totalBtChannelsValueSats(blocktankInfo)
val params = ChannelLiquidityParams(
clientBalanceSat = clientBalanceSat,
existingChannelsTotalSat = existingChannelsTotalSat,
minChannelSizeSat = blocktankInfo.options.minChannelSizeSat,
maxChannelSizeSat = blocktankInfo.options.maxChannelSizeSat,
satsPerEur = satsPerEur
)
return Result.success(calculateChannelLiquidityOptions(params))
}
private fun getSatsPerEur(): ULong? {
return currencyRepo.convertFiatToSats(BigDecimal(1), EUR_CURRENCY).getOrNull()
}
private fun totalBtChannelsValueSats(info: IBtInfo?): ULong {
val channels = lightningRepo.getChannels() ?: return 0u
val btNodeIds = info?.nodes?.map { it.pubkey } ?: return 0u
val btChannels = channels.filter { btNodeIds.contains(it.counterpartyNodeId) }
return btChannels.sumOf { it.channelValueSats }
}
suspend fun resetState() = withContext(bgDispatcher) {
_blocktankState.update { BlocktankState() }
Logger.debug("Blocktank state reset", context = TAG)
}
suspend fun restoreFromBackup(payload: BlocktankBackupV1): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.blocktank.upsertOrderList(payload.orders)
coreService.blocktank.upsertCjitList(payload.cjitEntries)
payload.info?.let { info ->
coreService.blocktank.setInfo(info)
}
// We don't refresh orders here because we rely on the polling mechanism.
// We also don't restore `paidOrders` the refresh interval uses restored paidOrderIds to rebuild the list.
_blocktankState.update {
it.copy(
orders = payload.orders,
cjitEntries = payload.cjitEntries,
info = payload.info,
)
}
}.onSuccess {
Logger.debug("Restored ${payload.orders.size} orders, ${payload.cjitEntries.size} CJITs", TAG)
}
}
suspend fun claimGiftCode(
code: String,
amount: ULong,
waitTimeout: Duration = TIMEOUT_GIFT_CODE,
): Result<GiftClaimResult> = withContext(bgDispatcher) {
runCatching {
require(code.isNotBlank()) { "Gift code cannot be blank" }
require(amount > 0u) { "Gift amount must be positive" }
lightningRepo.executeWhenNodeRunning(
operationName = "claimGiftCode",
waitTimeout = waitTimeout,
) {
delay(PEER_CONNECTION_DELAY_MS)
val channels = lightningRepo.getChannelsAsync().getOrThrow()
val maxInboundCapacity = channels.calculateRemoteBalance()
if (maxInboundCapacity >= amount) {
Result.success(claimGiftCodeWithLiquidity(code))
} else {
Result.success(claimGiftCodeWithoutLiquidity(code, amount))
}
}.getOrThrow()
}.onFailure { e ->
Logger.error("Failed to claim gift code", e, context = TAG)
}
}
private suspend fun claimGiftCodeWithLiquidity(code: String): GiftClaimResult {
val invoice = lightningRepo.createInvoice(
amountSats = null,
description = "blocktank-gift-code:$code",
expirySeconds = 3600u,
).getOrThrow()
ServiceQueue.CORE.background {
giftPay(invoice = invoice)
}
return GiftClaimResult.SuccessWithLiquidity
}
private suspend fun claimGiftCodeWithoutLiquidity(code: String, amount: ULong): GiftClaimResult {
val nodeId = lightningService.nodeId ?: throw ServiceError.NodeNotStarted
val order = ServiceQueue.CORE.background {
giftOrder(clientNodeId = nodeId, code = "blocktank-gift-code:$code")
}
val orderId = checkNotNull(order.orderId) { "Order ID is null" }
val openedOrder = openChannel(orderId).getOrThrow()
return GiftClaimResult.SuccessWithoutLiquidity(
paymentHashOrTxId = openedOrder.channel?.fundingTx?.id ?: orderId,
sats = amount.toLong(),
invoice = openedOrder.payment?.bolt11Invoice?.request ?: "",
code = code,
)
}
companion object {
private const val TAG = "BlocktankRepo"
private const val DEFAULT_CHANNEL_EXPIRY_WEEKS = 6u
private const val DEFAULT_SOURCE = "bitkit-android"
private const val PEER_CONNECTION_DELAY_MS = 2_000L
private val TIMEOUT_GIFT_CODE = 30.seconds
}
}
data class BlocktankState(
val orders: List<IBtOrder> = emptyList(),
val paidOrders: List<IBtOrder> = emptyList(),
val cjitEntries: List<IcJitEntry> = emptyList(),
val info: IBtInfo? = null,
val minCjitSats: Int? = null,
)
sealed class GiftClaimResult {
object SuccessWithLiquidity : GiftClaimResult()
data class SuccessWithoutLiquidity(
val paymentHashOrTxId: String,
val sats: Long,
val invoice: String,
val code: String,
) : GiftClaimResult()
}