-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTrezorRepo.kt
More file actions
653 lines (608 loc) · 26.5 KB
/
Copy pathTrezorRepo.kt
File metadata and controls
653 lines (608 loc) · 26.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
package to.bitkit.repositories
import android.content.Context
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import com.synonym.bitkitcore.AccountInfoResult
import com.synonym.bitkitcore.AccountType
import com.synonym.bitkitcore.CoinSelection
import com.synonym.bitkitcore.ComposeOutput
import com.synonym.bitkitcore.ComposeParams
import com.synonym.bitkitcore.ComposeResult
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 dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import to.bitkit.data.TrezorStore
import to.bitkit.di.IoDispatcher
import to.bitkit.env.Env
import to.bitkit.models.toCoreNetwork
import to.bitkit.services.TrezorDebugLog
import to.bitkit.services.TrezorService
import to.bitkit.services.TrezorTransport
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import java.io.File
import javax.inject.Inject
import javax.inject.Singleton
import com.synonym.bitkitcore.Network as BitkitCoreNetwork
@Suppress("TooManyFunctions")
@Singleton
class TrezorRepo @Inject constructor(
@ApplicationContext private val context: Context,
private val trezorService: TrezorService,
private val trezorTransport: TrezorTransport,
private val trezorStore: TrezorStore,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
companion object {
private const val TAG = "TrezorRepo"
private const val DEFAULT_ADDRESS_PATH = "m/84'/0'/0'/0/0"
private const val DEFAULT_ACCOUNT_PATH = "m/84'/0'/0'"
}
private val _state = MutableStateFlow(TrezorState())
val state = _state.asStateFlow()
/**
* 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()
}
suspend fun initialize(walletIndex: Int = 0): Result<Unit> = withContext(ioDispatcher) {
runCatching {
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(isInitialized = true, knownDevices = known.toImmutableList(), error = null) }
}.onFailure { e ->
Logger.error("Trezor init failed", e, context = TAG)
_state.update { it.copy(error = e.message) }
}
}
suspend fun scan(): Result<List<TrezorDeviceInfo>> = withContext(ioDispatcher) {
runCatching {
_state.update { it.copy(isScanning = true, error = null) }
val devices = trezorService.scan()
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 = e.message) }
}
}
suspend fun listDevices(): Result<List<TrezorDeviceInfo>> = withContext(ioDispatcher) {
runCatching {
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 = e.message) }
}
}
suspend fun connect(deviceId: String): Result<TrezorFeatures> = withContext(ioDispatcher) {
runCatching {
_state.update { it.copy(isConnecting = true, error = null) }
TrezorDebugLog.log("CONNECT", "connect() called for deviceId=$deviceId")
val features = connectWithThpRetry(deviceId)
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 = e.message) }
}
}
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 = e.message) }
}
}
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 = e.message) }
}
}
suspend fun getTransactionHistory(
extendedKey: String,
network: BitkitCoreNetwork = Env.network.toCoreNetwork(),
scriptType: AccountType? = null,
): Result<TransactionHistoryResult> = withContext(ioDispatcher) {
runCatching {
trezorService.getTransactionHistory(
extendedKey = extendedKey,
electrumUrl = electrumUrlForNetwork(network),
network = network,
scriptType = scriptType,
)
}.onFailure {
Logger.error("Failed to get Trezor transaction history", it, context = TAG)
_state.update { s -> s.copy(error = it.message) }
}
}
suspend fun getAccountInfo(
extendedKey: String,
network: BitkitCoreNetwork = Env.network.toCoreNetwork(),
scriptType: AccountType? = null,
): Result<AccountInfoResult> = withContext(ioDispatcher) {
runCatching {
trezorService.getAccountInfo(
extendedKey = extendedKey,
electrumUrl = electrumUrlForNetwork(network),
network = network,
scriptType = scriptType,
)
}.onFailure { e ->
Logger.error("Trezor getAccountInfo failed", e, context = TAG)
_state.update { it.copy(error = e.message) }
}
}
suspend fun getAddressInfo(
address: String,
network: BitkitCoreNetwork = Env.network.toCoreNetwork(),
): Result<SingleAddressInfoResult> = withContext(ioDispatcher) {
runCatching {
trezorService.getAddressInfo(
address = address,
electrumUrl = electrumUrlForNetwork(network),
network = network,
)
}.onFailure { e ->
Logger.error("Trezor getAddressInfo failed", e, context = TAG)
_state.update { it.copy(error = e.message) }
}
}
@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 {
val fingerprint = trezorService.getDeviceFingerprint()
val params = ComposeParams(
wallet = WalletParams(
extendedKey = extendedKey,
electrumUrl = electrumUrlForNetwork(network),
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 = it.message) }
}
}
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 = it.message) }
}
}
suspend fun broadcastRawTx(
serializedTx: String,
network: BitkitCoreNetwork,
): Result<String> = withContext(ioDispatcher) {
runCatching {
trezorService.broadcastRawTx(
serializedTx = serializedTx,
electrumUrl = electrumUrlForNetwork(network),
)
}.onFailure {
Logger.error("Trezor broadcastRawTx failed", it, context = TAG)
_state.update { s -> s.copy(error = it.message) }
}
}
suspend fun disconnect(): Result<Unit> = withContext(ioDispatcher) {
TrezorDebugLog.log("DISCONNECT", "disconnect() called, connectedDeviceId=${_state.value.connectedDeviceId}")
val result = runCatching { trezorService.disconnect() }
_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 = e.message) }
}
}
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 = e.message) }
}
}
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 = e.message) }
}
}
fun hasKnownDevices(): Boolean = _state.value.knownDevices.isNotEmpty()
suspend fun autoReconnect(walletIndex: Int = 0): Result<TrezorFeatures> = withContext(ioDispatcher) {
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 {
if (!_state.value.isInitialized) {
initialize(walletIndex).getOrThrow()
}
if (trezorService.isConnected()) {
_state.value.connectedDevice ?: throw AppError("Connected but no features")
} else {
val scannedDevices = scan().getOrThrow()
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 }
}
val match = idMatch ?: usbDevice ?: throw AppError("No known device found nearby")
connect(match.id).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 = e.message) }
}
}
suspend fun connectKnownDevice(deviceId: String): Result<TrezorFeatures> = withContext(ioDispatcher) {
if (_state.value.isConnecting) {
return@withContext Result.failure(AppError("Connection already in progress"))
}
runCatching {
_state.update { it.copy(isConnecting = true, error = null) }
TrezorDebugLog.log("RECONNECT", "=== connectKnownDevice START ===")
TrezorDebugLog.log("RECONNECT", "deviceId=$deviceId")
TrezorDebugLog.log("RECONNECT", "isInitialized=${_state.value.isInitialized}")
if (!_state.value.isInitialized) {
TrezorDebugLog.log("RECONNECT", "Initializing...")
initialize().getOrThrow()
TrezorDebugLog.log("RECONNECT", "Initialized OK")
}
TrezorDebugLog.log("RECONNECT", "Scanning for devices...")
val scannedDevices = trezorService.scan()
TrezorDebugLog.log(
"RECONNECT",
"Scan found ${scannedDevices.size} devices: ${scannedDevices.map { it.id }}",
)
val exactMatch = scannedDevices.find { it.id == deviceId }
val knownIds = _state.value.knownDevices.map { it.id }.toSet()
val usbDevice = scannedDevices.find {
it.transportType == TrezorTransportType.USB && it.id in knownIds
}
val device = if (exactMatch?.transportType == TrezorTransportType.BLUETOOTH && usbDevice != null) {
TrezorDebugLog.log("RECONNECT", "Preferring USB over BLE")
usbDevice
} else {
exactMatch ?: throw AppError("Device not found nearby — is it powered on?")
}
TrezorDebugLog.log("RECONNECT", "Found matching device: id=${device.id}, name=${device.name}")
TrezorDebugLog.log("RECONNECT", "Calling connectWithThpRetry...")
val features = connectWithThpRetry(device.id)
TrezorDebugLog.log("RECONNECT", "Connected! label=${features.label}, model=${features.model}")
addOrUpdateKnownDevice(device, features)
_state.update {
it.copy(isConnecting = false, connected = ConnectedTrezorDevice(id = device.id, features = features))
}
TrezorDebugLog.log("RECONNECT", "=== connectKnownDevice SUCCESS ===")
features
}.onFailure { e ->
TrezorDebugLog.log("RECONNECT", "FAILED: ${e.message}")
Logger.error("Connect known device failed", e, context = TAG)
_state.update { it.copy(isConnecting = false, error = e.message) }
}
}
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() }.also {
_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 updated = _state.value.knownDevices.filter { it.id != deviceId }
saveKnownDevices(updated)
_state.update { it.copy(knownDevices = updated.toImmutableList()) }
disconnectResult.getOrThrow()
clearCredentialsResult.getOrThrow()
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 = e.message) }
}
}
fun clearError() {
_state.update { it.copy(error = null) }
}
fun observeExternalDisconnects(scope: CoroutineScope) {
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)
}
private suspend fun addOrUpdateKnownDevice(deviceInfo: TrezorDeviceInfo, features: TrezorFeatures) {
val existing = _state.value.knownDevices
val known = KnownDevice(
id = deviceInfo.id,
name = deviceInfo.name,
path = deviceInfo.path,
transportType = deviceInfo.transportType.toKnownTransportType(),
label = features.label ?: deviceInfo.label,
model = features.model ?: deviceInfo.model,
lastConnectedAt = System.currentTimeMillis(),
)
val updated = existing.filter { it.id != known.id } + known
saveKnownDevices(updated)
_state.update { it.copy(knownDevices = updated.toImmutableList()) }
}
private suspend fun loadKnownDevices(): List<KnownDevice> = runCatching {
trezorStore.loadKnownDevices()
}.onFailure {
Logger.error("Failed to load known devices", it, context = TAG)
}.getOrDefault(emptyList())
private suspend fun saveKnownDevices(devices: List<KnownDevice>) {
runCatching {
trezorStore.saveKnownDevices(devices)
}.onFailure { Logger.error("Failed to save known devices", it, context = TAG) }
}
private fun electrumUrlForNetwork(network: BitkitCoreNetwork): String = Env.electrumUrlForNetwork(network)
private suspend fun ensureConnected() {
if (trezorService.isConnected()) return
val deviceId = _state.value.connectedDeviceId
?: _state.value.knownDevices.firstOrNull()?.id
?: throw AppError("No device to reconnect")
if (!_state.value.isInitialized) {
initialize().getOrThrow()
}
val devices = trezorService.scan()
val device = devices.find { it.id == deviceId }
?: throw AppError("Device not found during reconnect")
val features = connectWithThpRetry(device.id)
_state.update { it.copy(connected = ConnectedTrezorDevice(id = deviceId, features = features)) }
}
suspend fun clearCredentials(deviceId: String): Result<Unit> = withContext(ioDispatcher) {
runCatching {
trezorService.clearCredentials(deviceId)
_state.update { it.copy(error = null) }
}.onFailure { e ->
Logger.error("Trezor clearCredentials failed", e, context = TAG)
_state.update { it.copy(error = e.message) }
}
}
private suspend fun connectWithThpRetry(deviceId: String): TrezorFeatures {
TrezorDebugLog.log("THPRetry", "First connect attempt for: $deviceId")
logCredentialFileState(deviceId, "BEFORE 1st attempt")
return runCatching {
trezorService.connect(deviceId)
}.onSuccess {
logCredentialFileState(deviceId, "AFTER 1st attempt (success)")
TrezorDebugLog.log("THPRetry", "First attempt succeeded")
}.getOrElse { e ->
logCredentialFileState(deviceId, "AFTER 1st attempt (failed)")
TrezorDebugLog.log("THPRetry", "First attempt failed: ${e.message}")
if (!isRetryableError(e)) {
TrezorDebugLog.log("THPRetry", "Error not retryable, throwing")
throw e
}
TrezorDebugLog.log("THPRetry", "Error is retryable, attempting second connect...")
Logger.warn("Connection failed for $deviceId, retrying", e, context = TAG)
logCredentialFileState(deviceId, "BEFORE 2nd attempt")
val result = trezorService.connect(deviceId)
logCredentialFileState(deviceId, "AFTER 2nd attempt (success)")
TrezorDebugLog.log("THPRetry", "Second attempt succeeded")
result
}
}
private fun logCredentialFileState(deviceId: String, label: String) {
val sanitizedId = deviceId.replace(":", "_").replace("/", "_")
val credDir = File(context.filesDir, "trezor-thp-credentials")
val credFile = File(credDir, "$sanitizedId.json")
val exists = credFile.exists()
val size = if (exists) credFile.length() else 0
TrezorDebugLog.log("CRED", "$label: file=$sanitizedId.json exists=$exists size=$size")
}
private fun isRetryableError(e: Throwable): Boolean {
val msg = e.message?.lowercase() ?: return false
return "thp" in msg || "session" in msg || "timeout" in msg || "disconnect" in msg
}
}
@Stable
data class TrezorState(
val isInitialized: Boolean = false,
val isScanning: Boolean = false,
val isConnecting: Boolean = false,
val isAutoReconnecting: Boolean = false,
val knownDevices: ImmutableList<KnownDevice> = persistentListOf(),
val nearbyDevices: ImmutableList<TrezorDeviceInfo> = persistentListOf(),
val connected: ConnectedTrezorDevice? = null,
val lastAddress: TrezorAddressResponse? = null,
val lastPublicKey: TrezorPublicKeyResponse? = null,
val error: String? = null,
) {
val connectedDevice: TrezorFeatures?
get() = connected?.features
val connectedDeviceId: String?
get() = connected?.id
}
@Stable
data class ConnectedTrezorDevice(
val id: String,
val features: TrezorFeatures,
)
@Serializable
@Immutable
data class KnownDevice(
val id: String,
val name: String?,
val path: String,
val transportType: KnownDeviceTransportType,
val label: String?,
val model: String?,
val lastConnectedAt: Long,
)
@Serializable
enum class KnownDeviceTransportType {
@SerialName("bluetooth")
BLUETOOTH,
@SerialName("usb")
USB,
}
private fun TrezorTransportType.toKnownTransportType(): KnownDeviceTransportType = when (this) {
TrezorTransportType.BLUETOOTH -> KnownDeviceTransportType.BLUETOOTH
TrezorTransportType.USB -> KnownDeviceTransportType.USB
}
private fun KnownDeviceTransportType.toCoreTransportType(): TrezorTransportType = when (this) {
KnownDeviceTransportType.BLUETOOTH -> TrezorTransportType.BLUETOOTH
KnownDeviceTransportType.USB -> TrezorTransportType.USB
}