-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWalletRepo.kt
More file actions
611 lines (533 loc) · 22.2 KB
/
Copy pathWalletRepo.kt
File metadata and controls
611 lines (533 loc) · 22.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
package to.bitkit.repositories
import com.synonym.bitkitcore.AddressType
import com.synonym.bitkitcore.PreActivityMetadata
import com.synonym.bitkitcore.Scanner
import com.synonym.bitkitcore.decode
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lightningdevkit.ldknode.Event
import org.lightningdevkit.ldknode.WordCount
import to.bitkit.data.CacheStore
import to.bitkit.data.SettingsStore
import to.bitkit.data.keychain.Keychain
import to.bitkit.di.BgDispatcher
import to.bitkit.env.Env
import to.bitkit.ext.filterOpen
import to.bitkit.ext.nowTimestamp
import to.bitkit.ext.toHex
import to.bitkit.models.AddressModel
import to.bitkit.models.BalanceState
import to.bitkit.models.toDerivationPath
import to.bitkit.services.CoreService
import to.bitkit.usecases.DeriveBalanceStateUseCase
import to.bitkit.usecases.WipeWalletUseCase
import to.bitkit.utils.Bip21Utils
import to.bitkit.utils.Logger
import to.bitkit.utils.ServiceError
import to.bitkit.utils.errLogOf
import to.bitkit.utils.measured
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.cancellation.CancellationException
@Suppress("LongParameterList")
@Singleton
class WalletRepo @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val keychain: Keychain,
private val coreService: CoreService,
private val settingsStore: SettingsStore,
private val lightningRepo: LightningRepo,
private val cacheStore: CacheStore,
private val preActivityMetadataRepo: PreActivityMetadataRepo,
private val deriveBalanceStateUseCase: DeriveBalanceStateUseCase,
private val wipeWalletUseCase: WipeWalletUseCase,
private val transferRepo: TransferRepo,
) {
private val repoScope = CoroutineScope(bgDispatcher + SupervisorJob())
private val _walletState = MutableStateFlow(WalletState(walletExists = walletExists()))
val walletState = _walletState.asStateFlow()
private val _balanceState = MutableStateFlow(BalanceState())
val balanceState = _balanceState.asStateFlow()
private var eventSyncJob: Job? = null
init {
repoScope.launch {
lightningRepo.nodeEvents.collect { event ->
if (!walletExists()) return@collect
refreshBip21ForEvent(event)
}
}
}
fun loadFromCache() {
// TODO try keeping in sync with cache if performant and reliable
repoScope.launch {
val cacheData = cacheStore.data.first()
_walletState.update { currentState ->
currentState.copy(
onchainAddress = cacheData.onchainAddress,
bolt11 = cacheData.bolt11,
bip21 = cacheData.bip21,
)
}
cacheData.balance?.let { balance ->
_balanceState.update { balance }
}
}
}
fun walletExists(): Boolean = keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)
fun setWalletExistsState() {
_walletState.update { it.copy(walletExists = walletExists()) }
}
suspend fun checkAddressUsage(address: String): Result<Boolean> = withContext(bgDispatcher) {
return@withContext try {
val result = coreService.isAddressUsed(address)
Result.success(result)
} catch (e: Exception) {
Logger.error("checkAddressUsage error", e, context = TAG)
Result.failure(e)
}
}
suspend fun refreshBip21(): Result<Unit> = withContext(bgDispatcher) {
Logger.debug("Refreshing bip21", context = TAG)
// Preserve current amount/description before clearing
val currentAmount = _walletState.value.bip21AmountSats
val currentDescription = _walletState.value.bip21Description
// Get old payment ID and tags before refreshing (which may change payment ID)
val oldPaymentId = paymentId()
val tagsToMigrate = if (oldPaymentId != null && oldPaymentId.isNotEmpty()) {
preActivityMetadataRepo
.getPreActivityMetadata(oldPaymentId, searchByAddress = false)
.getOrNull()
?.tags ?: emptyList()
} else {
emptyList()
}
clearBip21State(clearTags = false)
refreshAddressIfNeeded()
updateBip21Invoice(amountSats = currentAmount, description = currentDescription)
val newPaymentId = paymentId()
val newBip21Url = _walletState.value.bip21
if (newPaymentId != null && newPaymentId.isNotEmpty() && newBip21Url.isNotEmpty()) {
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url)
}
return@withContext Result.success(Unit)
}
private suspend fun persistPreActivityMetadata(
paymentId: String,
tags: List<String>,
bip21Url: String,
) {
val onChainAddress = getOnchainAddress()
val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
is Scanner.Lightning -> decoded.invoice.paymentHash.toHex()
is Scanner.OnChain -> decoded.extractLightningHash()
else -> null
}
}.getOrNull()
val preActivityMetadata = PreActivityMetadata(
paymentId = paymentId,
createdAt = nowTimestamp().toEpochMilli().toULong(),
tags = tags,
paymentHash = paymentHash,
txId = null,
address = onChainAddress,
isReceive = true,
feeRate = 0u,
isTransfer = false,
channelId = "",
)
preActivityMetadataRepo.addPreActivityMetadata(preActivityMetadata)
}
suspend fun syncNodeAndWallet(source: SyncSource = SyncSource.AUTO): Result<Unit> = withContext(bgDispatcher) {
if (!lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) {
Logger.debug("syncNodeAndWallet skipped: node not running", context = TAG)
return@withContext Result.failure(Exception("Node not running"))
}
val sourceLabel = source.name.lowercase()
val startHeight = lightningRepo.lightningState.value.block()?.height
Logger.debug("Sync $sourceLabel started at block height=$startHeight", context = TAG)
val result = measured("Sync $sourceLabel") {
syncBalances()
lightningRepo.sync().onSuccess {
syncBalances()
}.onFailure { e ->
if (e is TimeoutCancellationException) {
syncBalances()
}
}
}
val endHeight = lightningRepo.lightningState.value.block()?.height
Logger.debug("Sync $sourceLabel completed at block height=$endHeight", context = TAG)
result
}
suspend fun syncBalances() {
deriveBalanceStateUseCase().onSuccess { balanceState ->
runCatching { cacheStore.cacheBalance(balanceState) }
_balanceState.update { balanceState }
}.onFailure { e ->
if (e !is CancellationException) {
Logger.warn("Could not sync balances ${errLogOf(e)}", context = TAG)
}
}
}
/** Debounce syncs for [Event.SyncCompleted]. Rapid consecutive events are coalesced. */
fun debounceSyncByEvent() {
eventSyncJob?.cancel()
eventSyncJob = repoScope.launch {
delay(EVENT_SYNC_DEBOUNCE_MS)
syncNodeAndWallet()
transferRepo.syncTransferStates()
}
}
/** Cancels any pending sync for [Event.SyncCompleted]. Called when manual pull-to-refresh takes priority. */
fun cancelSyncByEvent() {
eventSyncJob?.cancel()
eventSyncJob = null
}
suspend fun refreshBip21ForEvent(event: Event) = withContext(bgDispatcher) {
when (event) {
is Event.ChannelReady -> {
// Only refresh bolt11 if we can now receive on lightning
Logger.debug("refreshBip21ForEvent: $event", context = TAG)
if (lightningRepo.canReceive()) {
lightningRepo.createInvoice(
amountSats = _walletState.value.bip21AmountSats,
description = _walletState.value.bip21Description,
).onSuccess { bolt11 ->
setBolt11(bolt11)
updateBip21Url()
}
}
}
is Event.ChannelClosed -> {
// Clear bolt11 if we can no longer receive on lightning
Logger.debug("refreshBip21ForEvent: $event", context = TAG)
if (!lightningRepo.canReceive()) {
setBolt11("")
updateBip21Url()
}
}
is Event.PaymentReceived, is Event.OnchainTransactionReceived -> {
// Check if onchain address was used, generate new one if needed
Logger.debug("refreshBip21ForEvent: $event", context = TAG)
refreshAddressIfNeeded()
updateBip21Url()
}
else -> Unit
}
}
private suspend fun refreshAddressIfNeeded() = withContext(bgDispatcher) {
val address = getOnchainAddress()
if (address.isEmpty()) {
newAddress()
} else {
checkAddressUsage(address).onSuccess { wasUsed ->
if (wasUsed) {
newAddress()
}
}
}
}
private suspend fun updateBip21Url(
amountSats: ULong? = _walletState.value.bip21AmountSats,
message: String = _walletState.value.bip21Description,
): String {
val address = getOnchainAddress()
val newBip21 = buildBip21Url(
bitcoinAddress = address,
amountSats = amountSats,
message = message.ifBlank { Env.DEFAULT_INVOICE_MESSAGE },
lightningInvoice = getBolt11(),
)
setBip21(newBip21)
return newBip21
}
suspend fun createWallet(bip39Passphrase: String?): Result<Unit> = withContext(bgDispatcher) {
lightningRepo.setRecoveryMode(enabled = false)
try {
val mnemonic = generateEntropyMnemonic()
keychain.saveString(Keychain.Key.BIP39_MNEMONIC.name, mnemonic)
if (bip39Passphrase != null) {
keychain.saveString(Keychain.Key.BIP39_PASSPHRASE.name, bip39Passphrase)
}
setWalletExistsState()
Result.success(Unit)
} catch (e: Throwable) {
Logger.error("Create wallet error", e, context = TAG)
Result.failure(e)
}
}
suspend fun restoreWallet(mnemonic: String, bip39Passphrase: String?): Result<Unit> = withContext(bgDispatcher) {
lightningRepo.setRecoveryMode(enabled = false)
try {
keychain.saveString(Keychain.Key.BIP39_MNEMONIC.name, mnemonic)
if (bip39Passphrase != null) {
keychain.saveString(Keychain.Key.BIP39_PASSPHRASE.name, bip39Passphrase)
}
setWalletExistsState()
Result.success(Unit)
} catch (e: Throwable) {
Logger.error("Restore wallet error", e)
Result.failure(e)
}
}
suspend fun wipeWallet(walletIndex: Int = 0): Result<Unit> = withContext(bgDispatcher) {
return@withContext wipeWalletUseCase(
walletIndex = walletIndex,
resetWalletState = ::resetState,
onSuccess = ::setWalletExistsState,
)
}
fun resetState() {
_walletState.update { WalletState() }
_balanceState.update { BalanceState() }
}
// Blockchain address management
fun getOnchainAddress(): String = _walletState.value.onchainAddress
suspend fun setOnchainAddress(address: String) {
cacheStore.setOnchainAddress(address)
_walletState.update { it.copy(onchainAddress = address) }
}
suspend fun newAddress(): Result<String> = withContext(bgDispatcher) {
return@withContext lightningRepo.newAddress()
.onSuccess { address -> setOnchainAddress(address) }
.onFailure { error -> Logger.error("Error generating new address", error) }
}
suspend fun getAddresses(
startIndex: Int = 0,
isChange: Boolean = false,
count: Int = 20,
): Result<List<AddressModel>> = withContext(bgDispatcher) {
return@withContext try {
val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound
val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)
val baseDerivationPath = AddressType.P2WPKH.toDerivationPath(
index = 0,
isChange = isChange,
).substringBeforeLast("/0")
val result = coreService.onchain.deriveBitcoinAddresses(
mnemonicPhrase = mnemonic,
derivationPathStr = baseDerivationPath,
network = Env.network,
bip39Passphrase = passphrase,
isChange = isChange,
startIndex = startIndex.toUInt(),
count = count.toUInt(),
)
val addresses = result.addresses.mapIndexed { index, address ->
AddressModel(
address = address.address,
index = startIndex + index,
path = address.path,
)
}
Result.success(addresses)
} catch (e: Exception) {
Logger.error("Error getting addresses", e)
Result.failure(e)
}
}
// Bolt11 management
fun getBolt11(): String = _walletState.value.bolt11
suspend fun setBolt11(bolt11: String) {
runCatching { cacheStore.saveBolt11(bolt11) }
_walletState.update { it.copy(bolt11 = bolt11) }
}
// BIP21 management
suspend fun setBip21(bip21: String) {
runCatching { cacheStore.setBip21(bip21) }
_walletState.update { it.copy(bip21 = bip21) }
}
fun buildBip21Url(
bitcoinAddress: String,
amountSats: ULong? = null,
message: String = Env.DEFAULT_INVOICE_MESSAGE,
lightningInvoice: String = "",
): String {
return Bip21Utils.buildBip21Url(
bitcoinAddress = bitcoinAddress,
amountSats = amountSats,
message = message,
lightningInvoice = lightningInvoice
)
}
// BIP21 state management
fun setBip21AmountSats(amount: ULong?) = _walletState.update { it.copy(bip21AmountSats = amount) }
fun setBip21Description(description: String) = _walletState.update { it.copy(bip21Description = description) }
fun clearBip21State(clearTags: Boolean = true) {
_walletState.update {
it.copy(
bip21 = "",
selectedTags = if (clearTags) emptyList() else it.selectedTags,
bip21AmountSats = null,
bip21Description = "",
)
}
}
// Payment ID management
private suspend fun paymentHash(): String? = withContext(bgDispatcher) {
val bolt11 = getBolt11()
if (bolt11.isEmpty()) return@withContext null
return@withContext runCatching {
when (val decoded = decode(bolt11)) {
is Scanner.Lightning -> decoded.invoice.paymentHash.toHex()
else -> null
}
}.onFailure { e ->
Logger.error("Error extracting payment hash from bolt11", e, context = TAG)
}.getOrNull()
}
suspend fun paymentId(): String? = withContext(bgDispatcher) {
val hash = paymentHash()
if (hash != null) return@withContext hash
val address = getOnchainAddress()
return@withContext if (address.isEmpty()) null else address
}
// Pre-activity metadata tag management
suspend fun addTagToSelected(newTag: String): Result<Unit> = withContext(bgDispatcher) {
val paymentId = paymentId()
if (paymentId == null || paymentId.isEmpty()) {
Logger.warn("Cannot add tag: payment ID not available", context = TAG)
return@withContext Result.failure(
IllegalStateException("Cannot add tag: payment ID not available")
)
}
return@withContext preActivityMetadataRepo.addPreActivityMetadataTags(paymentId, listOf(newTag))
.onSuccess {
_walletState.update {
it.copy(
selectedTags = (it.selectedTags + newTag).distinct()
)
}
settingsStore.addLastUsedTag(newTag)
}.onFailure { e ->
Logger.error("Failed to add tag to pre-activity metadata", e, context = TAG)
}
}
suspend fun removeTag(tag: String): Result<Unit> = withContext(bgDispatcher) {
val paymentId = paymentId()
if (paymentId == null || paymentId.isEmpty()) {
Logger.warn("Cannot remove tag: payment ID not available", context = TAG)
return@withContext Result.failure(
IllegalStateException("Cannot remove tag: payment ID not available")
)
}
return@withContext preActivityMetadataRepo.removePreActivityMetadataTags(paymentId, listOf(tag))
.onSuccess {
_walletState.update {
it.copy(
selectedTags = it.selectedTags.filterNot { tagItem -> tagItem == tag }
)
}
}.onFailure { e ->
Logger.error("Failed to remove tag from pre-activity metadata", e, context = TAG)
}
}
suspend fun resetPreActivityMetadataTagsForCurrentInvoice() = withContext(bgDispatcher) {
val paymentId = paymentId()
if (paymentId == null || paymentId.isEmpty()) return@withContext
preActivityMetadataRepo.resetPreActivityMetadataTags(paymentId).onSuccess {
_walletState.update { it.copy(selectedTags = emptyList()) }
}.onFailure { e ->
Logger.error("Failed to reset tags for pre-activity metadata", e, context = TAG)
}
}
suspend fun loadTagsForCurrentInvoice() {
val paymentId = paymentId()
if (paymentId == null || paymentId.isEmpty()) {
_walletState.update { it.copy(selectedTags = emptyList()) }
return
}
preActivityMetadataRepo.getPreActivityMetadata(paymentId, searchByAddress = false)
.onSuccess { metadata ->
_walletState.update {
it.copy(selectedTags = metadata?.tags ?: emptyList())
}
}
.onFailure { e ->
Logger.error("Failed to load tags for current invoice", e, context = TAG)
}
}
// BIP21 invoice creation and persistence
suspend fun updateBip21Invoice(
amountSats: ULong? = walletState.value.bip21AmountSats,
description: String = walletState.value.bip21Description,
): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
val oldPaymentId = paymentId()
val tagsToMigrate = if (oldPaymentId != null && oldPaymentId.isNotEmpty()) {
preActivityMetadataRepo
.getPreActivityMetadata(oldPaymentId, searchByAddress = false)
.getOrNull()
?.tags ?: emptyList()
} else {
emptyList()
}
setBip21AmountSats(amountSats)
setBip21Description(description)
val canReceive = lightningRepo.canReceive()
if (canReceive) {
lightningRepo.createInvoice(amountSats, description).onSuccess {
setBolt11(it)
}
} else {
setBolt11("")
}
val newBip21Url = updateBip21Url(amountSats, description)
setBip21(newBip21Url)
// Persist metadata with migrated tags
val newPaymentId = paymentId()
if (newPaymentId != null && newPaymentId.isNotEmpty() && newBip21Url.isNotEmpty()) {
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url)
}
}.onFailure { e ->
Logger.error("Update BIP21 invoice error", e, context = TAG)
}
}
suspend fun shouldRequestAdditionalLiquidity(): Result<Boolean> = withContext(bgDispatcher) {
return@withContext try {
if (coreService.isGeoBlocked()) return@withContext Result.success(false)
val channels = lightningRepo.lightningState.value.channels
if (channels.filterOpen().isEmpty()) return@withContext Result.success(false)
val inboundBalanceSats = channels.sumOf { it.inboundCapacityMsat / 1000u }
Result.success((_walletState.value.bip21AmountSats ?: 0uL) >= inboundBalanceSats)
} catch (e: Exception) {
Logger.error("shouldRequestAdditionalLiquidity error", e, context = TAG)
Result.failure(e)
}
}
private suspend fun Scanner.OnChain.extractLightningHash(): String? {
val lightningInvoice: String = this.invoice.params?.get("lightning") ?: return null
return when (val decoded = decode(lightningInvoice)) {
is Scanner.Lightning -> decoded.invoice.paymentHash.toHex()
else -> null
}
}
private fun generateEntropyMnemonic(): String {
return org.lightningdevkit.ldknode.generateEntropyMnemonic(wordCount = WordCount.WORDS12)
}
private companion object {
const val TAG = "WalletRepo"
const val EVENT_SYNC_DEBOUNCE_MS = 500L
}
}
data class WalletState(
val onchainAddress: String = "",
val bolt11: String = "",
val bip21: String = "",
val bip21AmountSats: ULong? = null,
val bip21Description: String = "",
val selectedTags: List<String> = listOf(),
val walletExists: Boolean = false,
)
enum class SyncSource { AUTO, MANUAL }