-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTrezorTransport.swift
More file actions
334 lines (261 loc) · 10.9 KB
/
Copy pathTrezorTransport.swift
File metadata and controls
334 lines (261 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import BitkitCore
import Combine
import CoreBluetooth
import Foundation
/// Implementation of TrezorTransportCallback protocol
/// Coordinates BLE and USB transports for Trezor device communication
final class TrezorTransport: TrezorTransportCallback {
static let shared = TrezorTransport()
private let bleManager = TrezorBLEManager.shared
private let bridgeTransport = TrezorBridgeTransport.shared
// MARK: - Pairing Code Handling
/// Subject to notify UI when pairing code is needed
let needsPairingCodePublisher = PassthroughSubject<Void, Never>()
private var submittedPairingCode: String = ""
private let pairingCodeLock = NSLock()
/// Timeout for pairing code entry (2 minutes)
private static let pairingCodeTimeoutSeconds: TimeInterval = 120
private init() {}
// MARK: - Debug Logging
/// Log to both Logger and in-app TrezorDebugLog
private func debugLog(_ message: String) {
Logger.debug(message, context: "TrezorTransport")
TrezorDebugLog.shared.log("[FFI] \(message)")
}
// MARK: - TrezorTransportCallback Implementation
/// Enumerate all connected/discovered Trezor devices
func enumerateDevices() -> [NativeDeviceInfo] {
let bleDevices = bleManager.enumerateDevices()
var devices = bleDevices.map { device in
NativeDeviceInfo(
path: device.path,
transportType: "bluetooth",
name: device.name,
vendorId: nil,
productId: nil
)
}
devices.append(contentsOf: bridgeTransport.enumerateDevices())
debugLog("enumerateDevices: \(devices.count) devices")
return devices
}
/// Open a connection to a device
func openDevice(path: String) -> TrezorTransportWriteResult {
debugLog("openDevice: \(path)")
do {
if bridgeTransport.isBridgeDevice(path: path) {
return bridgeTransport.openDevice(path: path)
}
guard path.hasPrefix("ble:") else {
throw TrezorTransportError.invalidPath(path)
}
// Synchronously start async connection
// Note: This blocks the calling thread which is expected by Rust
let semaphore = DispatchSemaphore(value: 0)
var connectionError: Error?
Task {
do {
try await bleManager.connect(path: path)
} catch {
connectionError = error
}
semaphore.signal()
}
semaphore.wait()
if let error = connectionError {
throw error
}
return TrezorTransportWriteResult(success: true, error: "", errorCode: nil)
} catch {
debugLog("openDevice FAILED: \(error.localizedDescription)")
return TrezorTransportWriteResult(success: false, error: error.localizedDescription, errorCode: nil)
}
}
/// Close a connection to a device
func closeDevice(path: String) -> TrezorTransportWriteResult {
debugLog("closeDevice: \(path)")
if bridgeTransport.isBridgeDevice(path: path) {
return bridgeTransport.closeDevice(path: path)
}
guard path.hasPrefix("ble:") else {
return TrezorTransportWriteResult(success: false, error: "Invalid device path: \(path)", errorCode: nil)
}
bleManager.disconnect(path: path)
return TrezorTransportWriteResult(success: true, error: "", errorCode: nil)
}
/// Read a chunk of data from the device
func readChunk(path: String) -> TrezorTransportReadResult {
do {
if bridgeTransport.isBridgeDevice(path: path) {
return bridgeTransport.readChunk(path: path)
}
guard path.hasPrefix("ble:") else {
throw TrezorTransportError.invalidPath(path)
}
let data = try bleManager.readChunk(path: path)
debugLog("readChunk: \(data.count) bytes")
return TrezorTransportReadResult(success: true, data: data, error: "", errorCode: nil)
} catch {
debugLog("readChunk FAILED: \(error.localizedDescription)")
return TrezorTransportReadResult(success: false, data: Data(), error: error.localizedDescription, errorCode: nil)
}
}
/// Write a chunk of data to the device
func writeChunk(path: String, data: Data) -> TrezorTransportWriteResult {
debugLog("writeChunk: \(data.count) bytes")
do {
if bridgeTransport.isBridgeDevice(path: path) {
return bridgeTransport.writeChunk(path: path, data: data)
}
guard path.hasPrefix("ble:") else {
throw TrezorTransportError.invalidPath(path)
}
// Synchronously run async write
let semaphore = DispatchSemaphore(value: 0)
var writeError: Error?
Task {
do {
try await bleManager.writeChunk(path: path, data: data)
} catch {
writeError = error
}
semaphore.signal()
}
semaphore.wait()
if let error = writeError {
throw error
}
return TrezorTransportWriteResult(success: true, error: "", errorCode: nil)
} catch {
debugLog("writeChunk FAILED: \(error.localizedDescription)")
return TrezorTransportWriteResult(success: false, error: error.localizedDescription, errorCode: nil)
}
}
/// Get the chunk size for a device
func getChunkSize(path: String) -> UInt32 {
if bridgeTransport.isBridgeDevice(path: path) {
return 64
}
return TrezorBLEManager.chunkSize // 244 bytes for BLE
}
/// Called by rust-trezor to delegate full message call to native transport
/// This is an optional optimization - return nil to have Rust handle it
func callMessage(path: String, messageType: UInt16, data: Data) -> TrezorCallMessageResult? {
if bridgeTransport.isBridgeDevice(path: path) {
return bridgeTransport.callMessage(path: path, messageType: messageType, data: data)
}
// Let Rust handle the message protocol
// We only provide the raw transport layer
return nil
}
/// Get the pairing code from the user (blocks until user enters code)
/// This is called when the Trezor displays a 6-digit code for BLE pairing
func getPairingCode() -> String {
debugLog("getPairingCode: waiting for user input...")
pairingCodeLock.lock()
submittedPairingCode = ""
pairingCodeLock.unlock()
// Drain any leftover signal from a prior (cancelled/submitted) pairing so this request
// doesn't return an empty code instantly and abort the handshake mid-pairing.
while pairingCodeSemaphore.wait(timeout: DispatchTime.now()) == .success {}
// Notify UI to show pairing code dialog
DispatchQueue.main.async {
self.needsPairingCodePublisher.send()
}
// Block and wait for user to enter code
let code = blockForPairingCode()
debugLog("getPairingCode: \(code.isEmpty ? "cancelled/empty" : "received")")
return code
}
/// Semaphore signalled when pairing code is submitted or cancelled
private let pairingCodeSemaphore = DispatchSemaphore(value: 0)
/// Blocking wait for pairing code with timeout
private func blockForPairingCode() -> String {
let timeout = DispatchTime.now() + Self.pairingCodeTimeoutSeconds
let result = pairingCodeSemaphore.wait(timeout: timeout)
if result == .timedOut {
return ""
}
pairingCodeLock.lock()
let code = submittedPairingCode
pairingCodeLock.unlock()
return code
}
/// Called by UI when user submits pairing code
func submitPairingCode(_ code: String) {
debugLog("submitPairingCode")
pairingCodeLock.lock()
submittedPairingCode = code
pairingCodeLock.unlock()
pairingCodeSemaphore.signal()
}
/// Cancel pairing code entry
func cancelPairingCode() {
debugLog("cancelPairingCode")
pairingCodeLock.lock()
submittedPairingCode = ""
pairingCodeLock.unlock()
pairingCodeSemaphore.signal()
}
/// Save THP credential to secure storage
/// An empty credential string indicates a clear request
func saveThpCredential(deviceId: String, credentialJson: String) -> Bool {
// Empty credential means "clear" - delete the stored credential
if credentialJson.isEmpty {
debugLog("saveThpCredential: CLEAR device=\(deviceId)")
TrezorCredentialStorage.delete(deviceId: deviceId)
return true
}
debugLog("saveThpCredential: device=\(deviceId) len=\(credentialJson.count)")
let result = TrezorCredentialStorage.save(deviceId: deviceId, json: credentialJson)
debugLog("saveThpCredential: \(result ? "OK" : "FAILED")")
return result
}
/// Forward Rust-level debug messages to Logger and TrezorDebugLog
func logDebug(tag: String, message: String) {
Logger.debug("[\(tag)] \(message)", context: "TrezorTransport")
TrezorDebugLog.shared.log("[\(tag)] \(message)")
}
/// Load THP credential from secure storage
func loadThpCredential(deviceId: String) -> String? {
debugLog("loadThpCredential: device=\(deviceId)")
// List all stored credentials for debugging
let allDevices = TrezorCredentialStorage.listAllDeviceIds()
debugLog("loadThpCredential: stored IDs=\(allDevices)")
let credential = TrezorCredentialStorage.load(deviceId: deviceId)
debugLog("loadThpCredential: \(credential != nil ? "FOUND len=\(credential!.count)" : "NOT FOUND")")
return credential
}
// MARK: - Device Scanning Helpers
/// Start scanning for BLE devices
func startBLEScanning() {
guard !bridgeTransport.isEnabled else { return }
bleManager.startScanning()
}
/// Stop scanning for BLE devices
func stopBLEScanning() {
bleManager.stopScanning()
}
/// Get Bluetooth state
var bluetoothState: CBManagerState {
bleManager.bluetoothState
}
/// Emits a device path when an established BLE connection drops unexpectedly
/// (out of range or phone Bluetooth turned off).
var externalDisconnectPublisher: PassthroughSubject<String, Never> {
bleManager.externalDisconnectPublisher
}
var isBridgeEnabled: Bool {
bridgeTransport.isEnabled
}
}
// MARK: - Transport Errors
enum TrezorTransportError: LocalizedError {
case invalidPath(String)
var errorDescription: String? {
switch self {
case let .invalidPath(path):
return "Invalid device path: \(path)"
}
}
}