From e93f0b6df290b0c6d2cc6be583574e6635c96d77 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:52:14 +0100 Subject: [PATCH 1/3] test: drive jade flows with the bitkit-docker emulator Verified: JadeEmulatorTransportTest and JadeTransportTest pass; dev debug on an emulator paired, verified and signed a send against the jade emulator --- app/build.gradle.kts | 8 ++ .../bitkit/services/JadeEmulatorTransport.kt | 132 ++++++++++++++++++ .../java/to/bitkit/services/JadeTransport.kt | 32 +++-- .../services/JadeEmulatorTransportTest.kt | 77 ++++++++++ .../to/bitkit/services/JadeTransportTest.kt | 5 +- journeys/hardware-wallet/README.md | 26 +++- .../hardware-wallet/jade-connect-sign.xml | 48 +++++++ 7 files changed, 315 insertions(+), 13 deletions(-) create mode 100644 app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt create mode 100644 app/src/test/java/to/bitkit/services/JadeEmulatorTransportTest.kt create mode 100644 journeys/hardware-wallet/jade-connect-sign.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8f15f629e9..dd4f41983d 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -143,6 +143,8 @@ val pubkySwapsProvidersEnv = providers.environmentVariable("PUBKY_SWAPS_PROVIDER val paykitUiDisabledEnv = envFlag("PAYKIT_UI_DISABLED", default = false) val trezorBridgeEnv = localProp("TREZOR_BRIDGE").map { it.toBoolean().toString() }.orElse("false") val trezorBridgeUrlEnv = localProp("TREZOR_BRIDGE_URL").orElse("http://10.0.2.2:21325") +val jadeEmulatorEnv = localProp("JADE_EMULATOR").map { it.toBoolean().toString() }.orElse("false") +val jadeEmulatorUrlEnv = localProp("JADE_EMULATOR_URL").orElse("10.0.2.2:30121") val networkPerFlavor = mapOf("dev" to "REGTEST", "mainnet" to "BITCOIN", "tnet" to "TESTNET") val requestedNdkVersion = providers.environmentVariable("NDK_VERSION").orNull?.takeIf { it.isNotBlank() } val androidTestAnnotationPackage = "to.bitkit.test.annotations" @@ -441,6 +443,12 @@ androidComponents { } buildConfigFields.put("TREZOR_BRIDGE", trezorBridgeEnv.booleanField()) buildConfigFields.put("TREZOR_BRIDGE_URL", trezorBridgeUrlEnv.stringField()) + val isDebug = variant.buildType == "debug" + buildConfigFields.put( + "JADE_EMULATOR", + (if (isDebug) jadeEmulatorEnv else provider { "false" }).booleanField(), + ) + buildConfigFields.put("JADE_EMULATOR_URL", jadeEmulatorUrlEnv.stringField()) buildConfigFields.put("FEATURE_PAYKIT_UI_DISABLED", paykitUiDisabledEnv.booleanField()) buildConfigFields.put("LOCALES", provider { bcp47Locales.joinToString(",") }.stringField()) buildConfigFields.put( diff --git a/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt b/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt new file mode 100644 index 0000000000..24ba6241ff --- /dev/null +++ b/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt @@ -0,0 +1,132 @@ +package to.bitkit.services + +import com.synonym.bitkitcore.JadeNativeDevice +import com.synonym.bitkitcore.JadeTransportErrorCode +import com.synonym.bitkitcore.JadeTransportKind +import com.synonym.bitkitcore.JadeTransportReadResult +import com.synonym.bitkitcore.JadeTransportResult +import to.bitkit.BuildConfig +import to.bitkit.utils.Logger +import java.io.IOException +import java.net.InetSocketAddress +import java.net.Socket +import java.net.SocketTimeoutException +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Serial over TCP to the Jade QEMU emulator from bitkit-docker (`jade-emulator`), so the Jade flows + * run without a device. Debug builds only, behind `JADE_EMULATOR`; the device shows up in scans as + * one more serial Jade at a `tcp:` path. + */ +@Singleton +class JadeEmulatorTransport( + private val address: String, + private val enabled: Boolean, +) { + @Inject + constructor() : this( + address = BuildConfig.JADE_EMULATOR_URL, + enabled = BuildConfig.JADE_EMULATOR, + ) + + companion object { + private const val TAG = "JadeEmulatorTransport" + private const val PATH_PREFIX = "tcp:" + private const val DEVICE_NAME = "Jade Emulator" + private const val CONNECT_TIMEOUT_MS = 3_000 + private const val READ_TIMEOUT_MAX_MS = 1_000L + private const val READ_BUFFER_BYTES = 4_096 + } + + private val path = "$PATH_PREFIX$address" + private val sockets = ConcurrentHashMap() + + fun isEmulatorPath(path: String): Boolean = enabled && path.startsWith(PATH_PREFIX) + + /** Lists the emulator only while its port answers, so a stopped container is not offered. */ + fun scanDevices(): List { + if (!enabled) return emptyList() + if (!sockets.containsKey(path) && !isReachable()) return emptyList() + return listOf( + JadeNativeDevice(path = path, transport = JadeTransportKind.SERIAL, name = DEVICE_NAME, serialNumber = null) + ) + } + + fun openDevice(path: String): JadeTransportResult { + closeDevice(path) + return runCatching { + val socket = connect() + socket.tcpNoDelay = true + sockets[path] = socket + Logger.info("Opened Jade emulator '$path'", context = TAG) + ok() + }.getOrElse { + Logger.warn("Failed to open Jade emulator '$path'", it, context = TAG) + fail(it.message ?: "Emulator connect failed", JadeTransportErrorCode.NOT_CONNECTED) + } + } + + fun closeDevice(path: String): JadeTransportResult { + sockets.remove(path)?.let { socket -> + runCatching { socket.close() } + Logger.info("Closed Jade emulator '$path'", context = TAG) + } + return ok() + } + + fun closeAll() = sockets.keys.toList().forEach { closeDevice(it) } + + fun writeChunk(path: String, data: ByteArray): JadeTransportResult { + val socket = sockets[path] ?: return fail("Device not open: '$path'", JadeTransportErrorCode.NOT_CONNECTED) + return try { + socket.getOutputStream().apply { + write(data) + flush() + } + ok() + } catch (e: IOException) { + Logger.warn("Jade emulator write failed", e, context = TAG) + fail(e.message ?: "Emulator write failed", JadeTransportErrorCode.DISCONNECTED) + } + } + + fun readChunk(path: String, timeoutMs: UInt): JadeTransportReadResult { + val socket = sockets[path] + ?: return readFail("Device not open: '$path'", JadeTransportErrorCode.NOT_CONNECTED) + return try { + socket.soTimeout = timeoutMs.toLong().coerceIn(1L, READ_TIMEOUT_MAX_MS).toInt() + val buffer = ByteArray(READ_BUFFER_BYTES) + when (val read = socket.getInputStream().read(buffer)) { + -1 -> readFail("Jade emulator closed the connection", JadeTransportErrorCode.DISCONNECTED) + else -> readOk(buffer.copyOf(read)) + } + } catch (_: SocketTimeoutException) { + // Nothing received yet is the normal state while the device works or waits. + readOk(byteArrayOf()) + } catch (e: IOException) { + Logger.warn("Jade emulator read failed", e, context = TAG) + readFail(e.message ?: "Emulator read failed", JadeTransportErrorCode.DISCONNECTED) + } + } + + private fun isReachable(): Boolean = runCatching { connect().close() }.isSuccess + + private fun connect(): Socket { + val host = address.substringBeforeLast(':') + val port = address.substringAfterLast(':').toInt() + return Socket().apply { connect(InetSocketAddress(host, port), CONNECT_TIMEOUT_MS) } + } + + private fun ok() = JadeTransportResult(success = true, error = "", errorCode = null) + + private fun fail(error: String, code: JadeTransportErrorCode?) = + JadeTransportResult(success = false, error = error, errorCode = code) + + private fun readOk(data: ByteArray) = + JadeTransportReadResult(success = true, data = data, error = "", errorCode = null) + + private fun readFail(error: String, code: JadeTransportErrorCode?) = + JadeTransportReadResult(success = false, data = byteArrayOf(), error = error, errorCode = code) +} diff --git a/app/src/main/java/to/bitkit/services/JadeTransport.kt b/app/src/main/java/to/bitkit/services/JadeTransport.kt index d515f44573..ec57d149dc 100644 --- a/app/src/main/java/to/bitkit/services/JadeTransport.kt +++ b/app/src/main/java/to/bitkit/services/JadeTransport.kt @@ -62,6 +62,7 @@ import javax.inject.Singleton @Singleton class JadeTransport @Inject constructor( @ApplicationContext private val context: Context, + private val emulatorTransport: JadeEmulatorTransport, ) : JadeTransportCallback { companion object { @@ -272,6 +273,7 @@ class JadeTransport @Inject constructor( fun isJadeUsbDevice(device: UsbDevice): Boolean = device.hwUsbId()?.vendor == HwWalletVendor.BLOCKSTREAM fun hasUsbPermission(devicePath: String): Boolean { + if (emulatorTransport.isEmulatorPath(devicePath)) return true val device = usbManager.deviceList[devicePath] ?: return false return usbManager.hasPermission(device) } @@ -283,6 +285,7 @@ class JadeTransport @Inject constructor( fun disconnectDevice(path: String): JadeTransportResult = closeDevice(path) fun closeAllConnections() { + emulatorTransport.closeAll() usbConnections.keys.toList().forEach { closeUsbDevice(it) } bleConnections.keys.toList().forEach { disconnectBleDevice(it) } } @@ -293,6 +296,7 @@ class JadeTransport @Inject constructor( override fun scanDevices(timeoutMs: UInt): List { val devices = mutableListOf() + devices.addAll(emulatorTransport.scanDevices()) runCatching { scanUsbDevices() } .onSuccess { @@ -316,17 +320,29 @@ class JadeTransport @Inject constructor( return devices } - override fun openDevice(path: String): JadeTransportResult = - if (path.isBlePath()) openBleDevice(path) else openUsbDevice(path) + override fun openDevice(path: String): JadeTransportResult = when { + emulatorTransport.isEmulatorPath(path) -> emulatorTransport.openDevice(path) + path.isBlePath() -> openBleDevice(path) + else -> openUsbDevice(path) + } - override fun closeDevice(path: String): JadeTransportResult = - if (path.isBlePath()) disconnectBleDevice(path) else closeUsbDevice(path) + override fun closeDevice(path: String): JadeTransportResult = when { + emulatorTransport.isEmulatorPath(path) -> emulatorTransport.closeDevice(path) + path.isBlePath() -> disconnectBleDevice(path) + else -> closeUsbDevice(path) + } - override fun writeChunk(path: String, data: ByteArray): JadeTransportResult = - if (path.isBlePath()) writeBleChunk(path, data) else writeUsbChunk(path, data) + override fun writeChunk(path: String, data: ByteArray): JadeTransportResult = when { + emulatorTransport.isEmulatorPath(path) -> emulatorTransport.writeChunk(path, data) + path.isBlePath() -> writeBleChunk(path, data) + else -> writeUsbChunk(path, data) + } - override fun readChunk(path: String, timeoutMs: UInt): JadeTransportReadResult = - if (path.isBlePath()) readBleChunk(path, timeoutMs) else readUsbChunk(path, timeoutMs) + override fun readChunk(path: String, timeoutMs: UInt): JadeTransportReadResult = when { + emulatorTransport.isEmulatorPath(path) -> emulatorTransport.readChunk(path, timeoutMs) + path.isBlePath() -> readBleChunk(path, timeoutMs) + else -> readUsbChunk(path, timeoutMs) + } override fun getChunkSize(path: String): UInt = when { path.isBlePath() -> chunkSizeForMtu(bleConnections[path]?.mtu ?: DEFAULT_ATT_MTU) diff --git a/app/src/test/java/to/bitkit/services/JadeEmulatorTransportTest.kt b/app/src/test/java/to/bitkit/services/JadeEmulatorTransportTest.kt new file mode 100644 index 0000000000..3c4d620a1c --- /dev/null +++ b/app/src/test/java/to/bitkit/services/JadeEmulatorTransportTest.kt @@ -0,0 +1,77 @@ +package to.bitkit.services + +import com.synonym.bitkitcore.JadeTransportKind +import org.junit.After +import org.junit.Test +import java.net.ServerSocket +import kotlin.concurrent.thread +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class JadeEmulatorTransportTest { + private val server = ServerSocket(0) + private val address = "127.0.0.1:${server.localPort}" + + @After + fun tearDown() { + server.close() + } + + @Test + fun `scan lists nothing when disabled`() { + val sut = JadeEmulatorTransport(address = address, enabled = false) + + assertTrue(sut.scanDevices().isEmpty()) + assertFalse(sut.isEmulatorPath("tcp:$address")) + } + + @Test + fun `scan lists nothing when the emulator port is closed`() { + server.close() + val sut = JadeEmulatorTransport(address = address, enabled = true) + + assertTrue(sut.scanDevices().isEmpty()) + } + + @Test + fun `scan lists the emulator as a serial device`() { + thread { server.accept().close() } + val sut = JadeEmulatorTransport(address = address, enabled = true) + + val devices = sut.scanDevices() + + assertEquals(1, devices.size) + assertEquals("tcp:$address", devices.single().path) + assertEquals(JadeTransportKind.SERIAL, devices.single().transport) + } + + @Test + fun `written bytes reach the emulator and its reply is read back`() { + val path = "tcp:$address" + thread { + server.accept().use { client -> + val request = ByteArray(3) + client.getInputStream().read(request) + client.getOutputStream().write(request.reversedArray()) + } + } + val sut = JadeEmulatorTransport(address = address, enabled = true) + + assertTrue(sut.openDevice(path).success) + assertTrue(sut.writeChunk(path, byteArrayOf(1, 2, 3)).success) + val read = sut.readChunk(path, 1_000u) + + assertTrue(read.success) + assertContentEquals(byteArrayOf(3, 2, 1), read.data) + assertTrue(sut.closeDevice(path).success) + } + + @Test + fun `read before open fails`() { + val sut = JadeEmulatorTransport(address = address, enabled = true) + + assertFalse(sut.readChunk("tcp:$address", 10u).success) + } +} diff --git a/app/src/test/java/to/bitkit/services/JadeTransportTest.kt b/app/src/test/java/to/bitkit/services/JadeTransportTest.kt index ff832374cb..f71b49014f 100644 --- a/app/src/test/java/to/bitkit/services/JadeTransportTest.kt +++ b/app/src/test/java/to/bitkit/services/JadeTransportTest.kt @@ -347,7 +347,10 @@ class JadeTransportTest { return waiters } - private fun createSut() = JadeTransport(context = context) + private fun createSut() = JadeTransport( + context = context, + emulatorTransport = JadeEmulatorTransport(address = "127.0.0.1:1", enabled = false), + ) private fun usbDevice( vendorId: Int, diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index d3df5dea47..55f24e9099 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -80,6 +80,7 @@ the other three rely on, and `passphrase-settings-remove.xml` removes it again. | `transfer-to-spending-node-warmup.xml` | Transfer started during app/node warm-up; verifies loading recovers into the sign screen | | `send-onchain.xml` | Normal Send flow funded by Trezor: source selection, guarded preparation, device signing, broadcast, success, and activity | | `scan-onchain-amount-over-spendable.xml` | Scanned on-chain amount the Trezor balance covers but not after fees: Insufficient Savings toast instead of a locked Amount screen | +| `jade-connect-sign.xml` | Jade emulator: Hardware suggestion → Found (PIN hint) → Paired, receive-address verification, send signed with Jade | | `receive-onchain.xml` | Trezor Receive tab: current address and QR display plus exact on-device address verification | | `passphrase-pairing.xml` | Passphrase button on Paired → Enter Passphrase → Passphrase Funds Found; second home tile, own label, no passphrase in logs | | `passphrase-duplicate.xml` | Re-entering a watched passphrase reports "already added" and adds no tile | @@ -145,7 +146,24 @@ the amount entered. ## Blockstream Jade -There is no Jade emulator in `bitkit-docker`, so the Jade flows (Connect Hardware over USB or -Bluetooth, receive-address verification and on-device signing) are covered by unit tests -(`JadeRepoTest.kt`, `JadeTransportTest.kt`, `HwWalletRepoTest.kt`) and by manual runs against a -physical Jade. The journeys in this folder stay Trezor-only. +`jade-connect-sign.xml` drives the Jade flows (Found with the PIN hint, Paired, receive-address +verification, Sign With Jade) against the Jade emulator from `bitkit-docker`: official 1.0.41 +firmware under QEMU, seeded with `all all ... all`, locked behind a PIN, serial over TCP on port +30121. The firmware enters its PIN and confirms every prompt itself, so nothing is pressed on the +device. + +1. Start it from a sibling `bitkit-docker` checkout: + ```sh + ../bitkit-docker/scripts/jade-emulator start + ``` +2. Build the dev debug app with `JADE_EMULATOR=true` in `local.properties`. An Android emulator + reaches it at the default `JADE_EMULATOR_URL=10.0.2.2:30121`; for a physical phone run + `../bitkit-docker/scripts/jade-emulator adb` and set `JADE_EMULATOR_URL=127.0.0.1:30121`. +3. The emulator then shows up as a Jade in the Connect Hardware flow, next to USB and Bluetooth + devices. + +The seed is the Trezor emulator's, so the Jade sees the same regtest history and funds. Each +`start` wipes the device back to that seed and PIN; `JADE_MNEMONIC=` (empty) leaves it +uninitialised. USB and Bluetooth transports, typing the PIN on the device, a wrong PIN and the +device's own screens still need a physical Jade; unit tests (`JadeRepoTest.kt`, +`JadeTransportTest.kt`, `JadeEmulatorTransportTest.kt`, `HwWalletRepoTest.kt`) cover the rest. diff --git a/journeys/hardware-wallet/jade-connect-sign.xml b/journeys/hardware-wallet/jade-connect-sign.xml new file mode 100644 index 0000000000..a127799067 --- /dev/null +++ b/journeys/hardware-wallet/jade-connect-sign.xml @@ -0,0 +1,48 @@ + + + Pairs the Blockstream Jade emulator from `bitkit-docker` through the Hardware suggestion card, + verifies a receive address on the device and pays from the Jade through the normal Send flow. + Requires `./scripts/jade-emulator start` (seeded, PIN-locked device on port 30121), a regtest + debug build with the Jade emulator enabled (see the README), a wallet with no Jade paired, and + funds on the Jade's regtest addresses. The emulator enters its PIN and confirms every prompt + itself. + + + + Launch the Bitkit app and go to the wallet home screen + + + Scroll the home screen until the card titled "Hardware" with the text "Connect device" (testTag "Suggestion-hardware") is visible, and tap it + + + Tap "Continue" (testTag "HardwareWalletIntroContinue"); if the system asks for Nearby devices or Bluetooth permission, allow it + + + Verify the "Found Device" step (testTag "HardwareWalletFoundScreen") appears within 15 seconds, headed "Found Jade" with Jade device artwork and a "Connect" button + + + Tap "Connect" (testTag "HardwareWalletFoundConnect") and verify the hint "Enter your PIN on your Jade to unlock it." (testTag "HwFoundUnlockHint") shows while the device unlocks (on the emulator this can last under a second, so a missed hint is not a failure when the next step follows) + + + Verify the "Device Connected" step (testTag "HardwareWalletPairedScreen") headed "Paired Jade" appears within 30 seconds, with a balance and a "Label Funds" field (testTag "HardwareWalletLabelInput") reading "Jade" + + + Tap "Finish" (testTag "HardwareWalletPairedFinish") and verify the home screen shows the Jade tile (testTag "ActivityHardware") with a green connection indicator + + + Tap Receive (testTag "Receive"), select the "Jade" tab (testTag "Tab-jade"), tap "Show Details" if the address is hidden behind it, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify no error appears and the shown address starts with "bcrt1" + + + Close the receive sheet. Tap Send (testTag "Send"), enter a regtest address of the bitkit-docker node manually, and on the amount screen select the Jade as the funding source (testTag "AssetButton-switch") + + + Enter an amount below the Jade's available balance, tap Continue (testTag "ContinueAmount"), verify the FROM field (testTag "SendConfirmAssetButton") shows the Jade, and swipe to confirm + + + Verify the hardware sign screen shows the amount (testTag "HardwareSendAmount"), the destination address (testTag "HardwareSendAddress") and a "Sign With Jade" button (testTag "HardwareSendOpenTrezorConnect"), then tap it + + + Verify the payment broadcasts and the success screen (testTag "SendSuccess") appears within 30 seconds, then close it and verify the payment appears once in recent activity with the blue hardware-wallet icon + + + From 83af1c81a83605b4fd0dfd75785dddd30ab68e47 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 22:01:36 +0100 Subject: [PATCH 2/3] test: cover every jade flow with emulator journeys Adds a journey for each hardware__jade_* error the app can reach, for signing on the device and for a passphrase wallet. Keeps the Found step's wrong PIN message while the next scan finds the same Jade, and closes the emulator socket when a connect fails. Verified: just compile, just test and just lint pass --- .../bitkit/services/JadeEmulatorTransport.kt | 9 ++++-- .../ui/sheets/hardware/HwConnectViewModel.kt | 2 +- .../sheets/hardware/HwConnectViewModelTest.kt | 16 +++++++++++ changelog.d/next/2049.fixed.md | 1 + journeys/README.md | 1 + journeys/hardware-wallet/README.md | 20 +++++++++++-- .../hardware-wallet/jade-connect-sign.xml | 2 +- .../hardware-wallet/jade-device-locked.xml | 28 +++++++++++++++++++ .../hardware-wallet/jade-network-mismatch.xml | 21 ++++++++++++++ journeys/hardware-wallet/jade-passphrase.xml | 24 ++++++++++++++++ .../hardware-wallet/jade-psbt-too-large.xml | 26 +++++++++++++++++ .../hardware-wallet/jade-sign-on-device.xml | 26 +++++++++++++++++ .../hardware-wallet/jade-uninitialized.xml | 21 ++++++++++++++ .../hardware-wallet/jade-wallet-mismatch.xml | 22 +++++++++++++++ journeys/hardware-wallet/jade-wrong-pin.xml | 28 +++++++++++++++++++ 15 files changed, 240 insertions(+), 7 deletions(-) create mode 100644 changelog.d/next/2049.fixed.md create mode 100644 journeys/hardware-wallet/jade-device-locked.xml create mode 100644 journeys/hardware-wallet/jade-network-mismatch.xml create mode 100644 journeys/hardware-wallet/jade-passphrase.xml create mode 100644 journeys/hardware-wallet/jade-psbt-too-large.xml create mode 100644 journeys/hardware-wallet/jade-sign-on-device.xml create mode 100644 journeys/hardware-wallet/jade-uninitialized.xml create mode 100644 journeys/hardware-wallet/jade-wallet-mismatch.xml create mode 100644 journeys/hardware-wallet/jade-wrong-pin.xml diff --git a/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt b/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt index 24ba6241ff..2c2fd7491a 100644 --- a/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt +++ b/app/src/main/java/to/bitkit/services/JadeEmulatorTransport.kt @@ -87,7 +87,7 @@ class JadeEmulatorTransport( } ok() } catch (e: IOException) { - Logger.warn("Jade emulator write failed", e, context = TAG) + Logger.warn("Failed to write to Jade emulator", e, context = TAG) fail(e.message ?: "Emulator write failed", JadeTransportErrorCode.DISCONNECTED) } } @@ -106,7 +106,7 @@ class JadeEmulatorTransport( // Nothing received yet is the normal state while the device works or waits. readOk(byteArrayOf()) } catch (e: IOException) { - Logger.warn("Jade emulator read failed", e, context = TAG) + Logger.warn("Failed to read from Jade emulator", e, context = TAG) readFail(e.message ?: "Emulator read failed", JadeTransportErrorCode.DISCONNECTED) } } @@ -116,7 +116,10 @@ class JadeEmulatorTransport( private fun connect(): Socket { val host = address.substringBeforeLast(':') val port = address.substringAfterLast(':').toInt() - return Socket().apply { connect(InetSocketAddress(host, port), CONNECT_TIMEOUT_MS) } + val socket = Socket() + return runCatching { socket.apply { connect(InetSocketAddress(host, port), CONNECT_TIMEOUT_MS) } } + .onFailure { runCatching { socket.close() } } + .getOrThrow() } private fun ok() = JadeTransportResult(success = true, error = "", errorCode = null) diff --git a/app/src/main/java/to/bitkit/ui/sheets/hardware/HwConnectViewModel.kt b/app/src/main/java/to/bitkit/ui/sheets/hardware/HwConnectViewModel.kt index 3744507274..da2aeb66c8 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/hardware/HwConnectViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/hardware/HwConnectViewModel.kt @@ -97,7 +97,7 @@ class HwConnectViewModel @Inject constructor( foundDeviceId = deviceId, deviceModel = deviceModel.ifBlank { resolveHwWalletName(label = null, model = null, vendor = vendor) }, vendor = vendor, - errorMessage = null, + errorMessage = if (it.foundDeviceId == deviceId) it.errorMessage else null, ) } scanUsbBeforeConnect = deviceId.startsWith(USB_DEVICE_PATH_PREFIX) diff --git a/app/src/test/java/to/bitkit/ui/sheets/hardware/HwConnectViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/hardware/HwConnectViewModelTest.kt index e8bf46cabc..470894a166 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/hardware/HwConnectViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/hardware/HwConnectViewModelTest.kt @@ -33,6 +33,7 @@ import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @@ -217,6 +218,21 @@ class HwConnectViewModelTest : BaseUnitTest() { assertEquals("dev1", sut.uiState.value.foundDeviceId) } + @Test + fun `onFoundRoute keeps the connect error when it reopens the same device`() = test { + givenDeviceFound() + runCurrent() + whenever(hwWalletRepo.connect("dev1")).thenReturn(Result.failure(AppError("connect failed"))) + sut.onConnectClick() + runCurrent() + + sut.onFoundRoute(deviceId = "dev1", deviceModel = "Trezor Safe 5") + assertEquals(CONNECT_ERROR, sut.uiState.value.errorMessage) + + sut.onFoundRoute(deviceId = "dev2", deviceModel = "Trezor Safe 5") + assertNull(sut.uiState.value.errorMessage) + } + @Test fun `cancelConnect cancels the pending jade transport operation`() = test { val pending = CompletableDeferred>() diff --git a/changelog.d/next/2049.fixed.md b/changelog.d/next/2049.fixed.md new file mode 100644 index 0000000000..8a7d3d5e29 --- /dev/null +++ b/changelog.d/next/2049.fixed.md @@ -0,0 +1 @@ +Fixed the wrong PIN message on the Found Jade step disappearing when the next scan found the same Jade. diff --git a/journeys/README.md b/journeys/README.md index 43ff20d0ff..b8b14c5925 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -130,6 +130,7 @@ journey PR, which is what made this file conflict on every merge. | Lightning channels | Manual Setup to the staging LSP node, which the dev flavor targets — [Backend preconditions](#backend-preconditions) | | A private inbound Lightning channel, receipt and amountless invoice from local LND | The pinned local-regtest [Send2 fixture](amount-limits/README.md#spending-immediately-after-a-lightning-receipt) starts Bitcoin, Electrum and LND and funds the Android wallet over that channel. | | A hardware wallet to pair, watch and sign with | the deterministic Trezor emulator from `bitkit-docker` over the Bridge transport, with the USB attach intent injected by `adb`; USB enumeration, permission grants, the OS picker and BLE are not simulated — [hardware-wallet](hardware-wallet/README.md) | +| A Jade to pair, unlock, verify and sign with | the Jade emulator from `bitkit-docker` (`./scripts/jade-emulator`) over serial over TCP; `press`, `pin` and `passphrase` drive its buttons, PIN pad and passphrase keyboard, and its recipes reach each `hardware__jade_*` error the app can show; Bluetooth, USB and the camera (QR mode) are not covered — [hardware-wallet](hardware-wallet/README.md) | | An incoming Payment Request from a linked issuer | the fixture issuer, saved as a contact and linked as identities — [payment-requests](payment-requests/README.md) | | Two linked Bitkit wallets for a subscription lifecycle | a second Bitkit instance linked to the first, so a proposal can be reviewed and accepted — [subscriptions](subscriptions) | | A Pubky identity and a two-wallet marketplace purchase | the integration fixture runtime: Pubky testnet, Paykit Server, regtest bitcoind and Fulcrum — [pubky-marketplace](pubky-marketplace/README.md) | diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index 55f24e9099..95cca5216d 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -81,6 +81,14 @@ the other three rely on, and `passphrase-settings-remove.xml` removes it again. | `send-onchain.xml` | Normal Send flow funded by Trezor: source selection, guarded preparation, device signing, broadcast, success, and activity | | `scan-onchain-amount-over-spendable.xml` | Scanned on-chain amount the Trezor balance covers but not after fees: Insufficient Savings toast instead of a locked Amount screen | | `jade-connect-sign.xml` | Jade emulator: Hardware suggestion → Found (PIN hint) → Paired, receive-address verification, send signed with Jade | +| `jade-uninitialized.xml` | Jade emulator with no wallet: Found shows the not-set-up message | +| `jade-wrong-pin.xml` | Interactive Jade emulator: wrong PIN on the device → Found shows the wrong-PIN message, retry pairs | +| `jade-network-mismatch.xml` | Jade emulator restricted to mainnet: Found shows the network message | +| `jade-device-locked.xml` | Interactive Jade logged out on the device after pairing: Verify on Device shows the busy message | +| `jade-psbt-too-large.xml` | Jade with about 200 small inputs: sending all of it shows the too-large message | +| `jade-sign-on-device.xml` | Interactive Jade: decline on the device keeps the payment unsent, approve sends it | +| `jade-wallet-mismatch.xml` | Paired Jade reseeded: Verify on Device shows the different-wallet message | +| `jade-passphrase.xml` | Interactive Jade asking for a passphrase: pairing adds the passphrase wallet next to the Jade's own | | `receive-onchain.xml` | Trezor Receive tab: current address and QR display plus exact on-device address verification | | `passphrase-pairing.xml` | Passphrase button on Paired → Enter Passphrase → Passphrase Funds Found; second home tile, own label, no passphrase in logs | | `passphrase-duplicate.xml` | Re-entering a watched passphrase reports "already added" and adds no tile | @@ -164,6 +172,14 @@ device. The seed is the Trezor emulator's, so the Jade sees the same regtest history and funds. Each `start` wipes the device back to that seed and PIN; `JADE_MNEMONIC=` (empty) leaves it -uninitialised. USB and Bluetooth transports, typing the PIN on the device, a wrong PIN and the -device's own screens still need a physical Jade; unit tests (`JadeRepoTest.kt`, +uninitialised. USB and Bluetooth transports still need a physical Jade; unit tests (`JadeRepoTest.kt`, `JadeTransportTest.kt`, `JadeEmulatorTransportTest.kt`, `HwWalletRepoTest.kt`) cover the rest. + +The error journeys start the emulator in another state first: `jade-uninitialized.xml` +(`JADE_MNEMONIC=`), `jade-wrong-pin.xml` (`JADE_MODE=interactive`, where the device shows its +own PIN pad and `./scripts/jade-emulator pin` types on it) and `jade-network-mismatch.xml` +(`JADE_NETWORK=mainnet`), and `jade-device-locked.xml` logs the interactive device out after +pairing (Android reports the locked Jade as busy; iOS asks for the PIN on the device again and retries, +so its copy of the journey checks that); `jade-psbt-too-large.xml` needs the app on the bitkit-docker Electrum and about 200 small +inputs on the Jade. `jade-sign-on-device.xml` declines and then approves a payment on the interactive +device's own screens. `jade-wallet-mismatch.xml` restarts the emulator with another seed after pairing. `jade-passphrase.xml` starts it with `JADE_PASSPHRASE=always` and pairs the wallet a passphrase typed on the device opens (`./scripts/jade-emulator passphrase`). The bitkit-docker `docs/jade-emulator.md` lists the modes and recipes. diff --git a/journeys/hardware-wallet/jade-connect-sign.xml b/journeys/hardware-wallet/jade-connect-sign.xml index a127799067..c04d70384d 100644 --- a/journeys/hardware-wallet/jade-connect-sign.xml +++ b/journeys/hardware-wallet/jade-connect-sign.xml @@ -30,7 +30,7 @@ Tap "Finish" (testTag "HardwareWalletPairedFinish") and verify the home screen shows the Jade tile (testTag "ActivityHardware") with a green connection indicator - Tap Receive (testTag "Receive"), select the "Jade" tab (testTag "Tab-jade"), tap "Show Details" if the address is hidden behind it, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify no error appears and the shown address starts with "bcrt1" + Tap Receive (testTag "Receive"), select the "Jade" tab (testTag "Tab-hardware"), tap "Show Details" if the address is hidden behind it, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify no error appears and the shown address starts with "bcrt1" Close the receive sheet. Tap Send (testTag "Send"), enter a regtest address of the bitkit-docker node manually, and on the amount screen select the Jade as the funding source (testTag "AssetButton-switch") diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml new file mode 100644 index 0000000000..f67eb0e352 --- /dev/null +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -0,0 +1,28 @@ + + + Logs the paired Jade out on the device itself and checks the message the app shows when it + next needs the Jade. Requires `JADE_MODE=interactive ./scripts/jade-emulator start` in + `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README) and no + Jade paired. The device answers the next request with HW_LOCKED, which the app reports as busy. + + + + Launch the Bitkit app and go to the wallet home screen + + + Open the menu (testTag "HeaderMenu"), tap Settings (testTag "DrawerSettings"), tap "Hardware Wallets" (testTag "HardwareWalletsSettings") and tap "Add Hardware Wallet" (testTag "AddHardwareWallet") + + + Tap "Continue" (testTag "HardwareWalletIntroContinue") and verify the "Found Device" step (testTag "HardwareWalletFoundScreen") headed "Found Jade" appears within 15 seconds + + + Tap "Connect" (testTag "HardwareWalletFoundConnect"), run `./scripts/jade-emulator pin 012345` in `bitkit-docker`, verify the "Device Connected" step (testTag "HardwareWalletPairedScreen") appears within 30 seconds and tap "Finish" (testTag "HardwareWalletPairedFinish") + + + Run `./scripts/jade-emulator press front right front` in `bitkit-docker` to choose Session, then Log Out, on the device + + + Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify a toast reads "Your Jade is busy. Finish what is shown on the device, then try again." + + + diff --git a/journeys/hardware-wallet/jade-network-mismatch.xml b/journeys/hardware-wallet/jade-network-mismatch.xml new file mode 100644 index 0000000000..4a9d9d9e46 --- /dev/null +++ b/journeys/hardware-wallet/jade-network-mismatch.xml @@ -0,0 +1,21 @@ + + + Connects a Jade emulator restricted to mainnet from a regtest build and checks the Found step's + message. Requires `JADE_NETWORK=mainnet ./scripts/jade-emulator start` in `bitkit-docker`, a + regtest debug build with the Jade emulator enabled (see the README) and no Jade paired. + + + + Launch the Bitkit app and go to the wallet home screen + + + Open the menu (testTag "HeaderMenu"), tap Settings (testTag "DrawerSettings"), tap "Hardware Wallets" (testTag "HardwareWalletsSettings") and tap "Add Hardware Wallet" (testTag "AddHardwareWallet") + + + Tap "Continue" (testTag "HardwareWalletIntroContinue") and verify the "Found Device" step (testTag "HardwareWalletFoundScreen") headed "Found Jade" appears within 15 seconds + + + Tap "Connect" (testTag "HardwareWalletFoundConnect") and verify that within 30 seconds the Found step shows "Your Jade is set up for a different Bitcoin network." (testTag "HwFoundError") + + + diff --git a/journeys/hardware-wallet/jade-passphrase.xml b/journeys/hardware-wallet/jade-passphrase.xml new file mode 100644 index 0000000000..0cd0e87ab0 --- /dev/null +++ b/journeys/hardware-wallet/jade-passphrase.xml @@ -0,0 +1,24 @@ + + + Pairs the wallet a BIP39 passphrase typed on the Jade emulator opens, next to the Jade's own wallet. + Requires `JADE_MODE=interactive JADE_PASSPHRASE=always ./scripts/jade-emulator start` in + `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README) and the + Jade's own wallet already paired from an earlier start without `JADE_PASSPHRASE` (the seed stays + the same across starts). The device asks for a passphrase after every PIN; + `./scripts/jade-emulator passphrase` types one on its keyboard and confirms it. + + + + Launch the Bitkit app, open the menu (testTag "HeaderMenu"), tap Settings (testTag "DrawerSettings"), tap "Hardware Wallets" (testTag "HardwareWalletsSettings") and tap "Add Hardware Wallet" (testTag "AddHardwareWallet") + + + Tap "Continue" (testTag "HardwareWalletIntroContinue"), then "Connect" (testTag "HardwareWalletFoundConnect") on the "Found Jade" step + + + Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator passphrase test` in `bitkit-docker`, and verify the "Device Connected" step (testTag "HardwareWalletPairedScreen") headed "Paired Jade" appears within 30 seconds with a balance of 0 + + + Tap "Finish" (testTag "HardwareWalletPairedFinish"), open Settings → "Hardware Wallets" again and verify two Jade wallets are listed: the one paired before, with its balance, and the new one at 0 + + + diff --git a/journeys/hardware-wallet/jade-psbt-too-large.xml b/journeys/hardware-wallet/jade-psbt-too-large.xml new file mode 100644 index 0000000000..a2d8f52baa --- /dev/null +++ b/journeys/hardware-wallet/jade-psbt-too-large.xml @@ -0,0 +1,26 @@ + + + Sends the whole balance of a Jade whose funds sit in many small inputs and checks the message + for a transaction too large to sign. Requires `./scripts/jade-emulator start` in + `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README) and a + paired Jade. Settings, Advanced, Electrum Server must point at the `bitkit-docker` Electrum, + and the Jade's receive address must hold about 200 inputs: run + `for i in $(seq 200); do ./bitcoin-cli sendtoaddress 0.0002; done; ./bitcoin-cli -generate 1` + in `bitkit-docker`. Over the client's 16 KiB PSBT limit, Bitkit refuses before the device + sees the transaction. + + + + Launch the Bitkit app and verify the home screen shows the Jade tile (testTag "ActivityHardware") with a balance of at least 4 000 000 sats + + + Tap Send (testTag "Send"), enter a regtest address of the bitkit-docker node manually, select the Jade as the funding source on the amount screen (testTag "AssetButton-switch") and tap the available balance (testTag "AvailableAmount") to send all of it + + + Tap Continue (testTag "ContinueAmount"), swipe to confirm, and confirm the dialog about sending over half the balance if it appears + + + Tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") and verify an error toast reads "This transaction is too large for Jade to sign. Try sending a smaller amount." and no payment appears in recent activity + + + diff --git a/journeys/hardware-wallet/jade-sign-on-device.xml b/journeys/hardware-wallet/jade-sign-on-device.xml new file mode 100644 index 0000000000..6dbce4f991 --- /dev/null +++ b/journeys/hardware-wallet/jade-sign-on-device.xml @@ -0,0 +1,26 @@ + + + Declines and then approves a payment on the Jade emulator's own screens. Requires + `JADE_MODE=interactive ./scripts/jade-emulator start` in `bitkit-docker`, a regtest debug + build with the Jade emulator enabled (see the README), a paired Jade and funds on the Jade's + regtest addresses. The device shows one Output screen per output and then Send Transaction + with the fee, where X is selected; `./scripts/jade-emulator screen` saves what it shows. + + + + Launch the Bitkit app and go to the wallet home screen + + + Tap Send (testTag "Send"), enter a regtest address of the bitkit-docker node manually, select the Jade as the funding source on the amount screen (testTag "AssetButton-switch"), enter 50 000 sats and tap Continue (testTag "ContinueAmount") + + + Swipe to confirm and verify the hardware sign screen shows "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect"), then tap it + + + If the device asks for its PIN, run `./scripts/jade-emulator pin 012345` in `bitkit-docker`. Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press front` again to choose X on Send Transaction, and verify the app stays on the sign screen with no payment sent + + + Tap "Sign With Jade" again, run `./scripts/jade-emulator press front`, then `./scripts/jade-emulator press right front` to sign, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds + + + diff --git a/journeys/hardware-wallet/jade-uninitialized.xml b/journeys/hardware-wallet/jade-uninitialized.xml new file mode 100644 index 0000000000..028d22a5b0 --- /dev/null +++ b/journeys/hardware-wallet/jade-uninitialized.xml @@ -0,0 +1,21 @@ + + + Connects a Jade emulator with no wallet on it and checks that the Found step names the problem. + Requires `JADE_MNEMONIC= ./scripts/jade-emulator start` in `bitkit-docker`, a regtest debug + build with the Jade emulator enabled (see the README) and no Jade paired. + + + + Launch the Bitkit app and go to the wallet home screen + + + Open the menu (testTag "HeaderMenu"), tap Settings (testTag "DrawerSettings"), tap "Hardware Wallets" (testTag "HardwareWalletsSettings") and tap "Add Hardware Wallet" (testTag "AddHardwareWallet") + + + Tap "Continue" (testTag "HardwareWalletIntroContinue") and verify the "Found Device" step (testTag "HardwareWalletFoundScreen") headed "Found Jade" appears within 15 seconds + + + Tap "Connect" (testTag "HardwareWalletFoundConnect") and verify that within 30 seconds the Found step shows "This Jade has not been set up yet. Create or restore a wallet on the device, then try again." (testTag "HwFoundError") and a "Connect" button to retry + + + diff --git a/journeys/hardware-wallet/jade-wallet-mismatch.xml b/journeys/hardware-wallet/jade-wallet-mismatch.xml new file mode 100644 index 0000000000..adbd84ae74 --- /dev/null +++ b/journeys/hardware-wallet/jade-wallet-mismatch.xml @@ -0,0 +1,22 @@ + + + Reseeds the paired Jade emulator and checks the message when the app reaches the device again. + Requires a regtest debug build with the Jade emulator enabled (see the README) and the Jade + from `./scripts/jade-emulator start` already paired. The emulator keeps its hardware id across a + restart, as a wiped and restored Jade does. + + + + Run `JADE_MNEMONIC="abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" ./scripts/jade-emulator start` in `bitkit-docker` + + + Launch the Bitkit app, tap Receive (testTag "Receive"), select the Jade tab and tap "Show Details" if the address is hidden behind it + + + Tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify an error toast reads "This device holds a different wallet than the one you paired. Connect the paired wallet, or add this one as a new hardware wallet." + + + Run `./scripts/jade-emulator start` in `bitkit-docker` to restore the paired seed, tap "Verify on Device" again and verify no error appears + + + diff --git a/journeys/hardware-wallet/jade-wrong-pin.xml b/journeys/hardware-wallet/jade-wrong-pin.xml new file mode 100644 index 0000000000..34bbe41557 --- /dev/null +++ b/journeys/hardware-wallet/jade-wrong-pin.xml @@ -0,0 +1,28 @@ + + + Enters a wrong PIN on the Jade emulator's own PIN pad and checks the Found step's message. + Requires `JADE_MODE=interactive ./scripts/jade-emulator start` in `bitkit-docker`, a regtest + debug build with the Jade emulator enabled (see the README) and no Jade paired. The emulator + shows its PIN pad and waits for buttons; `./scripts/jade-emulator pin` enters a PIN. + + + + Launch the Bitkit app and go to the wallet home screen + + + Open the menu (testTag "HeaderMenu"), tap Settings (testTag "DrawerSettings"), tap "Hardware Wallets" (testTag "HardwareWalletsSettings") and tap "Add Hardware Wallet" (testTag "AddHardwareWallet") + + + Tap "Continue" (testTag "HardwareWalletIntroContinue") and verify the "Found Device" step (testTag "HardwareWalletFoundScreen") headed "Found Jade" appears within 15 seconds + + + Tap "Connect" (testTag "HardwareWalletFoundConnect") and verify the hint "Enter your PIN on your Jade to unlock it." (testTag "HwFoundUnlockHint") shows + + + Run `./scripts/jade-emulator pin 999999` in `bitkit-docker` and verify that within 30 seconds the Found step shows "Wrong PIN. Try again on your Jade." (testTag "HwFoundError") + + + Tap "Connect" again, run `./scripts/jade-emulator pin 012345` (it first presses Continue on the device's "Incorrect PIN!" screen), and verify the "Device Connected" step (testTag "HardwareWalletPairedScreen") headed "Paired Jade" appears within 30 seconds + + + From 9f5af34a79b181b78628253944d4792e78f1166f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 23:06:37 +0100 Subject: [PATCH 3/3] fix: reconnect the jade emulator after it restarts A closed emulator socket now reports the Jade as disconnected, as a USB detach or dropped Bluetooth link does, so the next request reconnects instead of reusing a dead session. Verified: just compile, just test and just lint pass; on an emulator a send signed after the Jade emulator restarted under the app --- .../java/to/bitkit/services/JadeTransport.kt | 13 ++++++-- .../to/bitkit/services/JadeTransportTest.kt | 33 ++++++++++++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/JadeTransport.kt b/app/src/main/java/to/bitkit/services/JadeTransport.kt index ec57d149dc..a5418fe1d5 100644 --- a/app/src/main/java/to/bitkit/services/JadeTransport.kt +++ b/app/src/main/java/to/bitkit/services/JadeTransport.kt @@ -333,13 +333,15 @@ class JadeTransport @Inject constructor( } override fun writeChunk(path: String, data: ByteArray): JadeTransportResult = when { - emulatorTransport.isEmulatorPath(path) -> emulatorTransport.writeChunk(path, data) + emulatorTransport.isEmulatorPath(path) -> + emulatorTransport.writeChunk(path, data).also { onEmulatorResult(path, it.errorCode) } path.isBlePath() -> writeBleChunk(path, data) else -> writeUsbChunk(path, data) } override fun readChunk(path: String, timeoutMs: UInt): JadeTransportReadResult = when { - emulatorTransport.isEmulatorPath(path) -> emulatorTransport.readChunk(path, timeoutMs) + emulatorTransport.isEmulatorPath(path) -> + emulatorTransport.readChunk(path, timeoutMs).also { onEmulatorResult(path, it.errorCode) } path.isBlePath() -> readBleChunk(path, timeoutMs) else -> readUsbChunk(path, timeoutMs) } @@ -951,6 +953,13 @@ class JadeTransport @Inject constructor( } } + /** A closed emulator socket counts as the device going away, as a USB detach or BLE drop does. */ + private fun onEmulatorResult(path: String, errorCode: JadeTransportErrorCode?) { + if (errorCode != JadeTransportErrorCode.DISCONNECTED) return + emulatorTransport.closeDevice(path) + emitExternalDisconnect(path) + } + private fun emitExternalDisconnect(path: String) { if (!userInitiatedCloseSet.remove(path)) { _externalDisconnect.tryEmit(path) diff --git a/app/src/test/java/to/bitkit/services/JadeTransportTest.kt b/app/src/test/java/to/bitkit/services/JadeTransportTest.kt index f71b49014f..5f62b9457b 100644 --- a/app/src/test/java/to/bitkit/services/JadeTransportTest.kt +++ b/app/src/test/java/to/bitkit/services/JadeTransportTest.kt @@ -11,7 +11,11 @@ import android.hardware.usb.UsbInterface import android.hardware.usb.UsbManager import com.synonym.bitkitcore.JadeTransportErrorCode import com.synonym.bitkitcore.JadeTransportKind +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout import org.junit.Before import org.junit.Test import org.mockito.kotlin.any @@ -23,8 +27,10 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import java.net.ServerSocket import java.util.concurrent.CountDownLatch import java.util.concurrent.LinkedBlockingQueue +import kotlin.concurrent.thread import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -64,6 +70,26 @@ class JadeTransportTest { verify(usbManager, never()).requestPermission(eq(device), any()) } + @Test + fun `a closed emulator socket reports the jade as disconnected`() { + ServerSocket(0).use { server -> + val path = "tcp:127.0.0.1:${server.localPort}" + thread { server.accept().close() } + val sut = createSut(JadeEmulatorTransport(address = "127.0.0.1:${server.localPort}", enabled = true)) + assertTrue(sut.openDevice(path).success) + + val disconnected = runBlocking { + val event = async(start = CoroutineStart.UNDISPATCHED) { sut.externalDisconnect.first() } + val read = sut.readChunk(path, 1_000u) + assertEquals(JadeTransportErrorCode.DISCONNECTED, read.errorCode) + withTimeout(1_000) { event.await() } + } + + assertEquals(path, disconnected) + assertEquals(JadeTransportErrorCode.NOT_CONNECTED, sut.readChunk(path, 10u).errorCode) + } + } + @Test fun `scanDevices can skip the bluetooth scan`() { val sut = createSut() @@ -347,10 +373,9 @@ class JadeTransportTest { return waiters } - private fun createSut() = JadeTransport( - context = context, - emulatorTransport = JadeEmulatorTransport(address = "127.0.0.1:1", enabled = false), - ) + private fun createSut( + emulatorTransport: JadeEmulatorTransport = JadeEmulatorTransport(address = "127.0.0.1:1", enabled = false), + ) = JadeTransport(context = context, emulatorTransport = emulatorTransport) private fun usbDevice( vendorId: Int,