From 23cfaf1652fa63088471d52765f210c7cafcdc74 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:52:14 +0100 Subject: [PATCH 01/14] test: drive jade flows with the bitkit-docker emulator Verified: debug build on a simulator paired, verified and signed a send against the jade emulator --- Bitkit/Constants/Env.swift | 10 + Bitkit/Managers/JadeManager.swift | 4 +- Bitkit/Services/Jade/JadeEmulatorLink.swift | 176 ++++++++++++++++++ Bitkit/Services/Jade/JadeTransport.swift | 40 +++- journeys/hardware-wallet/README.md | 26 ++- .../hardware-wallet/jade-connect-sign.xml | 48 +++++ 6 files changed, 292 insertions(+), 12 deletions(-) create mode 100644 Bitkit/Services/Jade/JadeEmulatorLink.swift create mode 100644 journeys/hardware-wallet/jade-connect-sign.xml diff --git a/Bitkit/Constants/Env.swift b/Bitkit/Constants/Env.swift index 3b848e994a..b7c51c5fca 100644 --- a/Bitkit/Constants/Env.swift +++ b/Bitkit/Constants/Env.swift @@ -284,6 +284,16 @@ enum Env { configValue("TREZOR_BRIDGE_URL") ?? "http://127.0.0.1:21325" } + /// Whether the Jade QEMU emulator from bitkit-docker (`jade-emulator`) replaces Bluetooth Jades. + static var jadeEmulatorEnabled: Bool { + (isDebug || isE2E) && boolConfigValue("JADE_EMULATOR") + } + + /// The emulator's serial over TCP port, as `host:port`. + static var jadeEmulatorUrl: String { + configValue("JADE_EMULATOR_URL") ?? "127.0.0.1:30121" + } + /// Basic auth (`user:password`) for Blocktank's regtest routes, read only in Debug and E2E builds. static var blocktankRegtestAuth: String? { guard isDebug || isE2E else { return nil } diff --git a/Bitkit/Managers/JadeManager.swift b/Bitkit/Managers/JadeManager.swift index 28a867365a..663b2c2921 100644 --- a/Bitkit/Managers/JadeManager.swift +++ b/Bitkit/Managers/JadeManager.swift @@ -515,10 +515,10 @@ final class JadeManager { Logger.warn("Scan before the Jade reconnect failed: \(error)", context: Self.logContext) scanned = [] } - let bluetooth = scanned.filter { $0.transport == .bluetooth } - if let exact = bluetooth.first(where: { $0.path == entry.path }) { + if let exact = scanned.first(where: { $0.path == entry.path }) { return exact } + let bluetooth = scanned.filter { $0.transport == .bluetooth } if let readvertised = bluetooth.first(where: { entry.advertisesAs($0.name) }) { return readvertised } diff --git a/Bitkit/Services/Jade/JadeEmulatorLink.swift b/Bitkit/Services/Jade/JadeEmulatorLink.swift new file mode 100644 index 0000000000..0bee21a22c --- /dev/null +++ b/Bitkit/Services/Jade/JadeEmulatorLink.swift @@ -0,0 +1,176 @@ +import BitkitCore +import Darwin +import Foundation + +/// Serial over TCP to the Jade QEMU emulator from bitkit-docker (`jade-emulator`), so the Jade flows +/// run in the simulator without a device. Debug and E2E builds only, behind `JADE_EMULATOR`; the +/// emulator shows up in scans as one more serial Jade at a `tcp:` path. +final class JadeEmulatorLink: @unchecked Sendable { + static let shared = JadeEmulatorLink(address: Env.jadeEmulatorUrl, isEnabled: { Env.jadeEmulatorEnabled }) + + static let pathPrefix = "tcp:" + private static let deviceName = "Jade Emulator" + private static let connectTimeoutMs: Int32 = 3000 + private static let readTimeoutMaxMs: UInt32 = 1000 + private static let readBufferBytes = 4096 + private static let logContext = "JadeEmulator" + + private let address: String + private let isEnabled: () -> Bool + private let lock = NSLock() + private var sockets: [String: Int32] = [:] + + init(address: String, isEnabled: @escaping () -> Bool) { + self.address = address + self.isEnabled = isEnabled + } + + var enabled: Bool { + isEnabled() + } + + private var path: String { + Self.pathPrefix + address + } + + func isEmulatorPath(_ path: String) -> Bool { + isEnabled() && path.hasPrefix(Self.pathPrefix) + } + + /// Lists the emulator only while its port answers, so a stopped container is not offered. + func scanDevices() -> [JadeNativeDevice] { + guard isEnabled() else { return [] } + if socket(for: path) == nil { + guard let probe = try? connect() else { return [] } + close(probe) + } + return [JadeNativeDevice(path: path, transport: .serial, name: Self.deviceName, serialNumber: nil)] + } + + func open(path: String) -> JadeTransportResult { + closeDevice(path: path) + do { + let fd = try connect() + lock.withLock { sockets[path] = fd } + Logger.info("Opened Jade emulator '\(path)'", context: Self.logContext) + return Self.success + } catch { + Logger.warn("Failed to open Jade emulator '\(path)': \(error)", context: Self.logContext) + return JadeTransportResult(success: false, error: "\(error)", errorCode: .notConnected) + } + } + + @discardableResult + func closeDevice(path: String) -> JadeTransportResult { + if let fd = lock.withLock({ sockets.removeValue(forKey: path) }) { + close(fd) + Logger.info("Closed Jade emulator '\(path)'", context: Self.logContext) + } + return Self.success + } + + func closeAll() { + let paths = lock.withLock { Array(sockets.keys) } + paths.forEach { closeDevice(path: $0) } + } + + func write(path: String, data: Data) -> JadeTransportResult { + guard let fd = socket(for: path) else { + return JadeTransportResult(success: false, error: "Device not open: '\(path)'", errorCode: .notConnected) + } + var offset = 0 + while offset < data.count { + let written = data.withUnsafeBytes { buffer in + send(fd, buffer.baseAddress!.advanced(by: offset), data.count - offset, 0) + } + if written <= 0 { + return JadeTransportResult(success: false, error: "Jade emulator write failed: errno \(errno)", errorCode: .disconnected) + } + offset += written + } + return Self.success + } + + func read(path: String, timeoutMs: UInt32) -> JadeTransportReadResult { + guard let fd = socket(for: path) else { + return JadeTransportReadResult(success: false, data: Data(), error: "Device not open: '\(path)'", errorCode: .notConnected) + } + var poller = pollfd(fd: fd, events: Int16(POLLIN), revents: 0) + let ready = poll(&poller, 1, Int32(min(max(timeoutMs, 1), Self.readTimeoutMaxMs))) + // Nothing received yet is the normal state while the device works or waits. + guard ready > 0 else { return JadeTransportReadResult(success: true, data: Data(), error: "", errorCode: nil) } + var buffer = [UInt8](repeating: 0, count: Self.readBufferBytes) + let count = recv(fd, &buffer, buffer.count, 0) + guard count > 0 else { + return JadeTransportReadResult(success: false, data: Data(), error: "Jade emulator closed the connection", errorCode: .disconnected) + } + return JadeTransportReadResult(success: true, data: Data(buffer[0 ..< count]), error: "", errorCode: nil) + } + + // MARK: - Helpers + + private static let success = JadeTransportResult(success: true, error: "", errorCode: nil) + + private func socket(for path: String) -> Int32? { + lock.withLock { sockets[path] } + } + + private func connect() throws -> Int32 { + guard let separator = address.lastIndex(of: ":"), let port = UInt16(address[address.index(after: separator)...]) else { + throw JadeEmulatorError.invalidAddress(address) + } + let host = String(address[..= 0 else { throw JadeEmulatorError.connectFailed(errno) } + var noSigPipe: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout.size)) + var noDelay: Int32 = 1 + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &noDelay, socklen_t(MemoryLayout.size)) + + // Connect without blocking, so a stopped emulator fails within the timeout. + let flags = fcntl(fd, F_GETFL) + _ = fcntl(fd, F_SETFL, flags | O_NONBLOCK) + let result = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) + } + } + if result != 0 { + guard errno == EINPROGRESS else { + let error = errno + close(fd) + throw JadeEmulatorError.connectFailed(error) + } + var poller = pollfd(fd: fd, events: Int16(POLLOUT), revents: 0) + var socketError: Int32 = 0 + var length = socklen_t(MemoryLayout.size) + let ready = poll(&poller, 1, Self.connectTimeoutMs) + getsockopt(fd, SOL_SOCKET, SO_ERROR, &socketError, &length) + guard ready > 0, socketError == 0 else { + close(fd) + throw JadeEmulatorError.connectFailed(ready > 0 ? socketError : ETIMEDOUT) + } + } + _ = fcntl(fd, F_SETFL, flags) + return fd + } +} + +enum JadeEmulatorError: Error, CustomStringConvertible { + case invalidAddress(String) + case connectFailed(Int32) + + var description: String { + switch self { + case let .invalidAddress(address): + "Invalid Jade emulator address '\(address)'" + case let .connectFailed(code): + "Jade emulator connect failed: \(String(cString: strerror(code)))" + } + } +} diff --git a/Bitkit/Services/Jade/JadeTransport.swift b/Bitkit/Services/Jade/JadeTransport.swift index 55a109f45b..e1f880199f 100644 --- a/Bitkit/Services/Jade/JadeTransport.swift +++ b/Bitkit/Services/Jade/JadeTransport.swift @@ -28,12 +28,20 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc private static let minimumScanDuration: TimeInterval = 0.5 private static let maximumScanDuration: TimeInterval = 15 private static let logContext = "JadeBLE" + /// jade-client-rs `MAX_CHUNK_BYTES`, which its own serial transport uses too. + private static let serialChunkSize: UInt32 = 509 private let driver: JadeBLEDriving + private let emulator: JadeEmulatorLink private let isTrezorBridgeEnabled: () -> Bool - init(driver: JadeBLEDriving, isTrezorBridgeEnabled: @escaping () -> Bool = { Env.trezorBridgeEnabled }) { + init( + driver: JadeBLEDriving, + emulator: JadeEmulatorLink = .shared, + isTrezorBridgeEnabled: @escaping () -> Bool = { Env.trezorBridgeEnabled } + ) { self.driver = driver + self.emulator = emulator self.isTrezorBridgeEnabled = isTrezorBridgeEnabled } @@ -56,14 +64,20 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc // MARK: - JadeTransportControlling func disconnectDevice(path: String) async { + if emulator.isEmulatorPath(path) { + emulator.closeDevice(path: path) + return + } await runOffMainThread { $0.close(path: path) } } func closeAllConnections() async { + emulator.closeAll() await runOffMainThread { $0.closeAll() } } func releaseAllImmediately() { + emulator.closeAll() driver.releaseAllImmediately() } @@ -74,8 +88,11 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc // MARK: - JadeTransportCallback func scanDevices(timeoutMs: UInt32) -> [JadeNativeDevice] { - // Bridge runs (journeys and E2E) have no Jade nearby, and in the simulator the central never powers - // on, so a Bluetooth scan would only add its wait to every search pass. + // Bridge and emulator runs (journeys and E2E) have no Jade nearby, and in the simulator the central + // never powers on, so a Bluetooth scan would only add its wait to every search pass. + if emulator.enabled { + return emulator.scanDevices() + } guard !isTrezorBridgeEnabled() else { Logger.debug("Skipped the Jade Bluetooth scan while the Trezor Bridge is enabled", context: Self.logContext) return [] @@ -88,6 +105,9 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc } func openDevice(path: String) -> JadeTransportResult { + if emulator.isEmulatorPath(path) { + return emulator.open(path: path) + } do { try driver.open(path: path) return Self.success @@ -97,11 +117,17 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc } func closeDevice(path: String) -> JadeTransportResult { + if emulator.isEmulatorPath(path) { + return emulator.closeDevice(path: path) + } driver.close(path: path) return Self.success } func writeChunk(path: String, data: Data) -> JadeTransportResult { + if emulator.isEmulatorPath(path) { + return emulator.write(path: path, data: data) + } do { try driver.write(path: path, data: data) return Self.success @@ -112,6 +138,9 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc } func readChunk(path: String, timeoutMs: UInt32) -> JadeTransportReadResult { + if emulator.isEmulatorPath(path) { + return emulator.read(path: path, timeoutMs: timeoutMs) + } do { let data = try driver.read(path: path, timeout: Double(timeoutMs) / 1000) return JadeTransportReadResult(success: true, data: data, error: "", errorCode: nil) @@ -121,7 +150,10 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc } func getChunkSize(path: String) -> UInt32 { - driver.chunkSize(path: path) + if emulator.isEmulatorPath(path) { + return Self.serialChunkSize + } + return driver.chunkSize(path: path) } // MARK: - Helpers diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index b25e7f2425..3c3c2fcd01 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -154,12 +154,26 @@ Broadcast faults on an ordinary send are not a journey capability; the manual re ## Blockstream Jade -There is no Jade emulator in `bitkit-docker`, and iOS reaches a Jade over Bluetooth only, which the -simulator does not have. The Jade flows (Connect Hardware, receive-address verification and on-device -signing) are therefore covered by unit tests (`JadeManagerTests.swift`, `JadeTransportTests.swift`, -`JadeBLELinkStateTests.swift`, `HwWalletManagerVendorTests.swift`, `HwConnectViewModelTests.swift`, -`HwFundingSignerTests.swift`, `HwEngagedSessionTests.swift`) and by manual runs against a physical Jade -paired with a physical iPhone. 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. A simulator has no Bluetooth LE, so this is the only way to run the Jade flows there. + +```bash +../bitkit-docker/scripts/jade-emulator start +``` + +Launch the debug app with `-JADE_EMULATOR true` (and `-JADE_EMULATOR_URL host:port` when the +simulator does not reach it at `127.0.0.1:30121`). The scan then lists only the emulator, and the +home tile reads "Connected via Bluetooth", the only transport badge iOS has. + +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. Bluetooth, typing the PIN on the device, a +wrong PIN and the device's own screens still need a physical Jade; unit tests +(`JadeManagerTests.swift`, `JadeTransportTests.swift`, `JadeBLELinkStateTests.swift`, +`HwWalletManagerVendorTests.swift`, `HwConnectViewModelTests.swift`, `HwFundingSignerTests.swift`, +`HwEngagedSessionTests.swift`) cover the rest. While a Jade waits for its PIN, the Found step shows `HwFoundUnlockHint`. The receive tab of a hardware wallet is labelled with its vendor: a Trezor wallet keeps `Tab-trezor` and a Jade reads `Tab-jade`. 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 5f33d8c9692b1ba747d87cb9d2cf75318b230fae Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 22:01:36 +0100 Subject: [PATCH 02/14] 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. Lets the emulator build skip the Bluetooth check, since it connects over TCP. Verified: unit tests pass (4586, 0 failures); SwiftFormat lint clean on the changed files --- .../Views/Sheets/HardwareConnectSheet.swift | 4 +++ journeys/README.md | 1 + journeys/hardware-wallet/README.md | 12 +++++-- .../hardware-wallet/jade-connect-sign.xml | 2 +- .../hardware-wallet/jade-device-locked.xml | 32 +++++++++++++++++++ .../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 ++++++++++++++++ 12 files changed, 216 insertions(+), 3 deletions(-) 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/Bitkit/Views/Sheets/HardwareConnectSheet.swift b/Bitkit/Views/Sheets/HardwareConnectSheet.swift index ec27c64c0c..a7d660c1e2 100644 --- a/Bitkit/Views/Sheets/HardwareConnectSheet.swift +++ b/Bitkit/Views/Sheets/HardwareConnectSheet.swift @@ -213,6 +213,10 @@ private struct HardwareConnectFlow: View { } private var isBluetoothUsable: Bool { + // The Jade emulator is reached over TCP, so a simulator without Bluetooth can still connect. + if Env.jadeEmulatorEnabled { + return true + } switch trezorManager.bluetoothState { case .poweredOn, .unknown, .resetting: return true diff --git a/journeys/README.md b/journeys/README.md index 01b2be1ead..3d7579d7a2 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -224,6 +224,7 @@ journey PR, which is what made this file conflict on every merge. | Spark emergency exit up to the swipe | a Debug build with Spark connected on its regtest and a Spark balance from Lightspark's regtest faucet; the states after the swipe take days of blocks, so they are covered by unit tests — [transfer](transfer/spark-emergency-exit.xml) | | Lightning channels | a channel opened through Manual Setup to the node of the LSP the `E2E_BUILD` app targets, as an external LN peer — [Backend preconditions](#backend-preconditions) | | A hardware wallet to pair, watch and sign with | the deterministic Trezor emulator from `bitkit-docker`, reached through Trezor Bridge on the host; the simulator has no Bluetooth LE and iOS cannot do WebUSB, so BLE pairing and USB are not covered — [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) | | The OS notification-permission dialog | the one-shot `UNUserNotificationCenter` alert, reset with `xcrun simctl uninstall to.bitkit` and a rebuild | | 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) | | A Pubky identity and a two-wallet marketplace purchase | a Bitkit-generated Pubky profile, plus the integration fixture runtime: Pubky testnet, Paykit Server, regtest bitcoind and Fulcrum — [pubky-auth](pubky-auth/README.md), [pubky-marketplace](pubky-marketplace/README.md) | diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index 3c3c2fcd01..da56ec6569 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -169,11 +169,19 @@ simulator does not reach it at `127.0.0.1:30121`). The scan then lists only the home tile reads "Connected via Bluetooth", the only transport badge iOS has. 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. Bluetooth, typing the PIN on the device, a -wrong PIN and the device's own screens still need a physical Jade; unit tests +`start` wipes the device back to that seed and PIN. Bluetooth still needs a physical Jade; unit tests (`JadeManagerTests.swift`, `JadeTransportTests.swift`, `JadeBLELinkStateTests.swift`, `HwWalletManagerVendorTests.swift`, `HwConnectViewModelTests.swift`, `HwFundingSignerTests.swift`, `HwEngagedSessionTests.swift`) 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. + While a Jade waits for its PIN, the Found step shows `HwFoundUnlockHint`. The receive tab of a hardware wallet is labelled with its vendor: a Trezor wallet keeps `Tab-trezor` and a Jade reads `Tab-jade`. diff --git a/journeys/hardware-wallet/jade-connect-sign.xml b/journeys/hardware-wallet/jade-connect-sign.xml index a127799067..81ef904c2b 100644 --- a/journeys/hardware-wallet/jade-connect-sign.xml +++ b/journeys/hardware-wallet/jade-connect-sign.xml @@ -39,7 +39,7 @@ 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 hardware sign screen shows the amount (testTag "HardwareSendSignAmount"), the destination address under "To address (confirm on device)" 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 diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml new file mode 100644 index 0000000000..02c858b661 --- /dev/null +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -0,0 +1,32 @@ + + + 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. iOS then asks for the PIN on the + device again and retries, where Android reports the Jade as busy (see the README). + + + + 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 the Jade shows its PIN pad again + + + Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator press right front` once the device shows Verify Address, and verify the button returns to "Verify on Device" with no error + + + 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 428cff5bbe05d2db2d0977ee2b9d2d658ad7690b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 23:06:15 +0100 Subject: [PATCH 03/14] fix: reconnect the jade emulator after it restarts A closed emulator socket now reports the Jade as disconnected, as a dropped Bluetooth link does, so the next request reconnects instead of reusing a dead session. Verified: unit tests pass (4587, 0 failures); on a simulator a send signed after the emulator restarted under the app --- Bitkit/Services/Jade/JadeTransport.swift | 18 +++++++++-- BitkitTests/JadeTransportTests.swift | 39 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/Jade/JadeTransport.swift b/Bitkit/Services/Jade/JadeTransport.swift index e1f880199f..dba34239ad 100644 --- a/Bitkit/Services/Jade/JadeTransport.swift +++ b/Bitkit/Services/Jade/JadeTransport.swift @@ -34,6 +34,7 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc private let driver: JadeBLEDriving private let emulator: JadeEmulatorLink private let isTrezorBridgeEnabled: () -> Bool + private let emulatorDisconnects = PassthroughSubject() init( driver: JadeBLEDriving, @@ -46,7 +47,7 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc } var externalDisconnects: AnyPublisher { - driver.externalDisconnects + driver.externalDisconnects.merge(with: emulatorDisconnects).eraseToAnyPublisher() } var bluetoothPoweredOn: AnyPublisher { @@ -85,6 +86,13 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc driver.setPairedPaths(paths) } + /// A closed emulator socket counts as the Jade going away, as a dropped Bluetooth link does. + private func onEmulatorResult(path: String, errorCode: JadeTransportErrorCode?) { + guard errorCode == .disconnected else { return } + emulator.closeDevice(path: path) + emulatorDisconnects.send(path) + } + // MARK: - JadeTransportCallback func scanDevices(timeoutMs: UInt32) -> [JadeNativeDevice] { @@ -126,7 +134,9 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc func writeChunk(path: String, data: Data) -> JadeTransportResult { if emulator.isEmulatorPath(path) { - return emulator.write(path: path, data: data) + let result = emulator.write(path: path, data: data) + onEmulatorResult(path: path, errorCode: result.errorCode) + return result } do { try driver.write(path: path, data: data) @@ -139,7 +149,9 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc func readChunk(path: String, timeoutMs: UInt32) -> JadeTransportReadResult { if emulator.isEmulatorPath(path) { - return emulator.read(path: path, timeoutMs: timeoutMs) + let result = emulator.read(path: path, timeoutMs: timeoutMs) + onEmulatorResult(path: path, errorCode: result.errorCode) + return result } do { let data = try driver.read(path: path, timeout: Double(timeoutMs) / 1000) diff --git a/BitkitTests/JadeTransportTests.swift b/BitkitTests/JadeTransportTests.swift index b78c6f1522..46bb13a2b4 100644 --- a/BitkitTests/JadeTransportTests.swift +++ b/BitkitTests/JadeTransportTests.swift @@ -130,6 +130,45 @@ final class JadeTransportTests: XCTestCase { XCTAssertEqual(result.error, "Your Jade disconnected.") } + func testClosedEmulatorSocketReportsAnExternalDisconnect() throws { + let port = try acceptOnceAndClose() + let emulatorPath = "tcp:127.0.0.1:\(port)" + let emulator = JadeEmulatorLink(address: "127.0.0.1:\(port)", isEnabled: { true }) + let transport = JadeTransport(driver: driver, emulator: emulator, isTrezorBridgeEnabled: { false }) + var reported: [String] = [] + transport.externalDisconnects.sink { reported.append($0) }.store(in: &cancellables) + XCTAssertTrue(transport.openDevice(path: emulatorPath).success) + + let result = transport.readChunk(path: emulatorPath, timeoutMs: 1000) + + XCTAssertEqual(result.errorCode, .disconnected) + XCTAssertEqual(reported, [emulatorPath]) + XCTAssertEqual(transport.readChunk(path: emulatorPath, timeoutMs: 10).errorCode, .notConnected) + } + + /// A one-shot TCP server on 127.0.0.1 that closes its first connection at once. + private func acceptOnceAndClose() throws -> UInt16 { + let server = socket(AF_INET, SOCK_STREAM, 0) + var address = sockaddr_in() + address.sin_family = sa_family_t(AF_INET) + address.sin_addr.s_addr = inet_addr("127.0.0.1") + var length = socklen_t(MemoryLayout.size) + let bound = withUnsafeMutablePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + bind(server, $0, length) == 0 && listen(server, 1) == 0 && getsockname(server, $0, &length) == 0 + } + } + guard bound else { + close(server) + throw XCTSkip("Could not listen on 127.0.0.1") + } + DispatchQueue.global().async { + close(accept(server, nil, nil)) + close(server) + } + return UInt16(bigEndian: address.sin_port) + } + // MARK: - Writes func testWriteSendsTheChunkToTheDriver() { From b8fe09b7d79046aa909e9f4c3646bc11def6c774 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 18:19:27 +0100 Subject: [PATCH 04/14] test: mine every 20 sends in the jade psbt journey setup Bitcoin Core refuses a chain of more than 25 unconfirmed sends, so funding 200 inputs needs a block every 20 sends, as the bitkit-docker recipe does. The journey now parses as XML. Verified: xmllint on the journey --- journeys/hardware-wallet/jade-psbt-too-large.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/journeys/hardware-wallet/jade-psbt-too-large.xml b/journeys/hardware-wallet/jade-psbt-too-large.xml index a2d8f52baa..4eeb70ef61 100644 --- a/journeys/hardware-wallet/jade-psbt-too-large.xml +++ b/journeys/hardware-wallet/jade-psbt-too-large.xml @@ -4,8 +4,8 @@ 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` + and the Jade's receive address must hold about 200 inputs: with `JADE_ADDRESS` set to it, run + `for i in $(seq 200); do ./bitcoin-cli sendtoaddress "$JADE_ADDRESS" 0.0002; if [ $((i % 20)) = 0 ]; then ./bitcoin-cli -generate 1; fi; done` in `bitkit-docker`. Over the client's 16 KiB PSBT limit, Bitkit refuses before the device sees the transaction. From 2c6e0233389657b3190d4a8c85f605045a266ff4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 18:28:52 +0100 Subject: [PATCH 05/14] test: check the jade sender in the send details J1 opens Show details before it checks FROM, since the confirmation screen starts with them collapsed. The locked journey no longer describes Android as reporting busy: synonymdev/bitkit-android#2050 makes Android ask for the PIN and retry as iOS does. Verified: xmllint on the journeys --- journeys/hardware-wallet/README.md | 3 +-- journeys/hardware-wallet/jade-connect-sign.xml | 2 +- journeys/hardware-wallet/jade-device-locked.xml | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index da56ec6569..840e4fb0ad 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -178,8 +178,7 @@ The error journeys start the emulator in another state first: `jade-uninitialize (`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 +pairing, so the next request asks for the PIN on the device again and retries; `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 81ef904c2b..d64c6f2696 100644 --- a/journeys/hardware-wallet/jade-connect-sign.xml +++ b/journeys/hardware-wallet/jade-connect-sign.xml @@ -36,7 +36,7 @@ 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 + Enter an amount below the Jade's available balance, tap Continue (testTag "ContinueAmount"), tap Show details (testTag "SendConfirmToggleDetails"), verify the FROM field (testTag "SendConfirmAssetButton") shows the Jade, and swipe to confirm Verify the hardware sign screen shows the amount (testTag "HardwareSendSignAmount"), the destination address under "To address (confirm on device)" and a "Sign With Jade" button (testTag "HardwareSendOpenTrezorConnect"), then tap it diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index 02c858b661..3a5c261c27 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -3,8 +3,8 @@ 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. iOS then asks for the PIN on the - device again and retries, where Android reports the Jade as busy (see the README). + Jade paired. The device answers the next request with HW_LOCKED, and the app asks for the PIN on + the device again and retries. From fdbad90bf75bb83ce783c9f4a4f7790bbdd89964 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 19:35:09 +0100 Subject: [PATCH 06/14] fix: reach the jade emulator by hostname JADE_EMULATOR_URL now resolves a hostname such as localhost, and a scan logs an address it cannot use. JadeTransportTests run with the emulator off, so a Debug environment that turns it on no longer changes them. Verified: swiftformat --lint, JadeTransportTests (28 passed) --- Bitkit/Services/Jade/JadeEmulatorLink.swift | 21 ++++++++++++++++++--- BitkitTests/JadeTransportTests.swift | 19 ++++++++++++++----- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/Bitkit/Services/Jade/JadeEmulatorLink.swift b/Bitkit/Services/Jade/JadeEmulatorLink.swift index 0bee21a22c..2911e1f007 100644 --- a/Bitkit/Services/Jade/JadeEmulatorLink.swift +++ b/Bitkit/Services/Jade/JadeEmulatorLink.swift @@ -41,8 +41,14 @@ final class JadeEmulatorLink: @unchecked Sendable { func scanDevices() -> [JadeNativeDevice] { guard isEnabled() else { return [] } if socket(for: path) == nil { - guard let probe = try? connect() else { return [] } - close(probe) + do { + try close(connect()) + } catch { + if case JadeEmulatorError.invalidAddress = error { + Logger.warn("Failed to scan for the Jade emulator: \(error)", context: Self.logContext) + } + return [] + } } return [JadeNativeDevice(path: path, transport: .serial, name: Self.deviceName, serialNumber: nil)] } @@ -123,7 +129,16 @@ final class JadeEmulatorLink: @unchecked Sendable { var addr = sockaddr_in() addr.sin_family = sa_family_t(AF_INET) addr.sin_port = port.bigEndian - guard inet_pton(AF_INET, host, &addr.sin_addr) == 1 else { throw JadeEmulatorError.invalidAddress(address) } + // Resolves a hostname such as localhost as well as an IPv4 literal. + var hints = addrinfo() + hints.ai_family = AF_INET + hints.ai_socktype = SOCK_STREAM + var resolved: UnsafeMutablePointer? + guard getaddrinfo(host, nil, &hints, &resolved) == 0, let found = resolved, let foundAddr = found.pointee.ai_addr else { + throw JadeEmulatorError.invalidAddress(address) + } + defer { freeaddrinfo(found) } + addr.sin_addr = foundAddr.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr } let fd = Darwin.socket(AF_INET, SOCK_STREAM, 0) guard fd >= 0 else { throw JadeEmulatorError.connectFailed(errno) } diff --git a/BitkitTests/JadeTransportTests.swift b/BitkitTests/JadeTransportTests.swift index 46bb13a2b4..e3ddc1179b 100644 --- a/BitkitTests/JadeTransportTests.swift +++ b/BitkitTests/JadeTransportTests.swift @@ -10,6 +10,8 @@ final class JadeTransportTests: XCTestCase { private var driver: FakeBLEDriver! private var cancellables: Set = [] + /// Keeps these tests off an emulator the Debug environment may have turned on. + private let disabledEmulator = JadeEmulatorLink(address: "127.0.0.1:1", isEnabled: { false }) override func setUp() { super.setUp() @@ -23,7 +25,7 @@ final class JadeTransportTests: XCTestCase { } private func makeTransport(isTrezorBridgeEnabled: Bool = false) -> JadeTransport { - JadeTransport(driver: driver, isTrezorBridgeEnabled: { isTrezorBridgeEnabled }) + JadeTransport(driver: driver, emulator: disabledEmulator, isTrezorBridgeEnabled: { isTrezorBridgeEnabled }) } // MARK: - Chunk size @@ -38,7 +40,7 @@ final class JadeTransportTests: XCTestCase { } func testChunkSizeDefaultsTo20WhenNotOpen() { - let transport = JadeTransport(driver: JadeBLEManager(), isTrezorBridgeEnabled: { false }) + let transport = JadeTransport(driver: JadeBLEManager(), emulator: disabledEmulator, isTrezorBridgeEnabled: { false }) XCTAssertEqual(transport.getChunkSize(path: path), 20) } @@ -52,7 +54,7 @@ final class JadeTransportTests: XCTestCase { // MARK: - Unopened paths func testOperationsOnUnopenedDeviceReportNotConnected() { - let transport = JadeTransport(driver: JadeBLEManager(), isTrezorBridgeEnabled: { false }) + let transport = JadeTransport(driver: JadeBLEManager(), emulator: disabledEmulator, isTrezorBridgeEnabled: { false }) let read = transport.readChunk(path: path, timeoutMs: 50) XCTAssertFalse(read.success) @@ -69,7 +71,7 @@ final class JadeTransportTests: XCTestCase { func testOpeningAnInvalidPathFailsWithoutStartingBluetooth() { let manager = JadeBLEManager() - let transport = JadeTransport(driver: manager, isTrezorBridgeEnabled: { false }) + let transport = JadeTransport(driver: manager, emulator: disabledEmulator, isTrezorBridgeEnabled: { false }) let result = transport.openDevice(path: "usb:jade") @@ -81,7 +83,7 @@ final class JadeTransportTests: XCTestCase { func testCentralIsOnlyCreatedByScanOrOpen() { let manager = JadeBLEManager() - let transport = JadeTransport(driver: manager, isTrezorBridgeEnabled: { false }) + let transport = JadeTransport(driver: manager, emulator: disabledEmulator, isTrezorBridgeEnabled: { false }) manager.setPairedPaths([path]) manager.releaseAllImmediately() @@ -146,6 +148,13 @@ final class JadeTransportTests: XCTestCase { XCTAssertEqual(transport.readChunk(path: emulatorPath, timeoutMs: 10).errorCode, .notConnected) } + func testEmulatorAddressAcceptsAHostname() throws { + let port = try acceptOnceAndClose() + let emulator = JadeEmulatorLink(address: "localhost:\(port)", isEnabled: { true }) + + XCTAssertEqual(emulator.scanDevices().map(\.path), ["tcp:localhost:\(port)"]) + } + /// A one-shot TCP server on 127.0.0.1 that closes its first connection at once. private func acceptOnceAndClose() throws -> UInt16 { let server = socket(AF_INET, SOCK_STREAM, 0) From 6a1b1e39a42f6e1e80e2cb52eeb86c34a632a5d7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 21:34:49 +0100 Subject: [PATCH 07/14] test: sign with a jade logged out on the device The locked journey also signs a send after a logout, as on Android (synonymdev/bitkit-android#2140). iOS does not retry the fingerprint read on Sign With Jade yet, so that step can still report busy until synonymdev/bitkit-ios#1517. Verified: xmllint on the journey --- journeys/hardware-wallet/README.md | 3 ++- .../hardware-wallet/jade-device-locked.xml | 20 ++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index 840e4fb0ad..38d34ac349 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -178,7 +178,8 @@ The error journeys start the emulator in another state first: `jade-uninitialize (`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, so the next request asks for the PIN on the device again and retries; `jade-psbt-too-large.xml` needs the app on the bitkit-docker Electrum and about 200 small +pairing, so the next request asks for the PIN on the device again and retries (on iOS, Sign With Jade +can still report busy until synonymdev/bitkit-ios#1517); `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-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index 3a5c261c27..de9f524886 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -2,9 +2,11 @@ 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, and the app asks for the PIN on - the device again and retries. + `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README), no + Jade paired and funds on the Jade's regtest addresses for the send steps. The device answers + the next request with HW_LOCKED, and the app asks for the PIN on the device again and retries, + on Verify on Device and on Sign With Jade. iOS does not retry the fingerprint read on Sign With + Jade yet, so that step can still report the Jade as busy (synonymdev/bitkit-ios#1517). @@ -28,5 +30,17 @@ Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator press right front` once the device shows Verify Address, and verify the button returns to "Verify on Device" with no error + + Close the receive sheet and run `./scripts/jade-emulator press front right front` to log out on the device again + + + 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, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") + + + Verify the Jade shows its PIN pad and the sheet's Back button is still shown, then run `./scripts/jade-emulator pin 012345` + + + Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press right front` to sign on Send Transaction, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds, with one payment sent + From 329013f8fd7c4b9df264ad069dbdc99acc642777 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 22:11:26 +0100 Subject: [PATCH 08/14] test: fund the jade for the locked journey's send The description names the bitkit-docker Electrum and the funding command for the send steps, and the PIN pad step no longer checks the sheet's Back button, as on Android (synonymdev/bitkit-android#2140). Verified: xmllint on the journey --- journeys/hardware-wallet/jade-device-locked.xml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index de9f524886..283fb49515 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -2,8 +2,11 @@ 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), no - Jade paired and funds on the Jade's regtest addresses for the send steps. The device answers + `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README) and no + Jade paired. For the send steps, Settings, Advanced, Electrum Server must point at the + `bitkit-docker` Electrum, and the Jade must hold funds there: after pairing, run + `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in + `bitkit-docker`, where `JADE_ADDRESS` is the address Receive shows on the Jade tab. The device answers the next request with HW_LOCKED, and the app asks for the PIN on the device again and retries, on Verify on Device and on Sign With Jade. iOS does not retry the fingerprint read on Sign With Jade yet, so that step can still report the Jade as busy (synonymdev/bitkit-ios#1517). @@ -37,7 +40,7 @@ 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, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") - Verify the Jade shows its PIN pad and the sheet's Back button is still shown, then run `./scripts/jade-emulator pin 012345` + Verify the Jade shows its PIN pad, then run `./scripts/jade-emulator pin 012345` Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press right front` to sign on Send Transaction, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds, with one payment sent From b24eb0dfadb1be8a0e1fbdd23a7b0643ec2edcb3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 22:12:49 +0100 Subject: [PATCH 09/14] fix: keep a closing jade emulator socket from reaching a new connection Each socket counts its in-flight reads and writes; closing shuts it down at once and frees the descriptor only after the last call returns, so a reused descriptor never receives an old call's bytes. Only a remote close reports a disconnect. Verified: JadeTransportTests (29 tests) on the iOS simulator --- Bitkit/Services/Jade/JadeEmulatorLink.swift | 118 +++++++++++++++----- Bitkit/Services/Jade/JadeTransport.swift | 1 - BitkitTests/JadeTransportTests.swift | 34 +++++- 3 files changed, 118 insertions(+), 35 deletions(-) diff --git a/Bitkit/Services/Jade/JadeEmulatorLink.swift b/Bitkit/Services/Jade/JadeEmulatorLink.swift index 2911e1f007..f9487b94b9 100644 --- a/Bitkit/Services/Jade/JadeEmulatorLink.swift +++ b/Bitkit/Services/Jade/JadeEmulatorLink.swift @@ -18,7 +18,7 @@ final class JadeEmulatorLink: @unchecked Sendable { private let address: String private let isEnabled: () -> Bool private let lock = NSLock() - private var sockets: [String: Int32] = [:] + private var sockets: [String: EmulatorSocket] = [:] init(address: String, isEnabled: @escaping () -> Bool) { self.address = address @@ -40,7 +40,7 @@ final class JadeEmulatorLink: @unchecked Sendable { /// Lists the emulator only while its port answers, so a stopped container is not offered. func scanDevices() -> [JadeNativeDevice] { guard isEnabled() else { return [] } - if socket(for: path) == nil { + if lock.withLock({ sockets[path] }) == nil { do { try close(connect()) } catch { @@ -57,7 +57,7 @@ final class JadeEmulatorLink: @unchecked Sendable { closeDevice(path: path) do { let fd = try connect() - lock.withLock { sockets[path] = fd } + lock.withLock { sockets[path] = EmulatorSocket(fd: fd) } Logger.info("Opened Jade emulator '\(path)'", context: Self.logContext) return Self.success } catch { @@ -68,8 +68,8 @@ final class JadeEmulatorLink: @unchecked Sendable { @discardableResult func closeDevice(path: String) -> JadeTransportResult { - if let fd = lock.withLock({ sockets.removeValue(forKey: path) }) { - close(fd) + if let socket = lock.withLock({ sockets.removeValue(forKey: path) }) { + retire(socket) Logger.info("Closed Jade emulator '\(path)'", context: Self.logContext) } return Self.success @@ -81,44 +81,90 @@ final class JadeEmulatorLink: @unchecked Sendable { } func write(path: String, data: Data) -> JadeTransportResult { - guard let fd = socket(for: path) else { - return JadeTransportResult(success: false, error: "Device not open: '\(path)'", errorCode: .notConnected) - } - var offset = 0 - while offset < data.count { - let written = data.withUnsafeBytes { buffer in - send(fd, buffer.baseAddress!.advanced(by: offset), data.count - offset, 0) - } - if written <= 0 { - return JadeTransportResult(success: false, error: "Jade emulator write failed: errno \(errno)", errorCode: .disconnected) + let notOpen = JadeTransportResult(success: false, error: "Device not open: '\(path)'", errorCode: .notConnected) + return withSocket(path, notOpen: notOpen) { socket in + var offset = 0 + while offset < data.count { + let written = data.withUnsafeBytes { buffer in + send(socket.fd, buffer.baseAddress!.advanced(by: offset), data.count - offset, 0) + } + if written <= 0 { + let error = errno + guard dropAfterRemoteClose(socket, path: path) else { return notOpen } + return JadeTransportResult(success: false, error: "Jade emulator write failed: errno \(error)", errorCode: .disconnected) + } + offset += written } - offset += written + return Self.success } - return Self.success } func read(path: String, timeoutMs: UInt32) -> JadeTransportReadResult { - guard let fd = socket(for: path) else { - return JadeTransportReadResult(success: false, data: Data(), error: "Device not open: '\(path)'", errorCode: .notConnected) - } - var poller = pollfd(fd: fd, events: Int16(POLLIN), revents: 0) - let ready = poll(&poller, 1, Int32(min(max(timeoutMs, 1), Self.readTimeoutMaxMs))) - // Nothing received yet is the normal state while the device works or waits. - guard ready > 0 else { return JadeTransportReadResult(success: true, data: Data(), error: "", errorCode: nil) } - var buffer = [UInt8](repeating: 0, count: Self.readBufferBytes) - let count = recv(fd, &buffer, buffer.count, 0) - guard count > 0 else { - return JadeTransportReadResult(success: false, data: Data(), error: "Jade emulator closed the connection", errorCode: .disconnected) + let notOpen = JadeTransportReadResult(success: false, data: Data(), error: "Device not open: '\(path)'", errorCode: .notConnected) + return withSocket(path, notOpen: notOpen) { socket in + var poller = pollfd(fd: socket.fd, events: Int16(POLLIN), revents: 0) + let ready = poll(&poller, 1, Int32(min(max(timeoutMs, 1), Self.readTimeoutMaxMs))) + // Nothing received yet is the normal state while the device works or waits. + guard ready > 0 else { return JadeTransportReadResult(success: true, data: Data(), error: "", errorCode: nil) } + var buffer = [UInt8](repeating: 0, count: Self.readBufferBytes) + let count = recv(socket.fd, &buffer, buffer.count, 0) + guard count > 0 else { + guard dropAfterRemoteClose(socket, path: path) else { return notOpen } + return JadeTransportReadResult(success: false, data: Data(), error: "Jade emulator closed the connection", errorCode: .disconnected) + } + return JadeTransportReadResult(success: true, data: Data(buffer[0 ..< count]), error: "", errorCode: nil) } - return JadeTransportReadResult(success: true, data: Data(buffer[0 ..< count]), error: "", errorCode: nil) } // MARK: - Helpers private static let success = JadeTransportResult(success: true, error: "", errorCode: nil) - private func socket(for path: String) -> Int32? { - lock.withLock { sockets[path] } + /// Runs one call on the path's socket and keeps its descriptor open until the call returns, + /// so a close from another thread cannot hand the number to a new connection mid-call. + private func withSocket(_ path: String, notOpen: T, _ body: (EmulatorSocket) -> T) -> T { + let socket: EmulatorSocket? = lock.withLock { + guard let socket = sockets[path] else { return nil } + socket.inFlight += 1 + return socket + } + guard let socket else { return notOpen } + defer { + let closeNow = lock.withLock { + socket.inFlight -= 1 + return socket.isClosed && socket.inFlight == 0 + } + if closeNow { + Darwin.close(socket.fd) + } + } + return body(socket) + } + + /// Wakes pending calls at once; the descriptor is released when the last of them returns. + private func retire(_ socket: EmulatorSocket) { + let closeNow = lock.withLock { + socket.isClosed = true + Darwin.shutdown(socket.fd, SHUT_RDWR) + return socket.inFlight == 0 + } + if closeNow { + Darwin.close(socket.fd) + } + } + + /// Drops a socket the emulator closed. False when it was closed here first, so a local close + /// is not reported as the Jade disconnecting and a newer socket on the path stays open. + private func dropAfterRemoteClose(_ socket: EmulatorSocket, path: String) -> Bool { + let wasCurrent = lock.withLock { + guard sockets[path] === socket else { return false } + sockets[path] = nil + return true + } + if wasCurrent { + retire(socket) + } + return wasCurrent } private func connect() throws -> Int32 { @@ -189,3 +235,13 @@ enum JadeEmulatorError: Error, CustomStringConvertible { } } } + +private final class EmulatorSocket { + let fd: Int32 + var inFlight = 0 + var isClosed = false + + init(fd: Int32) { + self.fd = fd + } +} diff --git a/Bitkit/Services/Jade/JadeTransport.swift b/Bitkit/Services/Jade/JadeTransport.swift index dba34239ad..105bc0688a 100644 --- a/Bitkit/Services/Jade/JadeTransport.swift +++ b/Bitkit/Services/Jade/JadeTransport.swift @@ -89,7 +89,6 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc /// A closed emulator socket counts as the Jade going away, as a dropped Bluetooth link does. private func onEmulatorResult(path: String, errorCode: JadeTransportErrorCode?) { guard errorCode == .disconnected else { return } - emulator.closeDevice(path: path) emulatorDisconnects.send(path) } diff --git a/BitkitTests/JadeTransportTests.swift b/BitkitTests/JadeTransportTests.swift index e3ddc1179b..a69b8d93ad 100644 --- a/BitkitTests/JadeTransportTests.swift +++ b/BitkitTests/JadeTransportTests.swift @@ -155,8 +155,32 @@ final class JadeTransportTests: XCTestCase { XCTAssertEqual(emulator.scanDevices().map(\.path), ["tcp:localhost:\(port)"]) } - /// A one-shot TCP server on 127.0.0.1 that closes its first connection at once. - private func acceptOnceAndClose() throws -> UInt16 { + func testClosingTheEmulatorDuringAReadReportsNoDisconnect() throws { + let port = try acceptOnceAndClose(holding: true) + let emulatorPath = "tcp:127.0.0.1:\(port)" + let emulator = JadeEmulatorLink(address: "127.0.0.1:\(port)", isEnabled: { true }) + let transport = JadeTransport(driver: driver, emulator: emulator, isTrezorBridgeEnabled: { false }) + var reported: [String] = [] + transport.externalDisconnects.sink { reported.append($0) }.store(in: &cancellables) + XCTAssertTrue(transport.openDevice(path: emulatorPath).success) + let readDone = expectation(description: "read returns") + var result: JadeTransportReadResult? + + DispatchQueue.global().async { + result = transport.readChunk(path: emulatorPath, timeoutMs: 1000) + readDone.fulfill() + } + Thread.sleep(forTimeInterval: 0.2) + emulator.closeDevice(path: emulatorPath) + wait(for: [readDone], timeout: 2) + + XCTAssertEqual(result?.errorCode, .notConnected) + XCTAssertTrue(reported.isEmpty) + } + + /// A one-shot TCP server on 127.0.0.1 that closes its first connection at once, or holds it + /// open until the test ends. + private func acceptOnceAndClose(holding: Bool = false) throws -> UInt16 { let server = socket(AF_INET, SOCK_STREAM, 0) var address = sockaddr_in() address.sin_family = sa_family_t(AF_INET) @@ -172,8 +196,12 @@ final class JadeTransportTests: XCTestCase { throw XCTSkip("Could not listen on 127.0.0.1") } DispatchQueue.global().async { - close(accept(server, nil, nil)) + let connection = accept(server, nil, nil) close(server) + if holding { + Thread.sleep(forTimeInterval: 3) + } + close(connection) } return UInt16(bigEndian: address.sin_port) } From 9c86c04239d32f7ad7d441b16acb4563651c2a3c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 23:48:38 +0100 Subject: [PATCH 10/14] test: lock the jade during an open session in both locked steps Closing Receive after Verify on Device ends the Jade session, so the send leg reconnected instead of meeting the locked device. The journey now funds from the address Receive shows, signs first and verifies the address last, each right after a log-out on an open session. Verified: xmllint on the journey --- .../hardware-wallet/jade-device-locked.xml | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index 283fb49515..070ffc038e 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -4,9 +4,9 @@ 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. For the send steps, Settings, Advanced, Electrum Server must point at the - `bitkit-docker` Electrum, and the Jade must hold funds there: after pairing, run - `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in - `bitkit-docker`, where `JADE_ADDRESS` is the address Receive shows on the Jade tab. The device answers + `bitkit-docker` Electrum. Each log-out happens while the app holds an open Jade session: send + first, since closing Receive after Verify on Device ends the session and the next step would + reconnect instead of meeting the locked device. The device answers the next request with HW_LOCKED, and the app asks for the PIN on the device again and retries, on Verify on Device and on Sign With Jade. iOS does not retry the fingerprint read on Sign With Jade yet, so that step can still report the Jade as busy (synonymdev/bitkit-ios#1517). @@ -24,26 +24,29 @@ 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") + + Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in `bitkit-docker` + 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 the Jade shows its PIN pad again + 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, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") - Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator press right front` once the device shows Verify Address, and verify the button returns to "Verify on Device" with no error + Verify the Jade shows its PIN pad, then run `./scripts/jade-emulator pin 012345` - Close the receive sheet and run `./scripts/jade-emulator press front right front` to log out on the device again + Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press right front` to sign on Send Transaction, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds, with one payment sent - 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, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") + Close the success screen and run `./scripts/jade-emulator press front right front` to log out on the device again - Verify the Jade shows its PIN pad, then run `./scripts/jade-emulator pin 012345` + Tap Receive, select the Jade tab, tap "Show Details" if needed, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify the Jade shows its PIN pad again - Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press right front` to sign on Send Transaction, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds, with one payment sent + Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator press right front` once the device shows Verify Address, and verify the button returns to "Verify on Device" with no error From caf69f3ee1d495a7ff65bedd7c8b9fb779062ca6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 07:33:26 +0100 Subject: [PATCH 11/14] test: expect the jade busy message on a locked sign Until synonymdev/bitkit-ios#1517 lands, Sign With Jade on a logged-out Jade shows the busy message instead of the PIN pad, so the locked journey checks that, keeps the device logged out and goes on to the Verify on Device retry. Verified: xmllint on the journey --- journeys/hardware-wallet/README.md | 4 ++-- .../hardware-wallet/jade-device-locked.xml | 23 +++++++------------ 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index 38d34ac349..56a81ac2c7 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -178,8 +178,8 @@ The error journeys start the emulator in another state first: `jade-uninitialize (`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, so the next request asks for the PIN on the device again and retries (on iOS, Sign With Jade -can still report busy until synonymdev/bitkit-ios#1517); `jade-psbt-too-large.xml` needs the app on the bitkit-docker Electrum and about 200 small +pairing: Sign With Jade shows the Jade busy message until synonymdev/bitkit-ios#1517, then Verify on Device +asks for the PIN on the device again and retries; `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-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index 070ffc038e..be5fc37885 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -1,15 +1,14 @@ - Logs the paired Jade out on the device itself and checks the message the app shows when it + Logs the paired Jade out on the device itself and checks the messages 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. For the send steps, Settings, Advanced, Electrum Server must point at the - `bitkit-docker` Electrum. Each log-out happens while the app holds an open Jade session: send - first, since closing Receive after Verify on Device ends the session and the next step would - reconnect instead of meeting the locked device. The device answers - the next request with HW_LOCKED, and the app asks for the PIN on the device again and retries, - on Verify on Device and on Sign With Jade. iOS does not retry the fingerprint read on Sign With - Jade yet, so that step can still report the Jade as busy (synonymdev/bitkit-ios#1517). + Jade paired. For the send step, Settings, Advanced, Electrum Server must point at the + `bitkit-docker` Electrum. The log-out happens while the app holds an open Jade session, so the + device answers the next request with HW_LOCKED. On Verify on Device the app asks for the PIN on + the device again and retries. On Sign With Jade iOS does not retry the fingerprint read yet and + shows the Jade busy message (synonymdev/bitkit-ios#1517); the PR that fixes it changes that step + to expect the PIN pad and a sent payment. @@ -34,13 +33,7 @@ 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, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") - Verify the Jade shows its PIN pad, then run `./scripts/jade-emulator pin 012345` - - - Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press right front` to sign on Send Transaction, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds, with one payment sent - - - Close the success screen and run `./scripts/jade-emulator press front right front` to log out on the device again + Verify the toast "Your Jade is busy. Finish what is shown on the device, then try again." appears, then close the send sheet; the device stays logged out Tap Receive, select the Jade tab, tap "Show Details" if needed, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify the Jade shows its PIN pad again From a54e9edc1d4ca43f668947724ab050e80d0b25a0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 11:53:07 +0100 Subject: [PATCH 12/14] test: dismiss the received sheet in the locked jade journey Funding the Jade opens the Received Bitcoin sheet over the wallet, which blocks the next Send tap; the journey now taps its button, as on Android (synonymdev/bitkit-android#2149). Verified: xmllint on the journey --- journeys/hardware-wallet/jade-device-locked.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index be5fc37885..a2316387fa 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -24,7 +24,7 @@ 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") - Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in `bitkit-docker` + Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in `bitkit-docker`. Wait for the "Received Bitcoin" sheet and tap its button (testTag "ReceivedTransactionButton") Run `./scripts/jade-emulator press front right front` in `bitkit-docker` to choose Session, then Log Out, on the device From bb88be91850392cc38db00b69477e6afc38d6cfc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 16:51:34 +0100 Subject: [PATCH 13/14] test: catch reconnects in the jade locked journey As on Android (synonymdev/bitkit-android#2158), the funding step waits for the deposit's received row, with the Received Bitcoin sheet optional, and each leg checks the app log for the line only the HW_LOCKED path writes, so a dropped connection that also ends in the PIN pad cannot pass for it. Verified: xmllint on the journey; both log lines appear in the J8 run at 2ac5ea01b --- journeys/hardware-wallet/jade-device-locked.xml | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index a2316387fa..6822b3b5c1 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -5,7 +5,9 @@ `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README) and no Jade paired. For the send step, Settings, Advanced, Electrum Server must point at the `bitkit-docker` Electrum. The log-out happens while the app holds an open Jade session, so the - device answers the next request with HW_LOCKED. On Verify on Device the app asks for the PIN on + device answers the next request with HW_LOCKED. A dropped connection also ends in the PIN pad + (the app reconnects and unlocks), so each leg checks the app log for the line only the + HW_LOCKED path writes. On Verify on Device the app asks for the PIN on the device again and retries. On Sign With Jade iOS does not retry the fingerprint read yet and shows the Jade busy message (synonymdev/bitkit-ios#1517); the PR that fixes it changes that step to expect the PIN pad and a sent payment. @@ -24,7 +26,10 @@ 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") - Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in `bitkit-docker`. Wait for the "Received Bitcoin" sheet and tap its button (testTag "ReceivedTransactionButton") + Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in `bitkit-docker` + + + Wait up to 60 seconds for a received row of 100 000 sats stamped with the minute of the funding command, or the next one, in the home activity list (testTag "ActivityShort-0" and the rows after it; tap "Show All" if it is not among the rows shown, since the Jade's seed is shared and other runs' rows can be newer). If the "Received Bitcoin" sheet appears, tap its button (testTag "ReceivedTransactionButton") first; it may not appear when the deposit arrives with the app's first view of the Jade's history Run `./scripts/jade-emulator press front right front` in `bitkit-docker` to choose Session, then Log Out, on the device @@ -33,10 +38,10 @@ 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, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") - Verify the toast "Your Jade is busy. Finish what is shown on the device, then try again." appears, then close the send sheet; the device stays logged out + Verify the app log shows `getMasterFingerprint` failing with "JadeError.DeviceLocked" for this tap and the toast "Your Jade is busy. Finish what is shown on the device, then try again." appears, then close the send sheet; the device stays logged out - Tap Receive, select the Jade tab, tap "Show Details" if needed, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify the Jade shows its PIN pad again + Tap Receive, select the Jade tab, tap "Show Details" if needed, then tap "Verify on Device" (testTag "HardwareVerifyAddress"). Verify the app log shows "The Jade locked since it connected; unlocking and retrying" for this tap, and the Jade shows its PIN pad again Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator press right front` once the device shows Verify Address, and verify the button returns to "Verify on Device" with no error From 65c43ec02b0728dcad68ecbabd3b3d63e17a19a8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 17:46:44 +0100 Subject: [PATCH 14/14] test: fund the locked jade journey enough to skip the balance warning On a fresh chain a 50 000 sat send from a 100 000 sat Jade shows the over 50% of balance warning before Sign With Jade; funding 0.01 BTC avoids it, as on Android (synonymdev/bitkit-android#2158). Verified: xmllint on the journey --- journeys/hardware-wallet/jade-device-locked.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index 6822b3b5c1..c0c4ca66a5 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -26,10 +26,10 @@ 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") - Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in `bitkit-docker` + Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, read the address without tapping "Verify on Device", close the receive sheet and fund it: `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.01; ./bitcoin-cli -generate 1` in `bitkit-docker` - Wait up to 60 seconds for a received row of 100 000 sats stamped with the minute of the funding command, or the next one, in the home activity list (testTag "ActivityShort-0" and the rows after it; tap "Show All" if it is not among the rows shown, since the Jade's seed is shared and other runs' rows can be newer). If the "Received Bitcoin" sheet appears, tap its button (testTag "ReceivedTransactionButton") first; it may not appear when the deposit arrives with the app's first view of the Jade's history + Wait up to 60 seconds for a received row of 1 000 000 sats stamped with the minute of the funding command, or the next one, in the home activity list (testTag "ActivityShort-0" and the rows after it; tap "Show All" if it is not among the rows shown, since the Jade's seed is shared and other runs' rows can be newer). If the "Received Bitcoin" sheet appears, tap its button (testTag "ReceivedTransactionButton") first; it may not appear when the deposit arrives with the app's first view of the Jade's history Run `./scripts/jade-emulator press front right front` in `bitkit-docker` to choose Session, then Log Out, on the device