-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTrezorRepo.kt
More file actions
1298 lines (1197 loc) · 53.5 KB
/
Copy pathTrezorRepo.kt
File metadata and controls
1298 lines (1197 loc) · 53.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.repositories
import android.content.Context
import androidx.compose.runtime.Stable
import com.synonym.bitkitcore.AccountInfoResult
import com.synonym.bitkitcore.AccountType
import com.synonym.bitkitcore.AddressType
import com.synonym.bitkitcore.CoinSelection
import com.synonym.bitkitcore.ComposeOutput
import com.synonym.bitkitcore.ComposeParams
import com.synonym.bitkitcore.ComposeResult
import com.synonym.bitkitcore.EventListener
import com.synonym.bitkitcore.SingleAddressInfoResult
import com.synonym.bitkitcore.TransactionHistoryResult
import com.synonym.bitkitcore.TrezorAddressResponse
import com.synonym.bitkitcore.TrezorCoinType
import com.synonym.bitkitcore.TrezorDeviceInfo
import com.synonym.bitkitcore.TrezorFeatures
import com.synonym.bitkitcore.TrezorPublicKeyResponse
import com.synonym.bitkitcore.TrezorScriptType
import com.synonym.bitkitcore.TrezorSignedMessageResponse
import com.synonym.bitkitcore.TrezorSignedTx
import com.synonym.bitkitcore.TrezorTransportType
import com.synonym.bitkitcore.WalletParams
import com.synonym.bitkitcore.WalletSelection
import com.synonym.bitkitcore.WatcherEvent
import com.synonym.bitkitcore.WatcherParams
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
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.withTimeout
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import to.bitkit.data.HwWalletStore
import to.bitkit.data.SettingsStore
import to.bitkit.di.IoDispatcher
import to.bitkit.env.Env
import to.bitkit.ext.isTrezorDeviceBusy
import to.bitkit.ext.isTrezorUserCancellation
import to.bitkit.ext.nowMs
import to.bitkit.ext.runSuspendCatching
import to.bitkit.ext.toTransportType
import to.bitkit.models.ALL_ADDRESS_TYPES
import to.bitkit.models.KnownDevice
import to.bitkit.models.TransportType
import to.bitkit.models.toAccountDerivationPath
import to.bitkit.models.toCoreNetwork
import to.bitkit.models.toSettingsString
import to.bitkit.models.toTrezorCoinType
import to.bitkit.services.TrezorDebugLog
import to.bitkit.services.TrezorService
import to.bitkit.services.TrezorTransport
import to.bitkit.services.TrezorUiHandler
import to.bitkit.services.TrezorWalletMode
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import to.bitkit.utils.TrezorErrorPresenter
import java.io.File
import to.bitkit.models.HwWalletId
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Clock
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import com.synonym.bitkitcore.Network as BitkitCoreNetwork
@OptIn(ExperimentalTime::class)
@Suppress("TooManyFunctions", "LongParameterList", "LargeClass")
@Singleton
class TrezorRepo @Inject constructor(
@ApplicationContext private val context: Context,
private val trezorService: TrezorService,
private val trezorTransport: TrezorTransport,
private val trezorUiHandler: TrezorUiHandler,
private val hwWalletStore: HwWalletStore,
private val settingsStore: SettingsStore,
private val clock: Clock,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
companion object {
private const val TAG = "TrezorRepo"
private const val WATCHER_TAG = "WATCHER"
private const val DEFAULT_ADDRESS_PATH = "m/84'/0'/0'/0/0"
private const val DEFAULT_ACCOUNT_PATH = "m/84'/0'/0'"
private const val WALLET_MODE_RECONNECT_DELAY_MS = 1_000L
private const val TRANSPORT_RESTORED_MAX_ATTEMPTS = 4
private val TRANSPORT_RESTORED_RECONNECT_DELAY = 2.seconds
private val CONNECT_ATTEMPT_POLL_INTERVAL = 250.milliseconds
private val CONNECT_ATTEMPT_MAX_WAIT = 28.seconds
private const val MAX_XPUB_FETCH_ATTEMPTS = 3
private val XPUB_FETCH_RETRY_DELAY = 300.milliseconds
private val TRANSIENT_FAILURE_MARKERS = listOf(
"TransportError",
"ConnectionError",
"DeviceDisconnected",
"Timeout",
"IoError",
"SessionError",
)
}
private val _state = MutableStateFlow(TrezorState())
val state = _state.asStateFlow()
private val scope = CoroutineScope(SupervisorJob() + ioDispatcher)
private var isSetup = CompletableDeferred<Unit>()
private val setupMutex = Mutex()
@Volatile
private var transportReconnectJob: Job? = null
init {
observeExternalDisconnects()
observeTransportRestored()
}
private val _watcherEvents = MutableSharedFlow<Pair<String, WatcherEvent>>(extraBufferCapacity = 64)
val watcherEvents: SharedFlow<Pair<String, WatcherEvent>> = _watcherEvents.asSharedFlow()
private val eventBridge: EventListener = object : EventListener {
override fun onEvent(watcherId: String, event: WatcherEvent) {
TrezorDebugLog.log(WATCHER_TAG, "[$watcherId] ${event::class.simpleName}")
_watcherEvents.tryEmit(watcherId to event)
}
}
/**
* Flow indicating when a pairing code needs to be entered.
* UI should show a dialog when this emits true.
*/
val needsPairingCode = trezorTransport.needsPairingCode
/**
* Submit the pairing code entered by the user.
*/
fun submitPairingCode(code: String) {
trezorTransport.submitPairingCode(code)
}
/**
* Cancel pairing code entry.
*/
fun cancelPairingCode() {
trezorTransport.cancelPairingCode()
}
val needsPinEntry = trezorUiHandler.needsPinEntry
fun submitPin(pin: String) {
trezorUiHandler.submitPin(pin)
}
fun cancelPin() {
trezorUiHandler.cancelPin()
}
val walletMode = trezorUiHandler.walletMode
/**
* Reset to the standard wallet and clear any selected passphrase, without
* reconnecting. Call this when the user explicitly picks a device from a
* list ([connect]/[connectKnownDevice]) so a passphrase or on-device
* selection left over from a previously connected device isn't silently
* applied to the newly selected one.
*
* Silent reconnects ([autoReconnect]/[ensureConnected]) deliberately skip
* this, so a dropped link reopens the same hidden wallet the user was using.
*/
fun resetWalletSelection() {
trezorUiHandler.setWalletMode(TrezorWalletMode.STANDARD)
}
suspend fun resetState() = withContext(ioDispatcher) {
resetSetup()
transportReconnectJob?.cancel()
transportReconnectJob = null
val knownDevices = (_state.value.knownDevices + hwWalletStore.loadKnownDevices())
.distinctBy { it.id }
if (_state.value.connected != null) {
runSuspendCatching { disconnect().getOrThrow() }
}
knownDevices.forEach { device ->
runCatching { trezorTransport.clearDeviceCredential(device.id) }
.onFailure { Logger.warn("Failed to clear transport credential for '${device.id}'", it, context = TAG) }
runCatching { trezorService.clearCredentials(device.id) }
.onFailure { Logger.warn("Failed to clear Trezor credentials for '${device.id}'", it, context = TAG) }
}
trezorUiHandler.setWalletMode(TrezorWalletMode.STANDARD)
hwWalletStore.reset()
_state.update {
it.copy(
isScanning = false,
isConnecting = false,
isAutoReconnecting = false,
knownDevices = persistentListOf(),
nearbyDevices = persistentListOf(),
connected = null,
lastAddress = null,
lastPublicKey = null,
error = null,
)
}
}
/**
* Switch between the standard wallet and a passphrase (hidden) wallet.
*
* The Trezor caches the passphrase for the whole session, so switching
* requires a fresh session: this sets the desired mode, then disconnects
* and reconnects. The new mode takes effect on the next wallet operation.
*/
suspend fun setWalletMode(
mode: TrezorWalletMode,
passphrase: String = "",
): Result<TrezorFeatures> = withContext(ioDispatcher) {
runCatching {
val deviceId = _state.value.connectedDeviceId()
?: throw AppError("No connected Trezor")
TrezorDebugLog.log("WALLET_MODE", "Switching to $mode, resetting session for $deviceId")
// Reset the session via disconnect/reconnect. disconnect() resets the
// UI handler's wallet mode to standard, so set the desired mode AFTER
// the disconnect and right before reconnecting.
runCatching { disconnect() }
// Reconnect by id WITHOUT a scan: scan() clears the discovered-device
// cache and a scan right after a disconnect usually finds nothing,
// whereas the cached handle (and direct address resolution) still work.
delay(WALLET_MODE_RECONNECT_DELAY_MS)
// Record the selection on the handler: THP reads it via
// currentSelection() to bind the passphrase at session creation,
// while non-THP devices re-request it mid-operation and are answered
// from the same value. connect() then derives the wallet from it.
trezorUiHandler.setWalletMode(mode, passphrase)
connect(deviceId).getOrThrow()
}
}
suspend fun initialize(walletIndex: Int = 0): Result<Unit> = withContext(ioDispatcher) {
setupMutex.withLock {
if (isSetup.isCancelled) {
isSetup = CompletableDeferred()
}
if (isSetup.isCompleted) {
isSetup.await()
return@withLock Result.success(Unit)
}
val setup = isSetup
runSuspendCatching {
val credentialPath = "${Env.bitkitCoreStoragePath(walletIndex)}/trezor-credentials.json"
Logger.debug("Initializing Trezor with credential path: '$credentialPath'", context = TAG)
trezorService.initialize(credentialPath)
val known = loadKnownDevices()
_state.update { it.copy(knownDevices = known.toImmutableList(), error = null) }
setup.complete(Unit)
Unit
}.onFailure { e ->
setup.completeExceptionally(e)
if (isSetup === setup) {
isSetup = CompletableDeferred()
}
Logger.error("Trezor init failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
}
suspend fun scan(includeBluetooth: Boolean = true): Result<List<TrezorDeviceInfo>> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
_state.update { it.copy(isScanning = true, error = null) }
val devices = trezorService.scan(includeBluetooth = includeBluetooth)
val knownIds = _state.value.knownDevices.map { it.id }.toSet()
val nearby = devices.filter { it.id !in knownIds }
_state.update { it.copy(isScanning = false, nearbyDevices = nearby.toImmutableList()) }
devices
}.onFailure { e ->
Logger.error("Trezor scan failed", e, context = TAG)
_state.update { it.copy(isScanning = false, error = trezorErrorMessage(e)) }
}
}
suspend fun listDevices(): Result<List<TrezorDeviceInfo>> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
val devices = trezorService.listDevices()
val knownIds = _state.value.knownDevices.map { it.id }.toSet()
val nearby = devices.filter { it.id !in knownIds }
_state.update { it.copy(nearbyDevices = nearby.toImmutableList()) }
devices
}.onFailure { e ->
Logger.error("Trezor listDevices failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun connect(
deviceId: String,
requestUsbPermission: Boolean = true,
): Result<TrezorFeatures> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
_state.update { it.copy(isConnecting = true, error = null) }
TrezorDebugLog.log("CONNECT", "connect() called for deviceId=$deviceId")
val features = connectWithThpRetry(
deviceId = deviceId,
selection = trezorUiHandler.currentSelection(),
requestUsbPermission = requestUsbPermission,
)
TrezorDebugLog.log("CONNECT", "connect() succeeded: label=${features.label}, model=${features.model}")
val deviceInfo = _state.value.nearbyDevices.find { it.id == deviceId }
?: _state.value.knownDevices.find { it.id == deviceId }?.let { known ->
TrezorDeviceInfo(
id = known.id,
transportType = known.transportType.toCoreTransportType(),
name = known.name,
path = known.path,
label = known.label,
model = known.model,
isBootloader = false,
)
}
if (deviceInfo != null) {
addOrUpdateKnownDevice(deviceInfo, features)
}
_state.update {
it.copy(
isConnecting = false,
connected = ConnectedTrezorDevice(id = deviceId, features = features),
nearbyDevices = it.nearbyDevices.filter { d -> d.id != deviceId }.toImmutableList(),
)
}
features
}.onFailure { e ->
Logger.error("Trezor connect failed", e, context = TAG)
_state.update { it.copy(isConnecting = false, error = trezorErrorMessage(e)) }
}
}
suspend fun getAddress(
path: String = DEFAULT_ADDRESS_PATH,
showOnTrezor: Boolean = false,
scriptType: TrezorScriptType? = TrezorScriptType.SPEND_WITNESS,
coin: TrezorCoinType = TrezorCoinType.BITCOIN,
): Result<TrezorAddressResponse> = withContext(ioDispatcher) {
runCatching {
ensureConnected()
val response = trezorService.getAddress(
path = path,
coin = coin,
showOnTrezor = showOnTrezor,
scriptType = scriptType,
)
_state.update { it.copy(lastAddress = response, error = null) }
response
}.onFailure { e ->
Logger.error("Trezor getAddress failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun getPublicKey(
path: String = DEFAULT_ACCOUNT_PATH,
showOnTrezor: Boolean = false,
coin: TrezorCoinType = TrezorCoinType.BITCOIN,
): Result<TrezorPublicKeyResponse> = withContext(ioDispatcher) {
runCatching {
ensureConnected()
val response = trezorService.getPublicKey(
path = path,
coin = coin,
showOnTrezor = showOnTrezor,
)
_state.update { it.copy(lastPublicKey = response, error = null) }
response
}.onFailure { e ->
Logger.error("Trezor getPublicKey failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun getTransactionHistory(
extendedKey: String,
network: BitkitCoreNetwork = Env.network.toCoreNetwork(),
scriptType: AccountType? = null,
): Result<TransactionHistoryResult> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
trezorService.getTransactionHistory(
extendedKey = extendedKey,
electrumUrl = currentElectrumUrl(),
network = network,
scriptType = scriptType,
)
}.onFailure {
Logger.error("Failed to get Trezor transaction history", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
suspend fun getAccountInfo(
extendedKey: String,
network: BitkitCoreNetwork = Env.network.toCoreNetwork(),
scriptType: AccountType? = null,
): Result<AccountInfoResult> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
trezorService.getAccountInfo(
extendedKey = extendedKey,
electrumUrl = currentElectrumUrl(),
network = network,
scriptType = scriptType,
)
}.onFailure { e ->
Logger.error("Trezor getAccountInfo failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun getAddressInfo(
address: String,
network: BitkitCoreNetwork = Env.network.toCoreNetwork(),
): Result<SingleAddressInfoResult> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
trezorService.getAddressInfo(
address = address,
electrumUrl = currentElectrumUrl(),
network = network,
)
}.onFailure { e ->
Logger.error("Trezor getAddressInfo failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
@Suppress("LongParameterList")
suspend fun composeTransaction(
extendedKey: String,
outputs: List<ComposeOutput>,
feeRates: List<Float>,
network: BitkitCoreNetwork,
accountType: AccountType?,
coinSelection: CoinSelection,
): Result<List<ComposeResult>> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
ensureConnected()
val fingerprint = trezorService.getDeviceFingerprint()
val params = ComposeParams(
wallet = WalletParams(
extendedKey = extendedKey,
electrumUrl = currentElectrumUrl(),
fingerprint = fingerprint,
network = network,
accountType = accountType,
),
outputs = outputs,
feeRates = feeRates,
coinSelection = coinSelection,
)
trezorService.composeTransaction(params)
}.onFailure {
Logger.error("Trezor composeTransaction failed", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
suspend fun signTxFromPsbt(
psbtBase64: String,
network: TrezorCoinType?,
): Result<TrezorSignedTx> = withContext(ioDispatcher) {
runCatching {
ensureConnected()
val response = trezorService.signTxFromPsbt(psbtBase64, network)
_state.update { it.copy(error = null) }
response
}.onFailure {
Logger.error("Trezor signTxFromPsbt failed", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
suspend fun broadcastRawTx(
serializedTx: String,
): Result<String> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
trezorService.broadcastRawTx(
serializedTx = serializedTx,
electrumUrl = currentElectrumUrl(),
)
}.onFailure {
Logger.error("Trezor broadcastRawTx failed", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
suspend fun disconnect(): Result<Unit> = withContext(ioDispatcher) {
val deviceId = _state.value.connectedDeviceId()
TrezorDebugLog.log("DISCONNECT", "disconnect() called, connectedDeviceId=$deviceId")
val result = runCatching {
trezorService.disconnect()
deviceId?.let { disconnectTransportDevice(it) }
Unit
}
// Mirror the core: trezorService.disconnect() resets the session
// passphrase to the standard wallet, so reset the UI handler's wallet
// mode too. This keeps the THP path, the legacy PassphraseRequest
// callback, and the displayed mode consistent on the next (re)connect —
// a hidden wallet must be re-selected explicitly after an explicit
// disconnect. (A transient external disconnect does not call this and so
// retains the selection, matching the core's behaviour.)
trezorUiHandler.setWalletMode(TrezorWalletMode.STANDARD)
_state.update {
it.copy(connected = null, lastAddress = null, lastPublicKey = null)
}
result.onSuccess {
TrezorDebugLog.log("DISCONNECT", "disconnect() complete (credentials NOT cleared)")
}.onFailure { e ->
TrezorDebugLog.log("DISCONNECT", "FAILED: ${e.message}")
Logger.error("Trezor disconnect failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun signMessage(
path: String = DEFAULT_ADDRESS_PATH,
message: String,
coin: TrezorCoinType = TrezorCoinType.BITCOIN,
): Result<TrezorSignedMessageResponse> = withContext(ioDispatcher) {
runCatching {
ensureConnected()
val response = trezorService.signMessage(
path = path,
message = message,
coin = coin,
)
_state.update { it.copy(error = null) }
response
}.onFailure { e ->
Logger.error("Trezor signMessage failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun verifyMessage(
address: String,
signature: String,
message: String,
coin: TrezorCoinType = TrezorCoinType.BITCOIN,
): Result<Boolean> = withContext(ioDispatcher) {
runCatching {
ensureConnected()
val result = trezorService.verifyMessage(
address = address,
signature = signature,
message = message,
coin = coin,
)
_state.update { it.copy(error = null) }
result
}.onFailure { e ->
Logger.error("Trezor verifyMessage failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
fun hasKnownDevices(): Boolean = _state.value.knownDevices.isNotEmpty()
suspend fun hasKnownDevice(deviceId: String): Boolean = withContext(ioDispatcher) {
_state.value.knownDevices.any { it.matches(deviceId) } ||
loadKnownDevices().any { it.matches(deviceId) }
}
suspend fun autoReconnect(
walletIndex: Int = 0,
preferredTransport: TransportType? = null,
): Result<TrezorFeatures> = withContext(ioDispatcher) {
if (isConnectInProgress()) {
// A live handshake looks like a stale session (transport connected,
// features pending), so resetting here would drop the session the
// user is entering their PIN or pairing code into.
return@withContext Result.failure(AppError("Connect already in progress"))
}
val knownDevices = _state.value.knownDevices.ifEmpty { loadKnownDevices() }
if (knownDevices.isEmpty()) {
return@withContext Result.failure(AppError("No known devices"))
}
_state.update { it.copy(isAutoReconnecting = true, error = null) }
runCatching {
awaitSetup(walletIndex)
val cachedFeatures = if (trezorService.isConnected()) _state.value.connectedDevice() else null
if (cachedFeatures != null) {
cachedFeatures
} else {
if (trezorService.isConnected()) {
// The transport dropped underneath the session (e.g. bluetooth was
// toggled), so reset it before a fresh scan and connect.
runCatching { trezorService.disconnect() }
}
val scannedDevices = scan().getOrThrow().filter { it.canAutoReconnect() }
val knownIds = knownDevices.map { it.id }.toSet()
val usbDevice = scannedDevices.find {
it.transportType == TrezorTransportType.USB && it.id in knownIds
}
val idMatch = knownDevices.firstNotNullOfOrNull { known ->
scannedDevices.find { it.id == known.id }
}
// Prefer the transport that just came back, so e.g. a USB replug does
// not reconnect over BLE when the same device is known on both.
val preferredMatch = preferredTransport?.let { preferred ->
scannedDevices.find {
it.id in knownIds && it.transportType.toTransportType() == preferred
}
}
val match = preferredMatch ?: idMatch ?: usbDevice
?: throw AppError("No known device found nearby")
connect(match.id, requestUsbPermission = false).getOrThrow()
}
}.onSuccess {
_state.update { it.copy(isAutoReconnecting = false) }
}.onFailure { e ->
Logger.error("Auto-reconnect failed", e, context = TAG)
_state.update { it.copy(isAutoReconnecting = false, error = trezorErrorMessage(e)) }
}
}
private fun TrezorDeviceInfo.canAutoReconnect(): Boolean {
if (transportType.toTransportType() != TransportType.USB) return true
if (trezorTransport.hasUsbPermission(path)) return true
Logger.info("Skipped USB auto-reconnect without permission for '$path'", context = TAG)
return false
}
suspend fun connectKnownDevice(
deviceId: String,
forceSession: Boolean = false,
allowBleFallback: Boolean = true,
): Result<TrezorFeatures> = withContext(ioDispatcher) {
if (isConnectInProgress()) {
return@withContext Result.failure(AppError("Connection already in progress"))
}
var startedConnecting = false
try {
runSuspendCatching {
startedConnecting = true
_state.update { it.copy(isConnecting = true, error = null) }
Logger.debug("Started known-device reconnect for '$deviceId'", context = TAG)
Logger.debug("Awaiting setup for reconnect", context = TAG)
awaitSetup()
Logger.debug("Completed setup for reconnect", context = TAG)
if (forceSession) {
Logger.debug("Closing stale session before reconnect for '$deviceId'", context = TAG)
disconnectStaleSession(deviceId)
}
Logger.debug("Scanning for reconnect devices", context = TAG)
val knownDevices = (_state.value.knownDevices + loadKnownDevices()).distinctBy { it.id }
val knownDevice = knownDevices.find { it.matches(deviceId) }
val device = resolveKnownReconnectDevice(deviceId, knownDevice, allowBleFallback)
Logger.debug("Found reconnect device '${device.id}'", context = TAG)
Logger.debug("Calling THP reconnect for '${device.id}'", context = TAG)
val features = connectWithThpRetry(device.id, trezorUiHandler.currentSelection())
Logger.debug("Connected known device '${device.id}'", context = TAG)
addOrUpdateKnownDevice(device, features)
_state.update { it.copy(connected = ConnectedTrezorDevice(id = device.id, features = features)) }
Logger.info("Reconnected known device '${device.id}'", context = TAG)
features
}.onFailure { e ->
Logger.error("Connect known device failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
if (!forceSession) {
disconnectStaleSession(deviceId)
}
}
} finally {
if (startedConnecting) {
_state.update { it.copy(isConnecting = false) }
}
}
}
suspend fun ensureConnected(deviceId: String): Result<TrezorFeatures> = withContext(ioDispatcher) {
awaitConnectedOrNull(deviceId)?.let { return@withContext Result.success(it) }
if (isKnownBluetoothDevice(deviceId)) {
return@withContext reconnectKnownBluetoothDevice(deviceId)
}
connectKnownDevice(deviceId, forceSession = true)
}
/**
* BLE Trezors often need a few seconds to advertise again after unlock, so retry
* with growing delays (same cadence as [retryAutoReconnect]) instead of failing on
* the first empty scan or a premature direct-address connect.
*/
private suspend fun reconnectKnownBluetoothDevice(deviceId: String): Result<TrezorFeatures> {
var lastFailure: Throwable? = null
repeat(TRANSPORT_RESTORED_MAX_ATTEMPTS) { attempt ->
if (attempt > 0) {
delay(TRANSPORT_RESTORED_RECONNECT_DELAY * attempt)
}
awaitConnectedOrNull(deviceId)?.let { return Result.success(it) }
val allowBleFallback = attempt == TRANSPORT_RESTORED_MAX_ATTEMPTS - 1
val result = connectKnownDevice(
deviceId = deviceId,
forceSession = attempt == 0,
allowBleFallback = allowBleFallback,
)
if (result.isSuccess) return result
val failure = result.exceptionOrNull()
if (failure?.isTrezorUserCancellation() == true) {
return Result.failure(failure)
}
lastFailure = failure
}
return Result.failure(lastFailure ?: AppError("Failed to connect"))
}
suspend fun isKnownBluetoothDevice(deviceId: String): Boolean = withContext(ioDispatcher) {
(_state.value.knownDevices + loadKnownDevices()).distinctBy { it.id }
.any { it.matches(deviceId) && it.transportType == TransportType.BLUETOOTH }
}
fun deriveWalletId(xpubs: Map<String, String>): String? =
deriveHardwareWalletId(xpubs)?.takeIf { it.isNotBlank() }
private suspend fun connectedFeatures(deviceId: String): TrezorFeatures? {
val current = _state.value.connected
return if (current?.id == deviceId && trezorService.isConnected()) current.features else null
}
private suspend fun awaitConnectedOrNull(deviceId: String): TrezorFeatures? {
connectedFeatures(deviceId)?.let { return it }
if (isConnectInProgress()) {
awaitInFlightConnect(deviceId)
connectedFeatures(deviceId)?.let { return it }
}
return null
}
private suspend fun awaitInFlightConnect(deviceId: String) {
transportReconnectJob?.takeIf { it.isActive }?.join()
waitForConnectAttempt(deviceId)
}
private suspend fun waitForConnectAttempt(deviceId: String) {
runCatching {
withTimeout(CONNECT_ATTEMPT_MAX_WAIT) {
while (true) {
if (connectedFeatures(deviceId) != null) return@withTimeout
if (!isConnectInProgress()) return@withTimeout
delay(CONNECT_ATTEMPT_POLL_INTERVAL)
}
}
}.onFailure {
if (it is CancellationException && it !is TimeoutCancellationException) throw it
}
}
private suspend fun resolveKnownReconnectDevice(
deviceId: String,
knownDevice: KnownDevice?,
allowBleFallback: Boolean = true,
): TrezorDeviceInfo = findKnownDeviceInScan(deviceId, knownDevice, allowBleFallback)
private suspend fun findKnownDeviceInScan(
deviceId: String,
knownDevice: KnownDevice?,
allowBleFallback: Boolean,
): TrezorDeviceInfo {
val scannedDevices = trezorService.scan()
Logger.debug(
"Found '${scannedDevices.size}' reconnect devices '${scannedDevices.map { it.id }}'",
context = TAG,
)
scannedDevices.find { it.id == deviceId }?.let { return it }
if (allowBleFallback) {
knownDevice?.takeIf { it.transportType == TransportType.BLUETOOTH }?.toDeviceInfo()?.let { return it }
}
throw AppError("Device not found nearby — is it powered on?")
}
suspend fun forgetDevice(deviceId: String): Result<Unit> = withContext(ioDispatcher) {
runCatching {
TrezorDebugLog.log("FORGET", "forgetDevice called for: $deviceId")
val disconnectResult = if (_state.value.connectedDeviceId() == deviceId) {
runCatching {
trezorService.disconnect()
disconnectTransportDevice(deviceId)
}.also {
// Clear any cached host passphrase so it can't be reused
// against a different device on a later connect.
trezorUiHandler.setWalletMode(TrezorWalletMode.STANDARD)
_state.update { it.copy(connected = null) }
}
} else {
Result.success(Unit)
}
TrezorDebugLog.log("FORGET", "Clearing credentials...")
trezorTransport.clearDeviceCredential(deviceId)
val clearCredentialsResult = runCatching { trezorService.clearCredentials(deviceId) }
val knownDevices = (_state.value.knownDevices + loadKnownDevices()).distinctBy { it.id }
val updated = knownDevices.filter { it.id != deviceId }
saveKnownDevices(updated)
_state.update { it.copy(knownDevices = updated.toImmutableList()) }
clearCredentialsResult.getOrThrow()
disconnectResult.onFailure {
TrezorDebugLog.log("FORGET", "Ignored disconnect failure: ${it.message}")
Logger.warn("Ignored disconnect failure while forgetting device '$deviceId'", it, context = TAG)
}
TrezorDebugLog.log("FORGET", "Device forgotten successfully")
Logger.info("Forgot device: '$deviceId'", context = TAG)
}.onFailure { e ->
TrezorDebugLog.log("FORGET", "FAILED: ${e.message}")
Logger.error("Forget device failed", e, context = TAG)
_state.update { it.copy(error = trezorErrorMessage(e)) }
}
}
suspend fun startWatcher(
watcherId: String,
extendedKey: String,
network: BitkitCoreNetwork,
gapLimit: UInt = 20u,
accountType: AccountType? = null,
electrumUrl: String = electrumUrlForNetwork(network),
walletId: String,
): Result<Unit> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
val params = WatcherParams(
watcherId = watcherId,
walletId = walletId,
extendedKey = extendedKey,
electrumUrl = electrumUrl,
network = network,
accountType = accountType,
gapLimit = gapLimit,
)
trezorService.startWatcher(params, eventBridge)
TrezorDebugLog.log(WATCHER_TAG, "Started watcher '$watcherId' for '${extendedKey.take(12)}...'")
Logger.info("Started watcher '$watcherId'", context = TAG)
}.onFailure {
Logger.error("Start watcher failed", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
suspend fun stopWatcher(watcherId: String): Result<Unit> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
trezorService.stopWatcher(watcherId)
TrezorDebugLog.log(WATCHER_TAG, "Stopped watcher '$watcherId'")
Logger.info("Stopped watcher '$watcherId'", context = TAG)
}.onFailure {
Logger.error("Stop watcher failed", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
fun stopWatcherOnCleared(watcherId: String) {
scope.launch { stopWatcher(watcherId) }
}
suspend fun stopAllWatchers(): Result<Unit> = withContext(ioDispatcher) {
runCatching {
awaitSetup()
trezorService.stopAllWatchers()
TrezorDebugLog.log(WATCHER_TAG, "Stopped all watchers")
}.onFailure {
Logger.error("Stop all watchers failed", it, context = TAG)
_state.update { s -> s.copy(error = trezorErrorMessage(it)) }
}
}
fun clearError() {
_state.update { it.copy(error = null) }
}
private fun observeExternalDisconnects() {
trezorTransport.externalDisconnect.onEach { path ->
val currentId = _state.value.connectedDeviceId() ?: return@onEach
val knownDevice = _state.value.knownDevices.find { it.path == path }
if (knownDevice?.id == currentId || path.contains(currentId)) {
Logger.warn("External disconnect detected for '$currentId'", context = TAG)
_state.update {
it.copy(connected = null, error = "Device disconnected")
}
}
}.launchIn(scope)
}
/**
* Silently reconnects to a known device when its transport comes back: stored THP
* credentials make the connect prompt-free, so the link indicator recovers on its
* own after Bluetooth is re-enabled or the device is plugged back in.
*/
private fun observeTransportRestored() {
trezorTransport.transportRestored.onEach {
launchTransportReconnect(it)
}.launchIn(scope)
}
/**
* Triggers the silent reconnect for transport events delivered through UI intents,
* e.g. the USB attach intent the OS app picker routes to the activity (attach is
* not broadcast to receivers, unlike detach).
*/
fun onTransportRestored(transportType: TransportType) = launchTransportReconnect(transportType)
fun onAppForegrounded() {
scope.launch {
if (_state.value.connected != null || isConnectInProgress()) return@launch
val knownDevices = _state.value.knownDevices.ifEmpty { loadKnownDevices() }
if (knownDevices.none { it.transportType == TransportType.BLUETOOTH }) return@launch
Logger.info("Attempting bluetooth auto-reconnect after app foregrounded", context = TAG)
launchTransportReconnect(TransportType.BLUETOOTH)
}
}
/** Pre-connects one known BLE Trezor before the transfer sign screen asks for it. */
fun warmUpKnownDevice(deviceId: String) {
scope.launch {
if (connectedFeatures(deviceId) != null) return@launch
if (isConnectInProgress()) return@launch
if (!hasKnownDevice(deviceId)) return@launch
if (!isKnownBluetoothDevice(deviceId)) return@launch
Logger.info("Warming up known bluetooth device '$deviceId'", context = TAG)
ensureConnected(deviceId).onFailure {
Logger.debug("Warm up connect failed for '$deviceId'", context = TAG)
}
}
}
/**
* Serializes reconnect triggers into one in-flight retry loop. A Trezor
* re-enumerates USB during its unlock flow, so a single replug delivers several
* attach intents; letting each spawn its own loop staggers connect attempts for
* many seconds, and every attempt restarts the device's PIN entry.
*/
private fun launchTransportReconnect(transportType: TransportType) {
if (transportReconnectJob?.isActive == true) return
transportReconnectJob = scope.launch { retryAutoReconnect(transportType) }
}
/**
* A device is often not discoverable right after its transport returns (a BLE
* Trezor takes a few seconds to advertise again), so retry the silent reconnect
* with growing delays instead of giving up on the first empty scan.
*/
private suspend fun retryAutoReconnect(transportType: TransportType) {
repeat(TRANSPORT_RESTORED_MAX_ATTEMPTS) { attempt ->
if (_state.value.connected != null || isConnectInProgress()) return
delay(TRANSPORT_RESTORED_RECONNECT_DELAY * (attempt + 1))
// A connect may have started while this attempt was waiting.
if (_state.value.connected != null || isConnectInProgress()) return
Logger.info("Attempting auto-reconnect after transport restored, attempt '${attempt + 1}'", context = TAG)
if (autoReconnect(preferredTransport = transportType).isSuccess) return
}
}
private fun isConnectInProgress(): Boolean = run {
val current = _state.value
current.isConnecting ||
current.isAutoReconnecting ||
needsPinEntry.value ||
needsPairingCode.value
}
private suspend fun addOrUpdateKnownDevice(deviceInfo: TrezorDeviceInfo, features: TrezorFeatures) {
val stored = hwWalletStore.loadKnownDevices()
val storedIds = stored.map { it.id }.toSet()
val knownDevices = stored + _state.value.knownDevices.filter { it.id !in storedIds }