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..f9487b94b9 --- /dev/null +++ b/Bitkit/Services/Jade/JadeEmulatorLink.swift @@ -0,0 +1,247 @@ +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: EmulatorSocket] = [:] + + 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 lock.withLock({ sockets[path] }) == nil { + 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)] + } + + func open(path: String) -> JadeTransportResult { + closeDevice(path: path) + do { + let fd = try connect() + lock.withLock { sockets[path] = EmulatorSocket(fd: 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 socket = lock.withLock({ sockets.removeValue(forKey: path) }) { + retire(socket) + 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 { + 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 + } + return Self.success + } + } + + func read(path: String, timeoutMs: UInt32) -> JadeTransportReadResult { + 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) + } + } + + // MARK: - Helpers + + private static let success = JadeTransportResult(success: true, error: "", errorCode: nil) + + /// 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 { + guard let separator = address.lastIndex(of: ":"), let port = UInt16(address[address.index(after: separator)...]) else { + throw JadeEmulatorError.invalidAddress(address) + } + let host = String(address[..? + 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) } + 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)))" + } + } +} + +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 55a109f45b..105bc0688a 100644 --- a/Bitkit/Services/Jade/JadeTransport.swift +++ b/Bitkit/Services/Jade/JadeTransport.swift @@ -28,17 +28,26 @@ 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 + private let emulatorDisconnects = PassthroughSubject() - 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 } var externalDisconnects: AnyPublisher { - driver.externalDisconnects + driver.externalDisconnects.merge(with: emulatorDisconnects).eraseToAnyPublisher() } var bluetoothPoweredOn: AnyPublisher { @@ -56,14 +65,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() } @@ -71,11 +86,20 @@ 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 } + emulatorDisconnects.send(path) + } + // 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 +112,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 +124,19 @@ 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) { + let result = emulator.write(path: path, data: data) + onEmulatorResult(path: path, errorCode: result.errorCode) + return result + } do { try driver.write(path: path, data: data) return Self.success @@ -112,6 +147,11 @@ final class JadeTransport: JadeTransportCallback, JadeTransportControlling, @unc } func readChunk(path: String, timeoutMs: UInt32) -> JadeTransportReadResult { + if emulator.isEmulatorPath(path) { + 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) return JadeTransportReadResult(success: true, data: data, error: "", errorCode: nil) @@ -121,7 +161,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/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/BitkitTests/JadeTransportTests.swift b/BitkitTests/JadeTransportTests.swift index b78c6f1522..a69b8d93ad 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() @@ -130,6 +132,80 @@ 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) + } + + func testEmulatorAddressAcceptsAHostname() throws { + let port = try acceptOnceAndClose() + let emulator = JadeEmulatorLink(address: "localhost:\(port)", isEnabled: { true }) + + XCTAssertEqual(emulator.scanDevices().map(\.path), ["tcp:localhost:\(port)"]) + } + + 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) + 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 { + let connection = accept(server, nil, nil) + close(server) + if holding { + Thread.sleep(forTimeInterval: 3) + } + close(connection) + } + return UInt16(bigEndian: address.sin_port) + } + // MARK: - Writes func testWriteSendsTheChunkToTheDriver() { 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 b25e7f2425..56a81ac2c7 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -154,12 +154,34 @@ 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 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: 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. 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..d64c6f2696 --- /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"), 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 + + + 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..c0c4ca66a5 --- /dev/null +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -0,0 +1,50 @@ + + + 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 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. 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. + + + + 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") + + + 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 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 + + + 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 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"). 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 + + + 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..4eeb70ef61 --- /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: 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. + + + + 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 + + +