Repository navigation
feat(swift-example-app): share a bounded login key with a browser over Bluetooth #4823
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,215 @@ | ||||||||||||||||||||||||||||||||||||||
| import CoreBluetooth | ||||||||||||||||||||||||||||||||||||||
| import Foundation | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| /// The Bluetooth LE peripheral a browser connects to for a login key. | ||||||||||||||||||||||||||||||||||||||
| /// | ||||||||||||||||||||||||||||||||||||||
| /// Owns the `CBPeripheralManager`, publishes the | ||||||||||||||||||||||||||||||||||||||
| /// `BrowserLoginKeyProtocol` service, reassembles the browser's | ||||||||||||||||||||||||||||||||||||||
| /// request write, and serves the status and response characteristics. | ||||||||||||||||||||||||||||||||||||||
| /// Everything the UI needs is pushed through `@Published` state on the | ||||||||||||||||||||||||||||||||||||||
| /// main actor; the flow decisions (confirm, register, deliver) stay in | ||||||||||||||||||||||||||||||||||||||
| /// the view model so this class knows nothing about identities. | ||||||||||||||||||||||||||||||||||||||
| @MainActor | ||||||||||||||||||||||||||||||||||||||
| final class BrowserLoginPeripheral: NSObject, ObservableObject { | ||||||||||||||||||||||||||||||||||||||
| enum RadioState: Equatable { | ||||||||||||||||||||||||||||||||||||||
| case unknown | ||||||||||||||||||||||||||||||||||||||
| case unauthorized | ||||||||||||||||||||||||||||||||||||||
| case poweredOff | ||||||||||||||||||||||||||||||||||||||
| case unsupported | ||||||||||||||||||||||||||||||||||||||
| case poweredOn | ||||||||||||||||||||||||||||||||||||||
| case advertising | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| @Published private(set) var radioState: RadioState = .unknown | ||||||||||||||||||||||||||||||||||||||
| @Published private(set) var status: BrowserLoginKeyProtocol.Status = .idle | ||||||||||||||||||||||||||||||||||||||
| @Published private(set) var lastError: String? | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| /// Called on the main actor with each complete request write. | ||||||||||||||||||||||||||||||||||||||
| var onRequest: ((Data) -> Void)? | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| private var manager: CBPeripheralManager? | ||||||||||||||||||||||||||||||||||||||
| private var service: CBMutableService? | ||||||||||||||||||||||||||||||||||||||
| private var statusCharacteristic: CBMutableCharacteristic? | ||||||||||||||||||||||||||||||||||||||
| private var responseCharacteristic: CBMutableCharacteristic? | ||||||||||||||||||||||||||||||||||||||
| private var responseBytes = Data() | ||||||||||||||||||||||||||||||||||||||
| /// Whether `start()` was called and the service should go up as | ||||||||||||||||||||||||||||||||||||||
| /// soon as the radio reports powered on. | ||||||||||||||||||||||||||||||||||||||
| private var wantsAdvertising = false | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| private let localName: String | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| init(localName: String) { | ||||||||||||||||||||||||||||||||||||||
| self.localName = localName | ||||||||||||||||||||||||||||||||||||||
| super.init() | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| /// Bring the radio up and advertise the service once it is ready. | ||||||||||||||||||||||||||||||||||||||
| func start() { | ||||||||||||||||||||||||||||||||||||||
| wantsAdvertising = true | ||||||||||||||||||||||||||||||||||||||
| lastError = nil | ||||||||||||||||||||||||||||||||||||||
| if manager == nil { | ||||||||||||||||||||||||||||||||||||||
| // A nil queue delivers delegate callbacks on the main queue, | ||||||||||||||||||||||||||||||||||||||
| // which is what the @MainActor isolation of this class expects. | ||||||||||||||||||||||||||||||||||||||
| manager = CBPeripheralManager(delegate: self, queue: nil) | ||||||||||||||||||||||||||||||||||||||
| } else { | ||||||||||||||||||||||||||||||||||||||
| publishIfReady() | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| /// Stop advertising and tear the service down. The response bytes | ||||||||||||||||||||||||||||||||||||||
| /// are wiped so a later connection cannot read a stale key. | ||||||||||||||||||||||||||||||||||||||
| func stop() { | ||||||||||||||||||||||||||||||||||||||
| wantsAdvertising = false | ||||||||||||||||||||||||||||||||||||||
| responseBytes.resetBytes(in: 0..<responseBytes.count) | ||||||||||||||||||||||||||||||||||||||
| responseBytes = Data() | ||||||||||||||||||||||||||||||||||||||
| manager?.stopAdvertising() | ||||||||||||||||||||||||||||||||||||||
| manager?.removeAllServices() | ||||||||||||||||||||||||||||||||||||||
| service = nil | ||||||||||||||||||||||||||||||||||||||
| statusCharacteristic = nil | ||||||||||||||||||||||||||||||||||||||
| responseCharacteristic = nil | ||||||||||||||||||||||||||||||||||||||
| if radioState == .advertising { | ||||||||||||||||||||||||||||||||||||||
| radioState = .poweredOn | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+61
to
+73
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Suggestion: Peripheral stop() does not reset status to .idle stop() tears down the service and wipes responseBytes but leaves status at its terminal value (.rejected, .failed, or .ready). The peripheral survives as a @StateObject, so the next start() advertises while a central reading the status characteristic immediately sees the stale terminal state instead of .idle.
Suggested change
source: |
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| /// Update the status byte and notify a subscribed browser. | ||||||||||||||||||||||||||||||||||||||
| func setStatus(_ status: BrowserLoginKeyProtocol.Status) { | ||||||||||||||||||||||||||||||||||||||
| self.status = status | ||||||||||||||||||||||||||||||||||||||
| guard let manager, let statusCharacteristic else { return } | ||||||||||||||||||||||||||||||||||||||
| _ = manager.updateValue( | ||||||||||||||||||||||||||||||||||||||
| Data([status.rawValue]), | ||||||||||||||||||||||||||||||||||||||
| for: statusCharacteristic, | ||||||||||||||||||||||||||||||||||||||
| onSubscribedCentrals: nil | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| /// Expose the encrypted response and flip the status to `ready`. | ||||||||||||||||||||||||||||||||||||||
| func deliver(response: Data) { | ||||||||||||||||||||||||||||||||||||||
| responseBytes = response | ||||||||||||||||||||||||||||||||||||||
| setStatus(.ready) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| private func publishIfReady() { | ||||||||||||||||||||||||||||||||||||||
| guard wantsAdvertising, let manager, manager.state == .poweredOn, service == nil else { return } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| let request = CBMutableCharacteristic( | ||||||||||||||||||||||||||||||||||||||
| type: BrowserLoginKeyProtocol.requestCharacteristicUUID, | ||||||||||||||||||||||||||||||||||||||
| properties: [.write], | ||||||||||||||||||||||||||||||||||||||
| value: nil, | ||||||||||||||||||||||||||||||||||||||
| permissions: [.writeable] | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
| let statusChar = CBMutableCharacteristic( | ||||||||||||||||||||||||||||||||||||||
| type: BrowserLoginKeyProtocol.statusCharacteristicUUID, | ||||||||||||||||||||||||||||||||||||||
| properties: [.read, .notify], | ||||||||||||||||||||||||||||||||||||||
| value: nil, | ||||||||||||||||||||||||||||||||||||||
| permissions: [.readable] | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
| let response = CBMutableCharacteristic( | ||||||||||||||||||||||||||||||||||||||
| type: BrowserLoginKeyProtocol.responseCharacteristicUUID, | ||||||||||||||||||||||||||||||||||||||
| properties: [.read], | ||||||||||||||||||||||||||||||||||||||
| value: nil, | ||||||||||||||||||||||||||||||||||||||
| permissions: [.readable] | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
| let service = CBMutableService(type: BrowserLoginKeyProtocol.serviceUUID, primary: true) | ||||||||||||||||||||||||||||||||||||||
| service.characteristics = [request, statusChar, response] | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| self.service = service | ||||||||||||||||||||||||||||||||||||||
| self.statusCharacteristic = statusChar | ||||||||||||||||||||||||||||||||||||||
| self.responseCharacteristic = response | ||||||||||||||||||||||||||||||||||||||
| manager.add(service) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| private func handle(writes requests: [CBATTRequest]) { | ||||||||||||||||||||||||||||||||||||||
| guard let manager, let first = requests.first else { return } | ||||||||||||||||||||||||||||||||||||||
| // A write longer than the ATT MTU arrives as several prepared | ||||||||||||||||||||||||||||||||||||||
| // writes with increasing offsets, delivered together. Stitch | ||||||||||||||||||||||||||||||||||||||
| // them back into one buffer before parsing. | ||||||||||||||||||||||||||||||||||||||
| var assembled = Data() | ||||||||||||||||||||||||||||||||||||||
| for request in requests.sorted(by: { $0.offset < $1.offset }) { | ||||||||||||||||||||||||||||||||||||||
| guard request.characteristic.uuid == BrowserLoginKeyProtocol.requestCharacteristicUUID else { | ||||||||||||||||||||||||||||||||||||||
| manager.respond(to: first, withResult: .writeNotPermitted) | ||||||||||||||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| guard request.offset == assembled.count, let chunk = request.value else { | ||||||||||||||||||||||||||||||||||||||
| manager.respond(to: first, withResult: .invalidOffset) | ||||||||||||||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| assembled.append(chunk) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| manager.respond(to: first, withResult: .success) | ||||||||||||||||||||||||||||||||||||||
| onRequest?(assembled) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| private func handle(read request: CBATTRequest) { | ||||||||||||||||||||||||||||||||||||||
| guard let manager else { return } | ||||||||||||||||||||||||||||||||||||||
| let bytes: Data | ||||||||||||||||||||||||||||||||||||||
| switch request.characteristic.uuid { | ||||||||||||||||||||||||||||||||||||||
| case BrowserLoginKeyProtocol.statusCharacteristicUUID: | ||||||||||||||||||||||||||||||||||||||
| bytes = Data([status.rawValue]) | ||||||||||||||||||||||||||||||||||||||
| case BrowserLoginKeyProtocol.responseCharacteristicUUID: | ||||||||||||||||||||||||||||||||||||||
| bytes = responseBytes | ||||||||||||||||||||||||||||||||||||||
| default: | ||||||||||||||||||||||||||||||||||||||
| manager.respond(to: request, withResult: .readNotPermitted) | ||||||||||||||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| guard request.offset <= bytes.count else { | ||||||||||||||||||||||||||||||||||||||
| manager.respond(to: request, withResult: .invalidOffset) | ||||||||||||||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| request.value = bytes.subdata(in: request.offset..<bytes.count) | ||||||||||||||||||||||||||||||||||||||
| manager.respond(to: request, withResult: .success) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| // The manager was created with a nil queue, so CoreBluetooth calls these | ||||||||||||||||||||||||||||||||||||||
| // on the main queue. The `@preconcurrency` conformance keeps the methods | ||||||||||||||||||||||||||||||||||||||
| // main-actor isolated (checked at runtime) so the non-Sendable manager | ||||||||||||||||||||||||||||||||||||||
| // and ATT requests can be used in place. | ||||||||||||||||||||||||||||||||||||||
| extension BrowserLoginPeripheral: @preconcurrency CBPeripheralManagerDelegate { | ||||||||||||||||||||||||||||||||||||||
| func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { | ||||||||||||||||||||||||||||||||||||||
| switch peripheral.state { | ||||||||||||||||||||||||||||||||||||||
| case .poweredOn: | ||||||||||||||||||||||||||||||||||||||
| radioState = .poweredOn | ||||||||||||||||||||||||||||||||||||||
| publishIfReady() | ||||||||||||||||||||||||||||||||||||||
| case .poweredOff: | ||||||||||||||||||||||||||||||||||||||
| radioState = .poweredOff | ||||||||||||||||||||||||||||||||||||||
| case .unauthorized: | ||||||||||||||||||||||||||||||||||||||
| radioState = .unauthorized | ||||||||||||||||||||||||||||||||||||||
| case .unsupported: | ||||||||||||||||||||||||||||||||||||||
| radioState = .unsupported | ||||||||||||||||||||||||||||||||||||||
| default: | ||||||||||||||||||||||||||||||||||||||
| radioState = .unknown | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| func peripheralManager( | ||||||||||||||||||||||||||||||||||||||
| _ peripheral: CBPeripheralManager, | ||||||||||||||||||||||||||||||||||||||
| didAdd service: CBService, | ||||||||||||||||||||||||||||||||||||||
| error: Error? | ||||||||||||||||||||||||||||||||||||||
| ) { | ||||||||||||||||||||||||||||||||||||||
| if let error { | ||||||||||||||||||||||||||||||||||||||
| lastError = "Could not publish the Bluetooth service: \(error.localizedDescription)" | ||||||||||||||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| peripheral.startAdvertising([ | ||||||||||||||||||||||||||||||||||||||
| CBAdvertisementDataServiceUUIDsKey: [BrowserLoginKeyProtocol.serviceUUID], | ||||||||||||||||||||||||||||||||||||||
| CBAdvertisementDataLocalNameKey: localName, | ||||||||||||||||||||||||||||||||||||||
| ]) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { | ||||||||||||||||||||||||||||||||||||||
| if let error { | ||||||||||||||||||||||||||||||||||||||
| lastError = "Could not start advertising: \(error.localizedDescription)" | ||||||||||||||||||||||||||||||||||||||
| } else { | ||||||||||||||||||||||||||||||||||||||
| radioState = .advertising | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { | ||||||||||||||||||||||||||||||||||||||
| handle(read: request) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { | ||||||||||||||||||||||||||||||||||||||
| handle(writes: requests) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import Foundation | ||
| import SwiftDashSDK | ||
|
|
||
| /// Renders a key's protocol 14 limits and contract bounds for the key | ||
| /// screens: credits as DASH, expiry as a date plus how far away it is, | ||
| /// and bounds as the contract they point at. | ||
| enum KeyLimitsFormatting { | ||
| /// 1 DASH = 100 000 000 duffs = 100 000 000 000 credits. | ||
| static let creditsPerDash: UInt64 = 100_000_000_000 | ||
|
|
||
| /// Credits rendered as DASH, trimming trailing zeros: 1_000_000_000 → "0.01 DASH". | ||
| static func dash(_ credits: UInt64) -> String { | ||
| "\(dashNumber(credits)) DASH" | ||
| } | ||
|
|
||
| /// The DASH amount alone, at full credit precision: 1_000_000_000 → "0.01". | ||
| static func dashNumber(_ credits: UInt64) -> String { | ||
| let whole = credits / creditsPerDash | ||
| let fraction = credits % creditsPerDash | ||
| var digits = String(fraction) | ||
| digits = String(repeating: "0", count: 11 - digits.count) + digits | ||
| while digits.hasSuffix("0") { digits.removeLast() } | ||
| return digits.isEmpty ? "\(whole)" : "\(whole).\(digits)" | ||
| } | ||
|
|
||
| /// "0.004 of 0.01 DASH left" or, without a remaining figure, "0.01 DASH". | ||
| static func budget(total: UInt64, remaining: UInt64?) -> String { | ||
| guard let remaining else { return dash(total) } | ||
| return "\(dashNumber(remaining)) of \(dash(total)) left" | ||
| } | ||
|
|
||
| /// Whether the key has expired at `now`. The expiry instant itself is | ||
| /// already expired, as consensus counts it. | ||
| static func isExpired(expiresAt: TimestampMillis, now: Date) -> Bool { | ||
| UInt64(now.timeIntervalSince1970 * 1000) >= expiresAt | ||
| } | ||
|
|
||
| /// The expiry as an absolute local date and time. | ||
| static func expiryDate(_ expiresAt: TimestampMillis, locale: Locale = .current) -> String { | ||
| let date = Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) | ||
| let formatter = DateFormatter() | ||
| formatter.locale = locale | ||
| formatter.dateStyle = .medium | ||
| formatter.timeStyle = .short | ||
| return formatter.string(from: date) | ||
| } | ||
|
|
||
| /// "Expires in 3 hours" or "Expired 2 days ago". | ||
| static func expiryRelative(_ expiresAt: TimestampMillis, now: Date, locale: Locale = .current) -> String { | ||
| let date = Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) | ||
| let formatter = RelativeDateTimeFormatter() | ||
| formatter.locale = locale | ||
| formatter.unitsStyle = .full | ||
| let relative = formatter.localizedString(for: date, relativeTo: now) | ||
| return isExpired(expiresAt: expiresAt, now: now) ? "Expired \(relative)" : "Expires \(relative)" | ||
| } | ||
|
|
||
| /// Short, readable rendering of contract bounds. | ||
| static func bounds(_ bounds: ContractBounds) -> String { | ||
| switch bounds { | ||
| case .singleContract(let id): | ||
| return "Contract \(shortId(id))" | ||
| case .singleContractDocumentType(let id, let documentTypeName): | ||
| return "Contract \(shortId(id)), type \(documentTypeName)" | ||
| } | ||
| } | ||
|
|
||
| static func shortId(_ id: Data) -> String { | ||
| let base58 = id.toBase58String() | ||
| guard base58.count > 13 else { return base58 } | ||
| return "\(base58.prefix(6))…\(base58.suffix(6))" | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: dashpay/platform
Length of output: 41562
🏁 Script executed:
Repository: dashpay/platform
Length of output: 50373
🏁 Script executed:
Repository: dashpay/platform
Length of output: 50373
🏁 Script executed:
Repository: dashpay/platform
Length of output: 9028
🏁 Script executed:
Repository: dashpay/platform
Length of output: 5130
Reset the protocol status when the peripheral stops.
stop()removes the service but leavesstatusat.failedor.rejected. The nextstart()publishes a new status characteristic, and reads return that stale value. A fresh advertisement can therefore report a terminal result from the previous session instead of the protocol’s.idlestate.Set
status = .idlewhile resetting the peripheral.Proposed fix
func stop() { wantsAdvertising = false + status = .idle responseBytes.resetBytes(in: 0..<responseBytes.count)📝 Committable suggestion
🤖 Prompt for AI Agents