-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMigrationService.kt
More file actions
1890 lines (1634 loc) · 73.5 KB
/
MigrationService.kt
File metadata and controls
1890 lines (1634 loc) · 73.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
package to.bitkit.services
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.synonym.bitkitcore.Activity
import com.synonym.bitkitcore.ActivityTags
import com.synonym.bitkitcore.ClosedChannelDetails
import com.synonym.bitkitcore.LightningActivity
import com.synonym.bitkitcore.OnchainActivity
import com.synonym.bitkitcore.PaymentState
import com.synonym.bitkitcore.PaymentType
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import org.lightningdevkit.ldknode.Network
import to.bitkit.data.CacheStore
import to.bitkit.data.SettingsStore
import to.bitkit.data.WidgetsStore
import to.bitkit.data.dao.TransferDao
import to.bitkit.data.dto.price.GraphPeriod
import to.bitkit.data.dto.price.TradingPair
import to.bitkit.data.entities.TransferEntity
import to.bitkit.data.keychain.Keychain
import to.bitkit.data.resetPin
import to.bitkit.di.json
import to.bitkit.env.Env
import to.bitkit.models.BitcoinDisplayUnit
import to.bitkit.models.CoinSelectionPreference
import to.bitkit.models.PrimaryDisplay
import to.bitkit.models.Suggestion
import to.bitkit.models.TransactionSpeed
import to.bitkit.models.TransferType
import to.bitkit.models.WidgetType
import to.bitkit.models.WidgetWithPosition
import to.bitkit.models.safe
import to.bitkit.models.widget.BlocksPreferences
import to.bitkit.models.widget.FactsPreferences
import to.bitkit.models.widget.HeadlinePreferences
import to.bitkit.models.widget.PricePreferences
import to.bitkit.models.widget.WeatherPreferences
import to.bitkit.repositories.ActivityRepo
import to.bitkit.services.core.Bip39Service
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import java.io.File
import java.security.KeyStore
import javax.inject.Inject
import javax.inject.Singleton
@Suppress("LargeClass", "TooManyFunctions", "LongParameterList")
@Singleton
class MigrationService @Inject constructor(
@ApplicationContext private val context: Context,
private val keychain: Keychain,
private val settingsStore: SettingsStore,
private val widgetsStore: WidgetsStore,
private val cacheStore: CacheStore,
private val activityRepo: ActivityRepo,
private val coreService: CoreService,
private val rnBackupClient: RNBackupClient,
private val bip39Service: Bip39Service,
private val transferDao: TransferDao,
) {
companion object {
private const val TAG = "Migration"
const val RN_MIGRATION_COMPLETED_KEY = "rnMigrationCompleted"
const val RN_MIGRATION_CHECKED_KEY = "rnMigrationChecked"
private const val OPENING_CURLY_BRACE = "{"
private const val MMKV_ROOT = "persist:root"
private const val RN_WALLET_NAME = "wallet0"
private const val MS_PER_SEC = 1000
private const val GCM_IV_LENGTH = 12
private const val GCM_TAG_LENGTH = 128
}
private val rnMigrationStore = context.rnMigrationDataStore
private inline fun <reified T> decodeBackupData(data: ByteArray): T {
val jsonElement = json.parseToJsonElement(String(data))
val dataElement = jsonElement.jsonObject["data"] ?: error("Missing 'data' field")
return json.decodeFromJsonElement(dataElement)
}
private val _isShowingMigrationLoading = MutableStateFlow(false)
val isShowingMigrationLoading: StateFlow<Boolean> = _isShowingMigrationLoading.asStateFlow()
fun setShowingMigrationLoading(value: Boolean) = _isShowingMigrationLoading.update { value }
private val _isRestoringFromRNRemoteBackup = MutableStateFlow(false)
val isRestoringFromRNRemoteBackup: StateFlow<Boolean> = _isRestoringFromRNRemoteBackup.asStateFlow()
fun setRestoringFromRNRemoteBackup(value: Boolean) = _isRestoringFromRNRemoteBackup.update { value }
@Volatile
private var pendingChannelMigration: PendingChannelMigration? = null
fun consumePendingChannelMigration(): PendingChannelMigration? {
val migration = pendingChannelMigration ?: return null
pendingChannelMigration = null
return migration
}
fun peekPendingChannelMigration(): PendingChannelMigration? = pendingChannelMigration
@Volatile
private var pendingRemoteActivityData: List<RNActivityItem>? = null
@Volatile
private var pendingRemoteTransfers: Map<String, String>? = null
@Volatile
private var pendingRemoteBoosts: Map<String, String>? = null
@Volatile
private var pendingRemoteMetadata: RNMetadata? = null
@Volatile
private var pendingRemotePaidOrders: Map<String, String>? = null
private fun buildRnLdkAccountPath(): File = run {
val rnNetworkString = when (Env.network) {
Network.BITCOIN -> "bitcoin"
Network.REGTEST -> "bitcoinRegtest"
Network.TESTNET -> "bitcoinTestnet"
Network.SIGNET -> "signet"
}
val rnLdkBasePath = File(context.filesDir, "ldk")
@Suppress("SpellCheckingInspection")
val accountName = buildString {
append(RN_WALLET_NAME)
append(rnNetworkString)
append("ldkaccountv3")
}
return File(rnLdkBasePath, accountName)
}
private fun getRnMmkvPath(): File = File(context.filesDir, "mmkv/mmkv.default")
suspend fun isMigrationChecked(): Boolean {
val key = stringPreferencesKey(RN_MIGRATION_CHECKED_KEY)
return rnMigrationStore.data.first()[key] == "true"
}
suspend fun markMigrationChecked() {
val key = stringPreferencesKey(RN_MIGRATION_CHECKED_KEY)
rnMigrationStore.edit { it[key] = "true" }
}
suspend fun hasRNWalletData(): Boolean {
val mnemonic = loadStringFromRNKeychain(RNKeychainKey.MNEMONIC)
if (mnemonic?.isNotEmpty() == true) return true
return hasRNMmkvData() || hasRNLdkData()
}
fun hasNativeWalletData() = runCatching { keychain.exists(Keychain.Key.BIP39_MNEMONIC.name) }.getOrDefault(false)
fun hasRNLdkData() = File(buildRnLdkAccountPath(), "channel_manager.bin").exists()
fun hasRNMmkvData() = getRnMmkvPath().exists()
private suspend fun loadStringFromRNKeychain(key: RNKeychainKey): String? {
val datastorePath = File(context.filesDir, "datastore/RN_KEYCHAIN.preferences_pb")
if (!datastorePath.exists()) return null
return runCatching {
val preferences = context.rnKeychainDataStore.data.first()
val passwordKey = stringPreferencesKey("${key.service}:p")
val cipherKey = stringPreferencesKey("${key.service}:c")
val encryptedValue = preferences[passwordKey] ?: return@runCatching null
val cipherInfo = preferences[cipherKey]
val fullEncryptedValue = if (cipherInfo != null && !encryptedValue.contains(":")) {
"$cipherInfo:$encryptedValue"
} else {
encryptedValue
}
decryptRNKeychainValue(fullEncryptedValue, key.service)
}.onFailure {
Logger.error("Error reading from RN_KEYCHAIN DataStore: $it", it, context = TAG)
}.getOrNull()
}
private fun decryptRNKeychainValue(encryptedValue: String, service: String): String? {
if (!encryptedValue.contains(":")) {
return runCatching {
val encryptedBytes = android.util.Base64.decode(encryptedValue, android.util.Base64.DEFAULT)
decryptWithKeystore(encryptedBytes, service)
}.onFailure {
Logger.error("Failed to decrypt without cipher prefix: $it", it, context = TAG)
}.getOrNull()
}
val parts = encryptedValue.split(":", limit = 2)
val cipherName = parts[0]
val encryptedDataBase64 = parts[1]
if (!cipherName.contains("KeystoreAESGCM")) {
Logger.warn("Unsupported cipher: $cipherName. Only KeystoreAESGCM is supported.", context = TAG)
return null
}
return runCatching {
val encryptedBytes = android.util.Base64.decode(encryptedDataBase64, android.util.Base64.DEFAULT)
decryptWithKeystore(encryptedBytes, service)
}.onFailure {
Logger.error("Failed to decrypt RN keychain value: $it", it, context = TAG)
}.getOrNull()
}
private fun decryptWithKeystore(encryptedBytes: ByteArray, service: String): String? {
if (encryptedBytes.size < GCM_IV_LENGTH) {
Logger.error("Encrypted data too short: ${encryptedBytes.size} bytes", context = TAG)
return null
}
val iv = encryptedBytes.sliceArray(0 until GCM_IV_LENGTH)
val ciphertext = encryptedBytes.sliceArray(GCM_IV_LENGTH until encryptedBytes.size)
return runCatching {
val keystore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
if (!keystore.containsAlias(service)) {
Logger.error("Keystore alias '$service' not found", context = TAG)
return@runCatching null
}
val secretKey = keystore.getKey(service, null) as javax.crypto.SecretKey
val transformation = "AES/GCM/NoPadding"
val spec = javax.crypto.spec.GCMParameterSpec(GCM_TAG_LENGTH, iv)
val cipher = javax.crypto.Cipher.getInstance(transformation).apply {
init(javax.crypto.Cipher.DECRYPT_MODE, secretKey, spec)
}
val decryptedBytes = cipher.doFinal(ciphertext)
String(decryptedBytes, Charsets.UTF_8)
}.onFailure {
Logger.error("Failed to decrypt with Keystore: $it", it, context = TAG)
}.getOrNull()
}
suspend fun migrateFromReactNative() = runCatching {
setShowingMigrationLoading(true)
val mnemonicMigrated = runCatching { migrateMnemonic() }.map { true }.onFailure {
Logger.warn("Could not migrate mnemonic: $it. User will need to manually restore.", context = TAG)
}.getOrDefault(false)
if (mnemonicMigrated) {
migratePassphrase()
migratePin()
if (hasRNLdkData()) {
migrateLdkData().onFailure {
Logger.warn("LDK data migration failed, continuing with other migrations: $it", it, context = TAG)
}
}
if (hasRNMmkvData()) {
migrateMMKVData()
}
rnMigrationStore.edit {
it[stringPreferencesKey(RN_MIGRATION_COMPLETED_KEY)] = "true"
it[stringPreferencesKey(RN_MIGRATION_CHECKED_KEY)] = "true"
}
} else {
markMigrationChecked()
setShowingMigrationLoading(false)
throw AppError("Migration data unavailable. Please restore your wallet using your recovery phrase.")
}
}.onFailure {
Logger.error("RN migration failed: $it", it, context = TAG)
markMigrationChecked()
setShowingMigrationLoading(false)
}.getOrThrow()
private suspend fun migrateMnemonic() {
val mnemonic = loadStringFromRNKeychain(RNKeychainKey.MNEMONIC)
if (mnemonic.isNullOrEmpty()) {
throw AppError("Migration data unavailable. Please restore your wallet using your recovery phrase.")
}
bip39Service.validateMnemonic(mnemonic).onFailure {
throw AppError(
"Recovery phrase is invalid. Please use your 12 or 24 word recovery phrase to restore manually."
)
}
keychain.saveString(Keychain.Key.BIP39_MNEMONIC.name, mnemonic)
}
private suspend fun migratePassphrase() {
val passphrase = loadStringFromRNKeychain(RNKeychainKey.PASSPHRASE)
if (passphrase.isNullOrEmpty()) return
keychain.saveString(Keychain.Key.BIP39_PASSPHRASE.name, passphrase)
}
private suspend fun migratePin() {
val pin = loadStringFromRNKeychain(RNKeychainKey.PIN)
if (pin.isNullOrEmpty()) return
if (pin.length != Env.PIN_LENGTH) {
Logger.warn(
"Invalid PIN length during migration: ${pin.length}, expected: ${Env.PIN_LENGTH}",
context = TAG,
)
return
}
if (!pin.all { it.isDigit() }) {
Logger.warn("Invalid PIN format during migration: contains non-numeric characters", context = TAG)
return
}
keychain.saveString(Keychain.Key.PIN.name, pin)
}
private fun migrateLdkData() = runCatching {
val accountPath = buildRnLdkAccountPath()
val managerPath = File(accountPath, "channel_manager.bin")
if (!managerPath.exists()) {
Logger.warn("LDK channel_manager.bin not found at ${managerPath.path}", context = TAG)
return@runCatching
}
val managerData = managerPath.readBytes()
val monitors = mutableListOf<ByteArray>()
val channelsPath = File(accountPath, "channels")
val monitorsPath = File(accountPath, "monitors")
val monitorDir = if (channelsPath.exists()) channelsPath else monitorsPath
monitorDir.takeIf { it.exists() }?.listFiles()?.forEach { file ->
if (file.name.endsWith(".bin")) {
monitors.add(file.readBytes())
}
}
pendingChannelMigration = PendingChannelMigration(
channelManager = managerData,
channelMonitors = monitors,
)
}.onFailure {
Logger.error("Failed to migrate LDK data: $it", it, context = TAG)
}
fun loadRNMmkvData(): Map<String, String>? = runCatching {
if (!hasRNMmkvData()) return@runCatching null
val data = getRnMmkvPath().readBytes()
val parser = MmkvParser(data)
parser.parse().takeIf { it.isNotEmpty() }
}.onFailure {
Logger.error("Failed to read MMKV data: $it", it, context = TAG)
}.getOrNull()
private fun extractRNSettings(mmkvData: Map<String, String>): RNSettings? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val settingsJsonString = root["settings"]?.jsonPrimitive?.content ?: return@runCatching null
json.decodeFromString<RNSettings>(settingsJsonString)
}.onFailure {
Logger.error("Failed to decode RN settings: $it", it, context = TAG)
}.getOrNull()
}
private fun extractRNMetadata(mmkvData: Map<String, String>): RNMetadata? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val metadataJsonString = root["metadata"]?.jsonPrimitive?.content ?: return@runCatching null
json.decodeFromString<RNMetadata>(metadataJsonString)
}.onFailure {
Logger.error("Failed to decode RN metadata: $it", it, context = TAG)
}.getOrNull()
}
private fun extractRNTodos(mmkvData: Map<String, String>): RNTodos? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val todosJsonString = root["todos"]?.jsonPrimitive?.content ?: return@runCatching null
json.decodeFromString<RNTodos>(todosJsonString)
}.onFailure {
Logger.error("Failed to decode RN todos: $it", it, context = TAG)
}.getOrNull()
}
private fun extractRNWidgets(mmkvData: Map<String, String>): RNWidgetsWithOptions? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val widgetsJsonString = root["widgets"]?.jsonPrimitive?.content
?: return@runCatching null
val widgets = json.decodeFromString<RNWidgets>(widgetsJsonString)
val widgetsData = json.parseToJsonElement(widgetsJsonString).jsonObject
val widgetOptions = convertRNWidgetPreferences(widgetsData["widgets"]?.jsonObject ?: widgetsData)
RNWidgetsWithOptions(widgets = widgets, widgetOptions = widgetOptions)
}.onFailure {
Logger.error("Failed to decode RN widgets: $it", it, context = TAG)
}.getOrNull()
}
private fun extractRNActivities(mmkvData: Map<String, String>): List<RNActivityItem>? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val activityJsonString = root["activity"]?.jsonPrimitive?.content ?: return@runCatching null
val activityState = json.decodeFromString<RNActivityState>(activityJsonString)
activityState.items ?: emptyList()
}.onFailure {
Logger.error("Failed to decode RN activities: $it", it, context = TAG)
}.getOrNull()
}
private fun extractTransfers(transfers: Map<String, List<RNRemoteTransfer>>?): Map<String, String> {
val transferMap = mutableMapOf<String, String>()
transfers?.values?.flatten()?.forEach { transfer ->
transfer.txId?.let { txId ->
transfer.type?.let { type ->
transferMap[txId] = type
}
}
}
return transferMap
}
private fun extractBoosts(boostedTxs: Map<String, Map<String, RNRemoteBoostedTx>>?): Map<String, String> {
val boostMap = mutableMapOf<String, String>()
boostedTxs?.values?.forEach { networkBoosts ->
networkBoosts.forEach { (parentTxId, boost) ->
val childTxId = boost.childTransaction ?: boost.newTxId
childTxId?.let {
boostMap[parentTxId] = it
}
}
}
return boostMap
}
private fun extractFromWalletState(walletState: RNWalletState): Pair<Map<String, String>, Map<String, String>>? {
val transferMap = mutableMapOf<String, String>()
val boostMap = mutableMapOf<String, String>()
walletState.wallets?.values?.forEach { walletDataItem ->
walletDataItem.transfers?.let { transferMap.putAll(extractTransfers(it)) }
walletDataItem.boostedTransactions?.let { boostMap.putAll(extractBoosts(it)) }
}
return if (transferMap.isNotEmpty() || boostMap.isNotEmpty()) {
Pair(transferMap, boostMap)
} else {
null
}
}
private fun extractFromWalletBackup(
walletBackup: RNRemoteWalletBackup,
): Pair<Map<String, String>, Map<String, String>>? {
val transferMap = extractTransfers(walletBackup.transfers)
val boostMap = extractBoosts(walletBackup.boostedTransactions)
return if (transferMap.isNotEmpty() || boostMap.isNotEmpty()) {
Pair(transferMap, boostMap)
} else {
null
}
}
private fun extractRNWalletBackup(mmkvData: Map<String, String>): Pair<Map<String, String>, Map<String, String>>? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val walletJsonString = root["wallet"]?.jsonPrimitive?.content ?: return@runCatching null
val walletData = json.parseToJsonElement(walletJsonString).jsonObject
val walletState = runCatching { json.decodeFromJsonElement<RNWalletState>(walletData) }.getOrNull()
walletState?.let { extractFromWalletState(it) } ?: run {
runCatching { json.decodeFromJsonElement<RNRemoteWalletBackup>(walletData) }.getOrNull()?.let {
extractFromWalletBackup(it)
}
}
}.onFailure {
Logger.error("Failed to decode RN wallet backup: $it", it, context = TAG)
}.getOrNull()
}
private fun extractRNBlocktank(mmkvData: Map<String, String>): Pair<List<String>, Map<String, String>>? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val blocktankJsonString = root["blocktank"]?.jsonPrimitive?.content ?: return@runCatching null
val blocktankData = json.parseToJsonElement(blocktankJsonString).jsonObject
val orderIds = mutableListOf<String>()
val paidOrdersMap = mutableMapOf<String, String>()
blocktankData["orders"]?.jsonArray?.forEach { orderElement ->
orderElement.jsonObject["id"]?.jsonPrimitive?.content?.let { id ->
orderIds.add(id)
}
}
blocktankData["paidOrders"]?.jsonObject?.forEach { (orderId, txIdElement) ->
val txId = txIdElement.jsonPrimitive.content
paidOrdersMap[orderId] = txId
if (orderId !in orderIds) {
orderIds.add(orderId)
}
}
if (orderIds.isEmpty() && paidOrdersMap.isEmpty()) {
return@runCatching null
}
Logger.info(
"Extracted ${orderIds.size} order IDs and ${paidOrdersMap.size} paid orders from local blocktank",
context = TAG,
)
Pair(orderIds, paidOrdersMap)
}.onFailure {
Logger.error("Failed to decode RN blocktank: $it", it, context = TAG)
}.getOrNull()
}
@Suppress("NestedBlockDepth")
private fun extractRNClosedChannels(mmkvData: Map<String, String>): List<RNChannel>? {
val rootJson = mmkvData[MMKV_ROOT] ?: return null
return runCatching {
val jsonStart = rootJson.indexOf(OPENING_CURLY_BRACE)
val jsonString = if (jsonStart >= 0) rootJson.substring(jsonStart) else rootJson
val root = json.parseToJsonElement(jsonString).jsonObject
val lightningJsonString = root["lightning"]?.jsonPrimitive?.content
?: return@runCatching null
val lightningState = json.decodeFromString<RNLightningState>(lightningJsonString)
val closedChannels = mutableListOf<RNChannel>()
lightningState.nodes?.forEach { (_, node) ->
node.channels?.forEach { (_, channels) ->
channels.forEach { (_, channel) ->
if (channel.status == "closed") {
closedChannels.add(channel)
}
}
}
}
closedChannels.takeIf { it.isNotEmpty() }
}.onFailure {
Logger.error("Failed to decode RN lightning state: $it", it, context = TAG)
}.getOrNull()
}
@Suppress("CyclomaticComplexMethod")
private suspend fun applyRNSettings(settings: RNSettings) {
settingsStore.update { current ->
current.copy(
selectedCurrency = settings.selectedCurrency ?: current.selectedCurrency,
primaryDisplay = when (settings.unit) {
"BTC" -> PrimaryDisplay.BITCOIN
else -> PrimaryDisplay.FIAT
},
displayUnit = when (settings.denomination) {
"sats" -> BitcoinDisplayUnit.MODERN
"BTC" -> BitcoinDisplayUnit.CLASSIC
else -> current.displayUnit
},
hideBalance = settings.hideBalance ?: current.hideBalance,
hideBalanceOnOpen = settings.hideBalanceOnOpen ?: current.hideBalanceOnOpen,
enableSwipeToHideBalance = settings.enableSwipeToHideBalance ?: current.enableSwipeToHideBalance,
isQuickPayEnabled = settings.enableQuickpay ?: current.isQuickPayEnabled,
quickPayAmount = settings.quickpayAmount ?: current.quickPayAmount,
enableAutoReadClipboard = settings.enableAutoReadClipboard ?: current.enableAutoReadClipboard,
enableSendAmountWarning = settings.enableSendAmountWarning ?: current.enableSendAmountWarning,
showWidgets = settings.showWidgets ?: current.showWidgets,
showWidgetTitles = settings.showWidgetTitles ?: current.showWidgetTitles,
defaultTransactionSpeed = when (settings.transactionSpeed) {
"fast" -> TransactionSpeed.Fast
"slow" -> TransactionSpeed.Slow
else -> TransactionSpeed.Medium
},
coinSelectAuto = settings.coinSelectAuto ?: current.coinSelectAuto,
coinSelectPreference = when (settings.coinSelectPreference) {
"branchAndBound" -> CoinSelectionPreference.BranchAndBound
else -> CoinSelectionPreference.SmallestFirst
},
isPinEnabled = settings.pin ?: current.isPinEnabled,
isPinForPaymentsEnabled = settings.pinForPayments ?: current.isPinForPaymentsEnabled,
isBiometricEnabled = settings.biometrics ?: current.isBiometricEnabled,
quickPayIntroSeen = settings.quickpayIntroSeen ?: current.quickPayIntroSeen,
hasSeenShopIntro = settings.shopIntroSeen ?: current.hasSeenShopIntro,
hasSeenTransferIntro = settings.transferIntroSeen ?: current.hasSeenTransferIntro,
hasSeenSpendingIntro = settings.spendingIntroSeen ?: current.hasSeenSpendingIntro,
hasSeenSavingsIntro = settings.savingsIntroSeen ?: current.hasSeenSavingsIntro,
)
}
}
private suspend fun applyRNMetadata(metadata: RNMetadata) {
val allTags = metadata.tags?.mapNotNull { (txId, tagList) ->
runCatching {
var activityId = txId
activityRepo.getOnchainActivityByTxId(txId)?.let {
activityId = it.id
}
ActivityTags(activityId = activityId, tags = tagList)
}.onFailure {
Logger.error("Failed to get activity ID for $txId: $it", it, context = TAG)
}.getOrNull()
} ?: emptyList()
if (allTags.isNotEmpty()) {
runCatching {
coreService.activity.upsertTags(allTags)
}.onFailure {
Logger.error("Failed to migrate tags: $it", it, context = TAG)
}
}
metadata.lastUsedTags?.forEach {
settingsStore.addLastUsedTag(it)
}
}
private suspend fun applyRNTodos(todos: RNTodos) {
val mapping = mapOf(
"backupSeedPhrase" to Suggestion.BACK_UP,
"buyBitcoin" to Suggestion.BUY,
"lightning" to Suggestion.LIGHTNING,
"quickpay" to Suggestion.QUICK_PAY,
"shop" to Suggestion.SHOP,
"slashtagsProfile" to Suggestion.PROFILE,
"support" to Suggestion.SUPPORT,
"invite" to Suggestion.INVITE,
"pin" to Suggestion.SECURE,
)
todos.hide?.keys?.forEach { rnTodoType ->
mapping[rnTodoType]?.let { suggestion ->
settingsStore.addDismissedSuggestion(suggestion)
}
}
}
private suspend fun applyRNActivities(items: List<RNActivityItem>) {
val activities = items.filter { it.activityType == "lightning" }.map { item ->
val txType = if (item.txType == "sent") PaymentType.SENT else PaymentType.RECEIVED
val status = when (item.status) {
"successful", "succeeded" -> PaymentState.SUCCEEDED
"failed" -> PaymentState.FAILED
else -> PaymentState.PENDING
}
val timestampSecs = (item.timestamp / MS_PER_SEC).toULong()
val invoice = item.address?.takeIf { it.isNotEmpty() } ?: "migrated:${item.id}"
Activity.Lightning(
LightningActivity(
id = item.id,
txType = txType,
status = status,
value = item.value.toULong(),
fee = item.fee?.toULong(),
invoice = invoice,
message = item.message ?: "",
timestamp = timestampSecs,
preimage = item.preimage,
createdAt = timestampSecs,
updatedAt = timestampSecs,
seenAt = timestampSecs,
)
)
}
activities.forEach { activity ->
activityRepo.upsertActivity(activity)
}
}
private suspend fun applyRNClosedChannels(channels: List<RNChannel>) {
val now = (System.currentTimeMillis() / MS_PER_SEC).toULong()
val closedChannels = channels.mapNotNull { channel ->
val fundingTxid = channel.fundingTxid ?: return@mapNotNull null
val closedAtSecs = channel.createdAt?.let { (it / MS_PER_SEC).toULong() } ?: now
val outboundMsat = (channel.outboundCapacitySat ?: 0u) * 1000u
val inboundMsat = (channel.inboundCapacitySat ?: 0u) * 1000u
ClosedChannelDetails(
channelId = channel.channelId,
counterpartyNodeId = channel.counterpartyNodeId ?: "",
fundingTxoTxid = fundingTxid,
fundingTxoIndex = 0u,
channelValueSats = channel.channelValueSatoshis ?: 0u,
closedAt = closedAtSecs,
outboundCapacityMsat = outboundMsat,
inboundCapacityMsat = inboundMsat,
counterpartyUnspendablePunishmentReserve = channel.counterpartyUnspendablePunishmentReserve ?: 0u,
unspendablePunishmentReserve = channel.unspendablePunishmentReserve ?: 0u,
forwardingFeeProportionalMillionths = 0u,
forwardingFeeBaseMsat = 0u,
channelName = "",
channelClosureReason = channel.closureReason ?: "unknown",
)
}
if (closedChannels.isNotEmpty()) {
runCatching {
coreService.activity.upsertClosedChannelList(closedChannels)
}.onFailure { e ->
Logger.error("Failed to migrate closed channels: $e", e, context = TAG)
}
}
}
private suspend fun applyRNWidgets(widgetsWithOptions: RNWidgetsWithOptions) {
val widgets = widgetsWithOptions.widgets
val widgetOptions = widgetsWithOptions.widgetOptions
widgets.sortOrder?.let { sortOrder ->
val widgetTypeMap = mapOf(
"price" to WidgetType.PRICE,
"news" to WidgetType.NEWS,
"blocks" to WidgetType.BLOCK,
"weather" to WidgetType.WEATHER,
"facts" to WidgetType.FACTS,
"calculator" to WidgetType.CALCULATOR,
)
val savedWidgets = sortOrder.mapNotNull { widgetName ->
widgetTypeMap[widgetName]?.let { type ->
WidgetWithPosition(type = type, position = sortOrder.indexOf(widgetName))
}
}
if (savedWidgets.isNotEmpty()) {
widgetsStore.updateWidgets(savedWidgets)
}
}
applyRNWidgetPreferences(widgetOptions)
widgets.onboardedWidgets?.takeIf { it }?.let {
settingsStore.update { it.copy(hasSeenWidgetsIntro = true) }
}
}
@Suppress("LongMethod", "CyclomaticComplexMethod")
private suspend fun applyRNWidgetPreferences(widgetOptions: Map<String, ByteArray>) {
widgetOptions["price"]?.let { priceData ->
runCatching {
val priceJson = json.decodeFromString<JsonObject>(
priceData.decodeToString()
)
val selectedPairs = priceJson["selectedPairs"]?.jsonArray?.mapNotNull { pairElement ->
val pairStr = pairElement.jsonPrimitive.content.replace("_", "/")
when (pairStr) {
"BTC/USD" -> TradingPair.BTC_USD
"BTC/EUR" -> TradingPair.BTC_EUR
"BTC/GBP" -> TradingPair.BTC_GBP
"BTC/JPY" -> TradingPair.BTC_JPY
else -> null
}
} ?: listOf(TradingPair.BTC_USD)
val periodStr = priceJson["selectedPeriod"]?.jsonPrimitive?.content ?: "1D"
val period = when (periodStr) {
"1D" -> GraphPeriod.ONE_DAY
"1W" -> GraphPeriod.ONE_WEEK
"1M" -> GraphPeriod.ONE_MONTH
"1Y" -> GraphPeriod.ONE_YEAR
else -> GraphPeriod.ONE_DAY
}
val showSource = priceJson["showSource"]?.jsonPrimitive?.content
?.toBooleanStrictOrNull() ?: false
widgetsStore.updatePricePreferences(
PricePreferences(
enabledPairs = selectedPairs,
period = period,
showSource = showSource
)
)
}.onFailure {
Logger.error("Failed to migrate price preferences: $it", it, context = TAG)
}
}
widgetOptions["weather"]?.let { weatherData ->
runCatching {
val weatherJson = json.decodeFromString<JsonObject>(
weatherData.decodeToString()
)
val showTitle = weatherJson["showStatus"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: true
val showDescription = weatherJson["showText"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: false
val showCurrentFee = weatherJson["showMedian"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: false
val showNextBlockFee = weatherJson["showNextBlockFee"]?.jsonPrimitive?.content
?.toBooleanStrictOrNull() ?: false
widgetsStore.updateWeatherPreferences(
WeatherPreferences(
showTitle = showTitle,
showDescription = showDescription,
showCurrentFee = showCurrentFee,
showNextBlockFee = showNextBlockFee
)
)
}.onFailure {
Logger.error("Failed to migrate weather preferences: $it", it, context = TAG)
}
}
widgetOptions["news"]?.let { newsData ->
runCatching {
val newsJson = json.decodeFromString<JsonObject>(
newsData.decodeToString()
)
val showTime = newsJson["showDate"]?.jsonPrimitive?.content
?.toBooleanStrictOrNull() ?: true
val showSource = newsJson["showSource"]?.jsonPrimitive?.content
?.toBooleanStrictOrNull() ?: true
widgetsStore.updateHeadlinePreferences(
HeadlinePreferences(
showTime = showTime,
showSource = showSource
)
)
}.onFailure {
Logger.error("Failed to migrate news preferences: $it", it, context = TAG)
}
}
widgetOptions["blocks"]?.let { blocksData ->
runCatching {
val blocksJson = json.decodeFromString<JsonObject>(
blocksData.decodeToString()
)
val showBlock = blocksJson["height"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: true
val showTime = blocksJson["time"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: true
val showDate = blocksJson["date"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: true
val showTransactions = blocksJson["transactionCount"]?.jsonPrimitive?.content
?.toBooleanStrictOrNull() ?: false
val showSize = blocksJson["size"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: false
val showSource = blocksJson["showSource"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: false
widgetsStore.updateBlocksPreferences(
BlocksPreferences(
showBlock = showBlock,
showTime = showTime,
showDate = showDate,
showTransactions = showTransactions,
showSize = showSize,
showSource = showSource
)
)
}.onFailure {
Logger.error("Failed to migrate blocks preferences: $it", it, context = TAG)
}
}
widgetOptions["facts"]?.let { factsData ->
runCatching {
val factsJson = json.decodeFromString<JsonObject>(
factsData.decodeToString()
)
val showSource = factsJson["showSource"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() ?: false
widgetsStore.updateFactsPreferences(
FactsPreferences(
showSource = showSource
)
)
}.onFailure {
Logger.error("Failed to migrate facts preferences: $it", it, context = TAG)
}
}
}
private suspend fun migrateMMKVData() {
val mmkvData = loadRNMmkvData() ?: return
extractRNActivities(mmkvData)?.let {
applyRNActivities(it)
}
extractRNClosedChannels(mmkvData)?.let {
applyRNClosedChannels(it)
}
extractRNSettings(mmkvData)?.let { settings ->
applyRNSettings(settings)
}
extractRNMetadata(mmkvData)?.let { metadata ->
applyRNMetadata(metadata)
}
extractRNWidgets(mmkvData)?.let { widgets ->
applyRNWidgets(widgets)
}
extractRNTodos(mmkvData)?.let { todos ->
applyRNTodos(todos)
}
extractRNBlocktank(mmkvData)?.let { (orderIds, paidOrders) ->
applyRNBlocktank(orderIds, paidOrders)
}
}
private suspend fun applyRNBlocktank(orderIds: List<String>, paidOrders: Map<String, String>) {
if (orderIds.isEmpty()) return
paidOrders.forEach { (orderId, txId) ->
cacheStore.addPaidOrder(orderId, txId)
}
runCatching {
val fetchedOrders = coreService.blocktank.orders(
orderIds = orderIds,
filter = null,
refresh = true,
)
if (fetchedOrders.isNotEmpty()) {
coreService.blocktank.upsertOrderList(fetchedOrders)
if (paidOrders.isNotEmpty()) {
createTransfersForPaidOrders(paidOrders, fetchedOrders)
}
}
}.onFailure { e ->
Logger.warn("Failed to fetch and upsert local Blocktank orders: $e", context = TAG)
}