diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 929566e384..df9571d4ae 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1021,7 +1021,7 @@ INFOPLIST_FILE = Bitkit/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = Bitkit; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; - INFOPLIST_KEY_NSBluetoothAlwaysUsageDescription = "Bitkit uses Bluetooth to connect to your hardware wallet for signing transactions."; + INFOPLIST_KEY_NSBluetoothAlwaysUsageDescription = "Bitkit uses Bluetooth to connect to your hardware wallet and to exchange payment requests with phones nearby."; INFOPLIST_KEY_NSCameraUsageDescription = "Bitkit needs access to the camera to scan QR codes"; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; @@ -1075,7 +1075,7 @@ INFOPLIST_FILE = Bitkit/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = Bitkit; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; - INFOPLIST_KEY_NSBluetoothAlwaysUsageDescription = "Bitkit uses Bluetooth to connect to your hardware wallet for signing transactions."; + INFOPLIST_KEY_NSBluetoothAlwaysUsageDescription = "Bitkit uses Bluetooth to connect to your hardware wallet and to exchange payment requests with phones nearby."; INFOPLIST_KEY_NSCameraUsageDescription = "Bitkit needs access to the camera to scan QR codes"; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index b687e946f9..43588de730 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1500,6 +1500,8 @@ struct AppScene: View { if settings.pinEnabled { // If PIN is enabled, lock the app when the app goes to the background incomingPaymentRequestPreparation?.suspendForAppLock(sheets: sheets) + scannerManager.invalidateScansForAppLock() + app.noteAppLocked() isPinVerified = false } hwWalletManager.onAppBackgrounded() diff --git a/Bitkit/Assets.xcassets/Illustrations/nfc.imageset/Contents.json b/Bitkit/Assets.xcassets/Illustrations/nfc.imageset/Contents.json new file mode 100644 index 0000000000..27c92c5511 --- /dev/null +++ b/Bitkit/Assets.xcassets/Illustrations/nfc.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "filename" : "nfc.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Bitkit/Assets.xcassets/Illustrations/nfc.imageset/nfc.png b/Bitkit/Assets.xcassets/Illustrations/nfc.imageset/nfc.png new file mode 100644 index 0000000000..687354a277 Binary files /dev/null and b/Bitkit/Assets.xcassets/Illustrations/nfc.imageset/nfc.png differ diff --git a/Bitkit/Bitkit.entitlements b/Bitkit/Bitkit.entitlements index 6c673bbaf5..8bdefab6aa 100644 --- a/Bitkit/Bitkit.entitlements +++ b/Bitkit/Bitkit.entitlements @@ -4,6 +4,10 @@ aps-environment development + com.apple.developer.nfc.readersession.formats + + TAG + com.apple.developer.aps-environment development com.apple.security.app-sandbox diff --git a/Bitkit/Components/Scanner.swift b/Bitkit/Components/Scanner.swift index 3120777c29..71ec16e215 100644 --- a/Bitkit/Components/Scanner.swift +++ b/Bitkit/Components/Scanner.swift @@ -189,13 +189,17 @@ private final class QRCodeScannerViewController: UIViewController, AVCaptureVide private struct ScannerCornerButtons: View { @Binding var isTorchOn: Bool let onImageSelection: (PhotosPickerItem?) async -> Void + /// True while the photo picker is open. + @Binding var isPickingPhoto: Bool @State private var selectedItem: PhotosPickerItem? var body: some View { GeometryReader { _ in HStack { - PhotosPicker(selection: $selectedItem, matching: .images) { + Button { + isPickingPhoto = true + } label: { Image("picture") .resizable() .aspectRatio(contentMode: .fit) @@ -205,6 +209,7 @@ private struct ScannerCornerButtons: View { .background(Color.white16) .clipShape(Circle()) } + .photosPicker(isPresented: $isPickingPhoto, selection: $selectedItem, matching: .images) .onChange(of: selectedItem) { _, item in Task { await onImageSelection(item) } } @@ -223,17 +228,146 @@ private struct ScannerCornerButtons: View { } } +// MARK: - Scanner Sources + +/// Which nearby sources a payment scanner is listening to, for its status pill. +struct ScannerSources: Equatable { + var nfc: Bool + var bluetooth: Bool + + var statusKey: String { + switch (nfc, bluetooth) { + case (true, true): "other__scan_status_qr_nfc_bluetooth" + case (true, false): "other__scan_status_qr_nfc" + case (false, true): "other__scan_status_qr_bluetooth" + case (false, false): "other__scan_status_qr" + } + } +} + +// MARK: - Scanner Status Overlay Component + +/// Status pill at the bottom of the camera preview, with buttons for sources that still need the user. +/// +/// iOS cannot detect NFC tags passively, so the NFC button (or the pill, when no buttons are shown) starts +/// an NFC read through the system sheet. The Bluetooth button asks for Bluetooth permission. +private struct ScannerStatusOverlay: View { + let isNfcAvailable: Bool + let showsBluetoothButton: Bool + let isBluetoothScanning: Bool + let onNfcRead: (() async -> Void)? + let onBluetooth: () -> Void + + private var showsButtons: Bool { + showsBluetoothButton + } + + private var sources: ScannerSources { + ScannerSources(nfc: isNfcAvailable && !showsButtons, bluetooth: isBluetoothScanning) + } + + var body: some View { + VStack(spacing: 8) { + if showsButtons { + HStack(spacing: 8) { + ScannerSourceButton(icon: "bluetooth-connected", label: t("other__bluetooth_enable"), testID: "ScannerBluetoothButton") { + onBluetooth() + } + if isNfcAvailable, let onNfcRead { + ScannerSourceButton(icon: "broadcast", label: t("other__nfc_read_button"), testID: "ScannerNfcButton") { + Task { await onNfcRead() } + } + } + } + } + + Button { + guard sources.nfc, let onNfcRead else { return } + Task { await onNfcRead() } + } label: { + HStack(spacing: 8) { + Image(sources.nfc || sources.bluetooth ? "broadcast" : "scan") + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 16, height: 16) + .foregroundColor(.white64) + CaptionMText(t(sources.statusKey), textColor: .white64) + } + .frame(maxWidth: .infinity) + .padding(.horizontal, 16) + .padding(.vertical, 12) + .background(Color.black50) + .clipShape(Capsule()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("ScannerStatus") + } + .padding(16) + .frame(maxHeight: .infinity, alignment: .bottom) + } +} + +private struct ScannerSourceButton: View { + let icon: String + /// Spoken by VoiceOver, since the button shows only an icon. + let label: String + let testID: String + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(icon) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 16, height: 16) + .foregroundColor(.textPrimary) + .frame(maxWidth: .infinity) + .frame(height: 40) + .background(Color.gray5) + .clipShape(Capsule()) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + .accessibilityIdentifier(testID) + } +} + // MARK: - Scanner Component struct Scanner: View { var accentColor: Color = .brandAccent var permissionDescription: String = t("other__camera_no_text") @Environment(CameraManager.self) private var cameraManager + @Environment(\.scenePhase) private var scenePhase let onScan: (QRCodePayload) async -> Void let onImageSelection: (PhotosPickerItem?) async -> Void + /// Starts an NFC read; nil hides the NFC control (non-payment scanners, devices without NFC). + var onNfcRead: (() async -> Void)? + /// Receives a request read over Bluetooth from a nearby phone, with a check that turns false once scanning stops + /// (scanner hidden, paused, or the app inactive), and returns whether it was taken; nil turns Bluetooth scanning off. + var onNearbyRequest: ((String, @escaping () -> Bool) async -> Bool)? + /// Pauses Bluetooth scanning while something covers the scanner (for example the payment sheet it opened). + var isNearbyPaused = false @State private var isTorchOn = false + /// The photo picker covers the scanner too: a Bluetooth request must not open Send behind it. + @State private var isPickingPhoto = false + @State private var nearby = NearbyPaymentScanner() + + private var isPaymentScanner: Bool { + onNfcRead != nil || onNearbyRequest != nil + } + + private var needsBluetoothPermission: Bool { + onNearbyRequest != nil && !nearby.isAuthorized + } + + private var bluetoothPermissionAction: (() -> Void)? { + guard needsBluetoothPermission else { return nil } + let nearby = nearby + return { nearby.requestAuthorization() } + } var body: some View { ZStack { @@ -254,7 +388,27 @@ struct Scanner: View { isTorchOn: $isTorchOn, onImageSelection: { item in await onImageSelection(item) - } + }, + isPickingPhoto: $isPickingPhoto + ) + + if isPaymentScanner { + ScannerStatusOverlay( + isNfcAvailable: onNfcRead != nil, + showsBluetoothButton: needsBluetoothPermission, + isBluetoothScanning: nearby.isScanning, + onNfcRead: onNfcRead, + onBluetooth: { nearby.requestAuthorization() } + ) + } + } else if isPaymentScanner { + ScannerPermissionRequest( + accentColor: accentColor, + title: t("other__scan_to_pay_title"), + description: t("other__scan_to_pay_text"), + onRequestPermission: cameraManager.requestPermission, + onBluetooth: bluetoothPermissionAction, + onNfcRead: onNfcRead ) } else { ScannerPermissionRequest( @@ -267,28 +421,87 @@ struct Scanner: View { .cornerRadius(16) .contentShape(Rectangle()) .onAppear { + startNearbyScanning() guard !cameraManager.hasPermission else { return } cameraManager.requestPermissionIfNeeded() } + .onDisappear { + nearby.stop() + } + .onChange(of: scenePhase) { _, phase in + if phase == .active { + startNearbyScanning() + } else { + nearby.stop() + } + } + .onChange(of: isNearbyHeld) { _, isPaused in + if isPaused { + nearby.stop() + } else { + startNearbyScanning() + } + } + } + + private var isNearbyHeld: Bool { + isNearbyPaused || isPickingPhoto + } + + private func startNearbyScanning() { + guard let onNearbyRequest, !isNearbyHeld, scenePhase == .active else { return } + nearby.start(onRequest: onNearbyRequest) } } struct ScannerPermissionRequest: View { var accentColor: Color = .brandAccent + var title: String = t("other__camera_no_title") var description: String = t("other__camera_no_text") let onRequestPermission: () -> Void + /// Payment scanners also offer Bluetooth and NFC, which work without the camera. + var onBluetooth: (() -> Void)? + var onNfcRead: (() async -> Void)? + + private var showsSourceButtons: Bool { + onBluetooth != nil || onNfcRead != nil + } var body: some View { - VStack(spacing: 0) { - DisplayText(t("other__camera_no_title"), accentColor: accentColor) + VStack(alignment: showsSourceButtons ? .leading : .center, spacing: 0) { + DisplayText(title, accentColor: accentColor) .padding(.bottom, 8) BodyMText(description) .padding(.bottom, 32) - CustomButton( - title: t("other__camera_no_button"), - icon: Image("camera").foregroundColor(.textPrimary) - ) { - onRequestPermission() + if showsSourceButtons { + HStack(spacing: 8) { + ScannerSourceButton( + icon: "camera", + label: t("other__camera_no_button"), + testID: "ScannerCameraButton", + action: onRequestPermission + ) + if let onBluetooth { + ScannerSourceButton( + icon: "bluetooth-connected", + label: t("other__bluetooth_enable"), + testID: "ScannerBluetoothButton", + action: onBluetooth + ) + } + if let onNfcRead { + ScannerSourceButton(icon: "broadcast", label: t("other__nfc_read_button"), testID: "ScannerNfcButton") { + Task { await onNfcRead() } + } + } + } + } else { + CustomButton( + title: t("other__camera_no_button"), + icon: Image("camera").foregroundColor(.textPrimary) + ) { + onRequestPermission() + } } } .padding(.horizontal, 32) diff --git a/Bitkit/Info.plist b/Bitkit/Info.plist index ccc26042b4..20402da083 100644 --- a/Bitkit/Info.plist +++ b/Bitkit/Info.plist @@ -73,9 +73,15 @@ NSBluetoothAlwaysUsageDescription - Bitkit uses Bluetooth to connect to your hardware wallet for signing transactions. + Bitkit uses Bluetooth to connect to your hardware wallet and to exchange payment requests with phones nearby. NSBluetoothPeripheralUsageDescription - Bitkit uses Bluetooth to connect to your hardware wallet for signing transactions. + Bitkit uses Bluetooth to connect to your hardware wallet and to exchange payment requests with phones nearby. + NFCReaderUsageDescription + Bitkit uses NFC to read payment requests from payment terminals and other phones. + com.apple.developer.nfc.readersession.iso7816.select-identifiers + + D2760000850101 + NSFaceIDUsageDescription Bitkit uses Face ID to securely authenticate access to your wallet and protect your Bitcoin. UIAppFonts diff --git a/Bitkit/MainNavView.swift b/Bitkit/MainNavView.swift index da57eb01b1..640dd4d0c3 100644 --- a/Bitkit/MainNavView.swift +++ b/Bitkit/MainNavView.swift @@ -258,6 +258,15 @@ struct MainNavView: View { ) { config in QuickpaySheet(config: config) } + .sheet( + item: $sheets.nfcIntroSheetItem, + onDismiss: { + sheets.hideSheetIfActive(.nfcIntro, reason: "NFC intro sheet dismissed") + app.hasSeenNfcIntro = true + } + ) { + config in NfcIntroSheet(config: config) + } .sheet( item: $sheets.sendSheetItem, onDismiss: { diff --git a/Bitkit/Managers/ScannerManager.swift b/Bitkit/Managers/ScannerManager.swift index 6072b640f5..ac6df7af64 100644 --- a/Bitkit/Managers/ScannerManager.swift +++ b/Bitkit/Managers/ScannerManager.swift @@ -20,12 +20,38 @@ class ScannerManager: ObservableObject { private var sheets: SheetViewModel? private var wallet: WalletViewModel? private weak var hwWalletManager: HwWalletManager? + private let nfcReader: NfcPaymentReading private var isHandlingScan = false + /// Photos the user picked that are still loading or decoding, each with a check that turns false once its scanner + /// visit ends. A nearby request waits until every photo is handled or its visit ends. + private var pendingImageScans: [UUID: () -> Bool] = [:] - init(playScanSuccess: @escaping () -> Void = { Haptics.play(.scanSuccess) }) { + private var isImageScanPending: Bool { + pendingImageScans.values.contains { $0() } + } + + /// Set while a Bluetooth request holds the scan lock. A QR code or NFC read the user starts takes the lock from it. + private var nearbyScanID: UUID? + /// Whether the last main scan opened a payment flow, so a Bluetooth read knows the request was taken. + private var didOpenScanFlow = false + /// Raised when the app locks, so a scan still decoding cannot open a payment behind the PIN screen or after it. + private var lockGeneration = 0 + /// A sheet replacement a scan started that has not run yet, so a lock can cancel the route it would open. + private var pendingRouteReplacement: Int? + + init( + nfcReader: NfcPaymentReading? = nil, + playScanSuccess: @escaping () -> Void = { Haptics.play(.scanSuccess) } + ) { + self.nfcReader = nfcReader ?? NfcReader.shared self.playScanSuccess = playScanSuccess } + /// Whether this device can read NFC tags; NFC controls are hidden otherwise. + var isNfcReadingAvailable: Bool { + nfcReader.isAvailable + } + func configure( app: AppViewModel, contactsManager: ContactsManager? = nil, @@ -49,14 +75,20 @@ class ScannerManager: ObservableObject { } func handleScan(_ uri: String, context: ScannerContext, isCurrent: () -> Bool = { true }) async { - guard !isHandlingScan, isCurrent() else { return } - isHandlingScan = true + guard isCurrent(), beginUserScan() else { return } defer { isHandlingScan = false } - await processScan(uri, context: context, isCurrent: isCurrent) + // A lookup can outlast a PIN lock; its result must not route, or choose QuickPay, after the unlock. + let isBeforeLock = lockCheck() + await processScan(uri, context: context, isCurrent: { isCurrent() && isBeforeLock() }) } - private func processScan(_ uri: String, context: ScannerContext, isCurrent: () -> Bool) async { + private func processScan( + _ uri: String, + context: ScannerContext, + scope: ScanHandlingScope = .unrestricted, + isCurrent: () -> Bool + ) async { let uri = uri.trimmingCharacters(in: .whitespacesAndNewlines) guard !uri.isEmpty else { return } @@ -66,9 +98,9 @@ class ScannerManager: ObservableObject { handleAddContactScan(uri) case .main: playScanSuccess() - await handleMainScan(uri, isCurrent: isCurrent) + await handleMainScan(uri, scope: scope, isCurrent: isCurrent) case .send: - await processSendScan(uri, isCurrent: isCurrent) { _ in } + await processSendScan(uri, scope: scope, isCurrent: isCurrent) { _ in } case .electrum: playScanSuccess() await handleElectrumScan(uri) @@ -93,18 +125,21 @@ class ScannerManager: ObservableObject { navigation?.navigate(.addContact(publicKey: input)) } - private func handleMainScan(_ uri: String, isCurrent: () -> Bool) async { + private func handleMainScan(_ uri: String, scope: ScanHandlingScope = .unrestricted, isCurrent: () -> Bool) async { + didOpenScanFlow = false guard let app else { return } - do { if let route = try resolveUsdtPaymentRoute(input: uri) { guard app.contactPaymentContext == nil, wallet?.usdtWallet.isSendPresented == false else { return } let path = navigation?.path + let replacementBefore = sheets?.latestReplacementID sheets?.hideSheetBeforePerforming(reason: "Scanner routed USDT payment") { [weak self] in guard let self, app.contactPaymentContext == nil, wallet?.usdtWallet.isSendPresented == false, navigation?.path == path else { return } navigation?.navigate(route) } + recordRouteReplacement(since: replacementBefore) + didOpenScanFlow = true return } if handlePubkyRouteIfNeeded(uri) { @@ -113,18 +148,25 @@ class ScannerManager: ObservableObject { try await app.handleScannedData( uri, + scope: scope, alternativeOnchainBalanceSats: hwWalletManager?.maximumFundingBalanceSats ?? 0, isCurrentScan: isCurrent ) guard isCurrent(), shouldOpenPaymentFlow(for: uri) else { return } if let currency, let settings, let sheets { + let presentationBefore = sheets.activeSheetConfiguration?.presentationID + let replacementBefore = sheets.latestReplacementID PaymentNavigationHelper.openPaymentSheet( app: app, currency: currency, settings: settings, sheetViewModel: sheets ) + recordRouteReplacement(since: replacementBefore) + // A refused request (e.g. an expired invoice) only shows a toast and opens no sheet. + didOpenScanFlow = !app.didRejectScannedPayment && + sheets.activeSheetConfiguration?.presentationID != presentationBefore } } catch { guard isCurrent(), !(error is CancellationError) else { return } @@ -137,6 +179,14 @@ class ScannerManager: ObservableObject { } } + /// Remembers the replacement a route started, so a lock before it runs drops it. Called right after the + /// synchronous route call with the id read just before it, so a sheet that replaced the scanner while the scan + /// was decoding (e.g. a received payment) is not claimed. + private func recordRouteReplacement(since before: Int?) { + guard let replacement = sheets?.latestReplacementID, replacement != before else { return } + pendingRouteReplacement = replacement + } + private func handlePubkyRouteIfNeeded(_ input: String, hiding sheetId: SheetID? = .scanner, reason: String = "Scanner routed pubky key") -> Bool { guard let navigation, let route = resolvePastedPubkyRoute( @@ -169,11 +219,11 @@ class ScannerManager: ObservableObject { isCurrent: () -> Bool = { true }, completion: @escaping (SendRoute?) -> Void ) async { - guard !isHandlingScan, isCurrent() else { return } - isHandlingScan = true + guard isCurrent(), beginUserScan() else { return } defer { isHandlingScan = false } - await processSendScan(uri, scope: scope, isCurrent: isCurrent, completion: completion) + let isBeforeLock = lockCheck() + await processSendScan(uri, scope: scope, isCurrent: { isCurrent() && isBeforeLock() }, completion: completion) } private func processSendScan( @@ -200,7 +250,7 @@ class ScannerManager: ObservableObject { playScanSuccess() do { - if scope == .unrestricted, case let .usdtPayment(recipient, amount)? = try resolveUsdtPaymentRoute(input: uri) { + if scope != .onchainPayments, case let .usdtPayment(recipient, amount)? = try resolveUsdtPaymentRoute(input: uri) { guard app.contactPaymentContext == nil, wallet?.usdtWallet.isSendPresented == false else { completion(nil) return @@ -262,6 +312,188 @@ class ScannerManager: ObservableObject { await handleSendScan(uri, scope: scope, isCurrent: isCurrent, completion: completion) } + /// Reads a payment request over NFC and handles it exactly like a scanned QR code. + /// The read holds the scan lock from the start, so a Bluetooth request can't route while the NFC sheet is up. + func handleNfcRead(context: ScannerContext, isCurrent: () -> Bool = { true }) async { + let isCurrentOrigin = originCheck() + func isStillCurrent() -> Bool { + isCurrent() && isCurrentOrigin() + } + guard isStillCurrent(), beginUserScan() else { return } + defer { isHandlingScan = false } + guard let uri = await readNfcPaymentRequest(isCurrent: isStillCurrent), isStillCurrent() else { return } + await processScan(uri, context: context, isCurrent: isStillCurrent) + } + + /// Reads a payment request over NFC from the Send sheet and resolves it like a scanned QR code. + func handleSendNfcRead( + scope: ScanHandlingScope = .unrestricted, + isCurrent: () -> Bool = { true }, + completion: @escaping (SendRoute?) -> Void + ) async { + let isCurrentOrigin = originCheck() + func isStillCurrent() -> Bool { + isCurrent() && isCurrentOrigin() + } + guard isStillCurrent(), beginUserScan() else { + completion(nil) + return + } + defer { isHandlingScan = false } + guard let uri = await readNfcPaymentRequest(isCurrent: isStillCurrent), isStillCurrent() else { + completion(nil) + return + } + await processSendScan(uri, scope: scope, isCurrent: isStillCurrent, completion: completion) + } + + /// Whether a request read over Bluetooth is accepted: a `bitcoin:` URI, a `lightning:` BOLT11 invoice or a USDT + /// `ethereum:` request. Unlike a camera or NFC read, a Bluetooth request can come from any nearby device before the + /// user picks it, so nothing that is resolved over the network before review is taken: LNURL and Lightning + /// addresses, also as a unified URI's `lightning` part, are refused. So are sign-in, setup, withdraw and contact + /// links, and BOLT12 offers, which the decoder does not read. An invoice is checked locally + /// (`ScannedPaymentRequest.isBolt11Invoice`), since a Lightning address can begin like one. A `bitcoin:` request + /// with a required (`req-`) parameter is refused, since none is supported. + nonisolated static func isNearbyPaymentRequest(_ uri: String) -> Bool { + typealias Request = ScannedPaymentRequest + let lowercase = uri.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + if Request.hasLiteralPrefix(lowercase, "ethereum:") { + return true + } + if Request.hasLiteralPrefix(lowercase, "lightning:") { + return Request.isBolt11Invoice(Request.droppingLiteralPrefix(lowercase, "lightning:")) + } + guard Request.hasLiteralPrefix(lowercase, "bitcoin:"), !Request.hasRequiredParameter(lowercase) else { return false } + // Split as the decoder splits, so a delimiter followed by a combining mark still separates the fields. + return Request.queryFields(lowercase).allSatisfy { field in + !Request.hasLiteralPrefix(field, "lightning=") || Request.isBolt11Invoice(Request.droppingLiteralPrefix(field, "lightning=")) + } + } + + /// Handles a request read over Bluetooth. It always opens the normal review (QuickPay does not apply) and is + /// limited to on-chain, BOLT11 Lightning and USDT requests. + /// - Returns: false when the request was not taken (refused, or another scan is being handled), so the caller + /// can keep listening. + @discardableResult + func handleNearbyRequest(_ request: String, context: ScannerContext, isCurrent: () -> Bool = { true }) async -> Bool { + guard app != nil, context == .main || context == .send else { return false } + let uri = ScannedPaymentRequest.normalized(request) + guard Self.isNearbyPaymentRequest(uri) else { + if isCurrent() { + showUnsupportedQRCodeError() + } + return false + } + // A request arrives unprompted, so it must not open anything once the user has left the scanner or started + // a scan of their own. + let isCurrentOrigin = originCheck() + guard isCurrent(), isCurrentOrigin(), let scanID = beginNearbyScan() else { return false } + defer { endNearbyScan(scanID) } + func isStillCurrent() -> Bool { + nearbyScanID == scanID && isCurrent() && isCurrentOrigin() + } + if context == .send { + var routed = false + await processSendScan(uri, scope: .paymentRequests, isCurrent: isStillCurrent) { routed = $0 != nil } + return routed + } + await processScan(uri, context: .main, scope: .paymentRequests, isCurrent: isStillCurrent) + return nearbyScanID == scanID && didOpenScanFlow + } + + /// Send-sheet variant of `handleNearbyRequest`. + @discardableResult + func handleSendNearbyRequest( + _ request: String, + scope: ScanHandlingScope = .unrestricted, + isCurrent: () -> Bool = { true }, + completion: @escaping (SendRoute?) -> Void + ) async -> Bool { + let uri = ScannedPaymentRequest.normalized(request) + guard app != nil, Self.isNearbyPaymentRequest(uri) else { + if isCurrent() { + showUnsupportedQRCodeError() + } + completion(nil) + return false + } + let isCurrentOrigin = originCheck() + guard isCurrent(), isCurrentOrigin(), let scanID = beginNearbyScan() else { return false } + defer { endNearbyScan(scanID) } + func isStillCurrent() -> Bool { + nearbyScanID == scanID && isCurrent() && isCurrentOrigin() + } + var routed = false + await processSendScan( + uri, + scope: scope == .onchainPayments ? .onchainPayments : .paymentRequests, + isCurrent: isStillCurrent + ) { route in + routed = route != nil + completion(route) + } + return routed + } + + /// Takes the scan lock for a QR code or NFC read the user started. A Bluetooth request still decoding gives it up. + private func beginUserScan() -> Bool { + if isHandlingScan { + guard let nearbyScanID else { return false } + app?.releaseQuickPaySuppression(nearbyScanID) + self.nearbyScanID = nil + } + isHandlingScan = true + return true + } + + private func beginNearbyScan() -> UUID? { + guard !isHandlingScan, !isImageScanPending else { return nil } + let scanID = UUID() + isHandlingScan = true + nearbyScanID = scanID + // A Bluetooth request always opens the normal review. The suppression ends with the request or when a user + // scan takes over. + app?.suppressQuickPay(scanID) + return scanID + } + + private func endNearbyScan(_ scanID: UUID) { + app?.releaseQuickPaySuppression(scanID) + // A user scan that took the lock releases it itself. + guard nearbyScanID == scanID else { return } + nearbyScanID = nil + isHandlingScan = false + } + + /// Reads a payment request over NFC. A failure shows its error only while [isCurrent] holds: a read that ends after + /// the payer left the scanner, or the app locked, ends quietly. + private func readNfcPaymentRequest(isCurrent: () -> Bool) async -> String? { + do { + let request = try await nfcReader.readPaymentRequest(alertMessage: t("other__nfc_alert")) + let uri = ScannedPaymentRequest.normalized(request) + // A QR code with a required parameter still goes to the decoder; core handles those after its bump (#1344). + guard !ScannedPaymentRequest.hasRequiredParameter(uri) else { throw NfcReadError.noPaymentRequest } + return uri + } catch let error as NfcReadError { + Logger.warn("NFC read failed: \(error)", context: "ScannerManager") + if isCurrent() { + showNfcReadError(error) + } + return nil + } catch { + Logger.error(error, context: "ScannerManager NFC read") + if isCurrent() { + app?.toast(error) + } + return nil + } + } + + private func showNfcReadError(_ error: NfcReadError) { + guard !error.isSilent, error != .busy else { return } + app?.toast(type: .error, title: t("other__nfc_error_header"), description: error.message) + } + private func shouldOpenPaymentFlow(for uri: String) -> Bool { !SamRockSetupRequest.isProtocolURL(uri) && !PubkyAuthRequest.isProtocolURL(uri) } @@ -320,32 +552,33 @@ class ScannerManager: ObservableObject { func handleImageSelection( _ item: PhotosPickerItem?, context: ScannerContext, + isCurrent: @escaping () -> Bool = { true }, scope: ScanHandlingScope = .unrestricted, completion: @escaping (SendRoute?) -> Void = { _ in } ) async { guard let item else { return } - await handleImageScan(context: context, scope: scope, decode: { + await handleImageScan(context: context, isCurrent: isCurrent, scope: scope, decode: { try await QRCodeImageDecoder.decode(item) }, completion: completion) } func handleImageScan( context: ScannerContext, + isCurrent: @escaping () -> Bool = { true }, scope: ScanHandlingScope = .unrestricted, decode: () async throws -> QRCodePayload, completion: @escaping (SendRoute?) -> Void = { _ in } ) async { guard let app else { return } - let presentationID = sheets?.activeSheetConfiguration?.presentationID - let navigationPath = navigation?.path let inputGeneration = app.sendStateGeneration - func isCurrentOrigin() -> Bool { - !Task.isCancelled && sheets?.activeSheetConfiguration?.presentationID == presentationID && - navigation?.path == navigationPath - } + // One check for the scanner visit the photo was picked in, used both to hold off nearby requests and to route + // the photo: the sheet, the navigation path generation (leaving and reopening a route is a new visit) and the + // caller's own visit, such as Send Options' inside its sheet. + let isOriginShown = originCheck() + let isCurrentOrigin = { isCurrent() && isOriginShown() } do { - let payload = try await decode() + let payload = try await decodeBeforeNearbyRequests(decode, isCurrent: isCurrentOrigin) guard isCurrentOrigin(), context != .send || app.sendStateGeneration == inputGeneration else { return } if context == .send { await handleSendScan(payload, scope: scope, isCurrent: isCurrentOrigin, completion: completion) @@ -379,6 +612,52 @@ class ScannerManager: ObservableObject { } } + /// Loads and decodes a picked photo. Like the user's other scans, the photo takes over a nearby request still + /// decoding, and it holds off new ones, since either would open Send and discard the photo. + private func decodeBeforeNearbyRequests( + _ decode: () async throws -> QRCodePayload, + isCurrent: @escaping () -> Bool + ) async throws -> QRCodePayload { + if let nearbyScanID { + app?.releaseQuickPaySuppression(nearbyScanID) + self.nearbyScanID = nil + isHandlingScan = false + } + let id = UUID() + pendingImageScans[id] = isCurrent + defer { pendingImageScans[id] = nil } + return try await decode() + } + + /// True until the app locks behind the PIN after this call. + private func lockCheck() -> () -> Bool { + let lockGeneration = lockGeneration + return { [weak self] in + self?.lockGeneration == lockGeneration + } + } + + /// True while the sheet and navigation path shown when this is called are still shown, without having left them. + private func originCheck() -> () -> Bool { + let presentationID = sheets?.activeSheetConfiguration?.presentationID + let pathGeneration = navigation?.pathGeneration + let lockGeneration = lockGeneration + return { [weak self] in + !Task.isCancelled && self?.sheets?.activeSheetConfiguration?.presentationID == presentationID && + self?.navigation?.pathGeneration == pathGeneration && self?.lockGeneration == lockGeneration + } + } + + /// Drops every scan still being handled, and a route a scan opens once its sheet has closed. Called when the app + /// locks behind the PIN. + func invalidateScansForAppLock() { + lockGeneration += 1 + if let replacement = pendingRouteReplacement { + sheets?.cancelReplacement(replacement) + pendingRouteReplacement = nil + } + } + private func showUnsupportedQRCodeError() { app?.toast( type: .error, diff --git a/Bitkit/Managers/TimedSheets/NfcIntroTimedSheet.swift b/Bitkit/Managers/TimedSheets/NfcIntroTimedSheet.swift new file mode 100644 index 0000000000..3a48debb9e --- /dev/null +++ b/Bitkit/Managers/TimedSheets/NfcIntroTimedSheet.swift @@ -0,0 +1,35 @@ +import Foundation + +/// Shows the NFC payments intro once, on devices that can read NFC tags. +struct NfcIntroTimedSheet: TimedSheetItem { + let id = SheetID.nfcIntro + let priority = TimedSheetPriority.low + let sheetItem: any SheetItem = NfcIntroSheetItem() + + private let appViewModel: AppViewModel + private let walletViewModel: WalletViewModel + private let isNfcReadingAvailable: @MainActor () -> Bool + + init( + appViewModel: AppViewModel, + walletViewModel: WalletViewModel, + isNfcReadingAvailable: @escaping @MainActor () -> Bool = { NfcReader.shared.isAvailable } + ) { + self.appViewModel = appViewModel + self.walletViewModel = walletViewModel + self.isNfcReadingAvailable = isNfcReadingAvailable + } + + @MainActor + func shouldShow() async -> Bool { + !appViewModel.hasSeenNfcIntro && walletViewModel.walletExists == true && isNfcReadingAvailable() + } + + func onShown() { + Logger.debug("NFC intro sheet shown") + } + + func onDismissed() { + Logger.debug("NFC intro sheet dismissed") + } +} diff --git a/Bitkit/Managers/TimedSheets/TimedSheetManager.swift b/Bitkit/Managers/TimedSheets/TimedSheetManager.swift index de31396124..9975ce7751 100644 --- a/Bitkit/Managers/TimedSheets/TimedSheetManager.swift +++ b/Bitkit/Managers/TimedSheets/TimedSheetManager.swift @@ -78,6 +78,8 @@ class TimedSheetManager: ObservableObject { registerSheet(UsdtIntroTimedSheet(wallet: walletViewModel, settings: settingsViewModel)) registerSheet(MoveToSparkTimedSheet(app: appViewModel, wallet: walletViewModel)) + registerSheet(NfcIntroTimedSheet(appViewModel: appViewModel, walletViewModel: walletViewModel)) + let quickpaySheet = QuickpayTimedSheet(appViewModel: appViewModel, walletViewModel: walletViewModel) registerSheet(quickpaySheet) diff --git a/Bitkit/Models/SettingsBackupConfig.swift b/Bitkit/Models/SettingsBackupConfig.swift index b494f9e6e6..24940799b2 100644 --- a/Bitkit/Models/SettingsBackupConfig.swift +++ b/Bitkit/Models/SettingsBackupConfig.swift @@ -46,6 +46,7 @@ enum SettingsBackupConfig { "selectedAddressType": .string(optional: true), "addressTypesToMonitor": .string(optional: true), "enableQuickpay": .bool, + "enableNearbyPayments": .bool, "showWidgets": .bool, "swipeBalanceToHide": .bool, "hideBalance": .bool, @@ -68,6 +69,7 @@ enum SettingsBackupConfig { "warnWhenSendingOver100": "enableSendAmountWarning", "bitcoinDisplayUnit": "displayUnit", "enableQuickpay": "isQuickPayEnabled", + "enableNearbyPayments": "isNearbyPaymentsEnabled", "quickpayAmount": "quickPayAmount", "quickpayDailyLimitMultiplier": "quickPayDailyLimitMultiplier", "enableNotifications": "notificationsGranted", diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 68fb4a1d08..c143dafff0 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -536,6 +536,26 @@ "onboarding__multiple_header" = "تنبيه:\nأجهزة متعددة"; "onboarding__multiple_text" = "لا تقم بتثبيت عبارة استرداد Bitkit على هواتف متعددة في وقت واحد، لأن ذلك قد يفسد بياناتك."; "other__qr_scan" = "مسح رمز QR"; +"other__scan_status_qr" = "مسح QR"; +"other__scan_status_qr_nfc" = "مسح QR و NFC"; +"other__scan_status_qr_bluetooth" = "مسح QR و Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "مسح QR و NFC و Bluetooth"; +"other__scan_to_pay_title" = "امسح\nللدفع"; +"other__scan_to_pay_text" = "اسمح بالوصول إلى الكاميرا و Bluetooth و NFC لمسح فواتير Bitcoin والدفع بشكل أسرع."; +"other__nfc_alert" = "المس جهاز الدفع أو الهاتف"; +"other__nfc_read_button" = "قراءة NFC"; +"other__bluetooth_enable" = "تفعيل البلوتوث"; +"other__nfc_error_header" = "فشلت قراءة NFC"; +"other__nfc_error_text" = "لا تحتوي هذه العلامة على طلب دفع يمكن لـ Bitkit قراءته."; +"other__nfc_error_multiple" = "تحتوي هذه العلامة على أكثر من طلب دفع واحد."; +"other__nfc_error_unavailable" = "لا يمكن لهذا الجهاز قراءة علامات NFC."; +"other__nfc_error_read_failed" = "تعذّر على Bitkit قراءة هذه العلامة. ثبّت هاتفك وحاول مرة أخرى."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "ادفع\nبلمسة واحدة"; +"other__nfc_intro__description" = "يدعم Bitkit الآن مدفوعات NFC. قرّب هاتفك من جهاز دفع أو هاتف متوافق للدفع فورًا."; +"other__nfc_intro__quickpay_toggle" = "استخدام QuickPay للمدفوعات الصغيرة"; +"other__nfc_intro__settings" = "الإعدادات"; +"other__nfc_intro__continue" = "رائع!"; "other__qr_error_header" = "تعذر قراءة رمز QR"; "other__qr_error_text" = "لا يستطيع Bitkit قراءة رمز QR هذا."; "other__qr_error_detection_description" = "فشل معالجة الصورة للبحث عن رموز QR."; @@ -860,6 +880,8 @@ "settings__security__swipe_balance_to_hide" = "اسحب الرصيد للإخفاء"; "settings__security__hide_balance_on_open" = "إخفاء الرصيد عند الفتح"; "settings__security__clipboard" = "قراءة الحافظة لسهولة الاستخدام"; +"settings__security__nearby_payments" = "المدفوعات القريبة"; +"settings__security__nearby_payments_text" = "عرض طلب الاستلام عبر Bluetooth"; "settings__security__warn_100" = "تحذير عند الإرسال فوق 100 دولار"; "settings__security__pin" = "رمز PIN"; "settings__security__section_backup" = "النسخ الاحتياطي أو إعادة التعيين"; @@ -911,6 +933,7 @@ "wallet__receive_bitcoin_invoice" = "فاتورة Bitcoin"; "wallet__receive_lightning_invoice" = "فاتورة Lightning"; "wallet__receive_note_placeholder" = "ملاحظة اختيارية للدافع"; +"wallet__receive_scan_or_tap" = "امسح أو المس للدفع"; "wallet__receive_show_qr" = "عرض رمز QR"; "settings__backup__category_contacts" = "جهات الاتصال"; "settings__support__title" = "الدعم"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 6da270c99c..79ae92f566 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -585,6 +585,26 @@ "onboarding__multiple_header" = "Precaució:\nmúltiples dispositius"; "onboarding__multiple_text" = "No instal·leu la vostra frase de recuperació de Bitkit en múltiples telèfons simultàniament, ja que això pot corrompre les vostres dades."; "other__qr_scan" = "Escaneja el codi QR"; +"other__scan_status_qr" = "Escanejant QR"; +"other__scan_status_qr_nfc" = "Escanejant QR i NFC"; +"other__scan_status_qr_bluetooth" = "Escanejant QR i Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Escanejant QR, NFC i Bluetooth"; +"other__scan_to_pay_title" = "Escaneja\nper pagar"; +"other__scan_to_pay_text" = "Permet l'accés a la càmera, al Bluetooth i a l'NFC per escanejar factures de bitcoin i pagar més ràpidament."; +"other__nfc_alert" = "Toca el terminal de pagament o el telèfon"; +"other__nfc_read_button" = "Llegir NFC"; +"other__bluetooth_enable" = "Habilitar Bluetooth"; +"other__nfc_error_header" = "Error de lectura NFC"; +"other__nfc_error_text" = "Aquesta etiqueta no conté cap sol·licitud de pagament que Bitkit pugui llegir."; +"other__nfc_error_multiple" = "Aquesta etiqueta conté més d'una sol·licitud de pagament."; +"other__nfc_error_unavailable" = "Aquest dispositiu no pot llegir etiquetes NFC."; +"other__nfc_error_read_failed" = "Bitkit no ha pogut llegir aquesta etiqueta. Mantén el telèfon quiet i torna-ho a provar."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Paga amb\nun sol toc"; +"other__nfc_intro__description" = "Ara Bitkit admet pagaments NFC. Apropa el telèfon a un terminal de pagament o a un telèfon compatible per pagar a l'instant."; +"other__nfc_intro__quickpay_toggle" = "Utilitza QuickPay per a pagaments petits"; +"other__nfc_intro__settings" = "Configuració"; +"other__nfc_intro__continue" = "Genial!"; "other__qr_error_header" = "No es pot llegir el codi QR"; "other__qr_error_text" = "Bitkit no pot llegir aquest codi QR."; "other__qr_error_detection_description" = "No s\'ha pogut processar la imatge per als codis QR."; @@ -950,6 +970,8 @@ "settings__security__swipe_balance_to_hide" = "Llisca el saldo per amagar"; "settings__security__hide_balance_on_open" = "Amaga el saldo en obrir"; "settings__security__clipboard" = "Llegeix el porta-retalls per facilitar l\'ús"; +"settings__security__nearby_payments" = "Pagaments propers"; +"settings__security__nearby_payments_text" = "Ofereix la recepció per Bluetooth"; "settings__security__warn_100" = "Avisa quan s\'enviïn més de 100 $"; "settings__security__pin" = "Codi PIN"; "settings__security__pin_change" = "Canvia el codi PIN"; @@ -1438,6 +1460,7 @@ "wallet__receive_bitcoin_invoice" = "Factura de Bitcoin"; "wallet__receive_lightning_invoice" = "Factura Lightning"; "wallet__receive_note_placeholder" = "Nota opcional per al pagador"; +"wallet__receive_scan_or_tap" = "Escaneja o toca per pagar"; "wallet__receive_show_qr" = "Mostra el codi QR"; "wallet__receive_cjit_error" = "Transacció fallida"; "wallet__minimum" = "MÍNIM"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 3646859eb9..84a8b90832 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -611,6 +611,26 @@ "onboarding__multiple_header" = "Upozornění:\nvíce zařízení"; "onboarding__multiple_text" = "Neinstalujte frázi pro obnovení Bitkit do více telefonů současně, protože by to mohlo poškodit vaše data."; "other__qr_scan" = "Naskenujte QR kód"; +"other__scan_status_qr" = "Skenování QR"; +"other__scan_status_qr_nfc" = "Skenování QR a NFC"; +"other__scan_status_qr_bluetooth" = "Skenování QR a Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Skenování QR, NFC a Bluetooth"; +"other__scan_to_pay_title" = "Naskenujte\na zaplaťte"; +"other__scan_to_pay_text" = "Povolte přístup k fotoaparátu, Bluetooth a NFC, abyste mohli skenovat bitcoinové faktury a platit rychleji."; +"other__nfc_alert" = "Přiložte telefon k platebnímu terminálu nebo telefonu"; +"other__nfc_read_button" = "Číst NFC"; +"other__bluetooth_enable" = "Povolit Bluetooth"; +"other__nfc_error_header" = "Čtení NFC selhalo"; +"other__nfc_error_text" = "Tento štítek neobsahuje platební požadavek, který Bitkit dokáže přečíst."; +"other__nfc_error_multiple" = "Tento štítek obsahuje více než jeden platební požadavek."; +"other__nfc_error_unavailable" = "Toto zařízení neumí číst NFC štítky."; +"other__nfc_error_read_failed" = "Bitkit nemohl tento štítek přečíst. Držte telefon v klidu a zkuste to znovu."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Plaťte\njedním dotykem"; +"other__nfc_intro__description" = "Bitkit nyní podporuje platby přes NFC. Přiložte telefon ke kompatibilnímu platebnímu terminálu nebo telefonu a zaplaťte okamžitě."; +"other__nfc_intro__quickpay_toggle" = "Používat QuickPay pro malé platby"; +"other__nfc_intro__settings" = "Nastavení"; +"other__nfc_intro__continue" = "Skvělé!"; "other__qr_error_header" = "Nelze přečíst QR"; "other__qr_error_text" = "Bitkit není schopen tento QR kód přečíst."; "other__qr_error_detection_description" = "Zpracování obrázku pro QR kódy selhalo."; @@ -1009,6 +1029,8 @@ "settings__security__swipe_balance_to_hide" = "Skrýt zůstatek přejetím"; "settings__security__hide_balance_on_open" = "Skrýt zůstatek při otevření"; "settings__security__clipboard" = "Číst schránku pro snadné použití"; +"settings__security__nearby_payments" = "Platby v okolí"; +"settings__security__nearby_payments_text" = "Nabízet příjem přes Bluetooth"; "settings__security__warn_100" = "Upozornit při odesílání více než $100"; "settings__security__pin" = "PIN kód"; "settings__security__pin_change" = "Změna PIN kódu"; @@ -1550,6 +1572,7 @@ "wallet__receive_bitcoin_invoice" = "bitcoinová faktura"; "wallet__receive_lightning_invoice" = "Lightningová faktura"; "wallet__receive_note_placeholder" = "Nepovinná poznámka pro plátce"; +"wallet__receive_scan_or_tap" = "Naskenujte nebo přiložte k platbě"; "wallet__receive_show_qr" = "Zobrazit QR kód"; "wallet__receive_text_lnfunds" = "Chcete obdržet prostředky lightning?"; "wallet__receive_cjit_error" = "Transakce selhala"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index e89f74affd..09a4925f93 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -609,6 +609,26 @@ "onboarding__multiple_header" = "Achtung:\nMehrere Geräte"; "onboarding__multiple_text" = "Füge deine Wiederherstellungsphrase nicht mehreren Geräten gleichzeitig hinzu, da es zu unwiderruflichen Schäden deiner Daten kommen kann."; "other__qr_scan" = "QR-Code scannen"; +"other__scan_status_qr" = "QR wird gescannt"; +"other__scan_status_qr_nfc" = "QR & NFC werden gescannt"; +"other__scan_status_qr_bluetooth" = "QR & Bluetooth werden gescannt"; +"other__scan_status_qr_nfc_bluetooth" = "QR, NFC & Bluetooth werden gescannt"; +"other__scan_to_pay_title" = "Scannen\nund zahlen"; +"other__scan_to_pay_text" = "Erlaube den Zugriff auf Kamera, Bluetooth und NFC, um Bitcoin-Rechnungen zu scannen und schneller zu bezahlen."; +"other__nfc_alert" = "Halte dein Telefon an das Zahlungsterminal oder Telefon"; +"other__nfc_read_button" = "NFC lesen"; +"other__bluetooth_enable" = "Bluetooth aktivieren"; +"other__nfc_error_header" = "NFC-Lesen fehlgeschlagen"; +"other__nfc_error_text" = "Dieser Tag enthält keine Zahlungsanforderung, die Bitkit lesen kann."; +"other__nfc_error_multiple" = "Dieser Tag enthält mehr als eine Zahlungsanforderung."; +"other__nfc_error_unavailable" = "Dieses Gerät kann keine NFC-Tags lesen."; +"other__nfc_error_read_failed" = "Bitkit konnte diesen Tag nicht lesen. Halte dein Telefon ruhig und versuche es erneut."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Bezahlen mit\neinem Tippen"; +"other__nfc_intro__description" = "Bitkit unterstützt jetzt NFC-Zahlungen. Halte dein Telefon an ein kompatibles Zahlungsterminal oder Telefon, um sofort zu bezahlen."; +"other__nfc_intro__quickpay_toggle" = "QuickPay für kleine Zahlungen nutzen"; +"other__nfc_intro__settings" = "Einstellungen"; +"other__nfc_intro__continue" = "Super!"; "other__qr_error_header" = "QR-Code kann nicht gelesen werden"; "other__qr_error_text" = "Bitkit kann diesen QR-Code nicht lesen."; "other__qr_error_detection_description" = "Bild konnte nicht für QR-Codes verarbeitet werden."; @@ -1007,6 +1027,8 @@ "settings__security__swipe_balance_to_hide" = "Wischen um Kontostand zu verbergen"; "settings__security__hide_balance_on_open" = "Kontostand beim Start verbergen"; "settings__security__clipboard" = "Lesen der Zwischenablage erlauben"; +"settings__security__nearby_payments" = "Zahlungen in der Nähe"; +"settings__security__nearby_payments_text" = "Empfangen über Bluetooth anbieten"; "settings__security__warn_100" = "Warnen beim Senden von über $100"; "settings__security__pin" = "PIN Code"; "settings__security__pin_change" = "PIN Code ändern"; @@ -1548,6 +1570,7 @@ "wallet__receive_bitcoin_invoice" = "Bitcoin-Rechnung"; "wallet__receive_lightning_invoice" = "Lightning-Rechnung"; "wallet__receive_note_placeholder" = "Optionale Notiz an den Zahler"; +"wallet__receive_scan_or_tap" = "Scannen oder tippen zum Bezahlen"; "wallet__receive_show_qr" = "QR-Code anzeigen"; "wallet__receive_text_lnfunds" = "Möchtest du Lightning-Gelder empfangen?"; "wallet__receive_cjit_error" = "Transaktion fehlgeschlagen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 646e51a91c..00a0f9b92f 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -562,6 +562,26 @@ "onboarding__multiple_header" = "Προσοχή:\nπολλαπλές συσκευές"; "onboarding__multiple_text" = "Μην εγκαταστήσετε τη φράση ανάκτησης του Bitkit σας σε πολλά τηλέφωνα ταυτόχρονα, καθώς αυτό μπορεί να καταστρέψει τα δεδομένα σας."; "other__qr_scan" = "Σάρωση Κωδικού QR"; +"other__scan_status_qr" = "Σάρωση QR"; +"other__scan_status_qr_nfc" = "Σάρωση QR & NFC"; +"other__scan_status_qr_bluetooth" = "Σάρωση QR & Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Σάρωση QR, NFC & Bluetooth"; +"other__scan_to_pay_title" = "Σάρωση\nγια πληρωμή"; +"other__scan_to_pay_text" = "Επιτρέψτε την πρόσβαση στην κάμερα, στο Bluetooth και στο NFC για να σαρώνετε τιμολόγια bitcoin και να πληρώνετε πιο γρήγορα."; +"other__nfc_alert" = "Ακουμπήστε το τερματικό πληρωμής ή το τηλέφωνο"; +"other__nfc_read_button" = "Ανάγνωση NFC"; +"other__bluetooth_enable" = "Ενεργοποίηση Bluetooth"; +"other__nfc_error_header" = "Η ανάγνωση NFC απέτυχε"; +"other__nfc_error_text" = "Αυτή η ετικέτα δεν περιέχει αίτημα πληρωμής που μπορεί να διαβάσει το Bitkit."; +"other__nfc_error_multiple" = "Αυτή η ετικέτα περιέχει περισσότερα από ένα αιτήματα πληρωμής."; +"other__nfc_error_unavailable" = "Αυτή η συσκευή δεν μπορεί να διαβάσει ετικέτες NFC."; +"other__nfc_error_read_failed" = "Το Bitkit δεν μπόρεσε να διαβάσει αυτή την ετικέτα. Κρατήστε το τηλέφωνο σταθερό και δοκιμάστε ξανά."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Πληρώστε με\nένα άγγιγμα"; +"other__nfc_intro__description" = "Το Bitkit υποστηρίζει πλέον πληρωμές NFC. Φέρτε το τηλέφωνό σας κοντά σε ένα συμβατό τερματικό πληρωμής ή τηλέφωνο για να πληρώσετε αμέσως."; +"other__nfc_intro__quickpay_toggle" = "Χρήση QuickPay για μικρές πληρωμές"; +"other__nfc_intro__settings" = "Ρυθμίσεις"; +"other__nfc_intro__continue" = "Τέλεια!"; "other__qr_error_header" = "Αδυναμία Ανάγνωσης QR"; "other__qr_error_text" = "Το Bitkit δεν μπορεί να διαβάσει αυτόν τον κωδικό QR."; "other__qr_error_detection_description" = "Αποτυχία επεξεργασίας της εικόνας για κωδικούς QR."; @@ -897,6 +917,8 @@ "settings__security__swipe_balance_to_hide" = "Σύρετε υπόλοιπο για απόκρυψη"; "settings__security__hide_balance_on_open" = "Απόκρυψη υπολοίπου στο άνοιγμα"; "settings__security__clipboard" = "Ανάγνωση πρόχειρου για ευκολία χρήσης"; +"settings__security__nearby_payments" = "Πληρωμές κοντά σας"; +"settings__security__nearby_payments_text" = "Προσφορά λήψης μέσω Bluetooth"; "settings__security__warn_100" = "Προειδοποίηση όταν στέλνετε πάνω από $100"; "settings__security__pin" = "Κωδικός PIN"; "settings__security__pin_change" = "Αλλαγή Κωδικού PIN"; @@ -1317,6 +1339,7 @@ "wallet__receive_bitcoin_invoice" = "Τιμολόγιο Bitcoin"; "wallet__receive_lightning_invoice" = "Τιμολόγιο Lightning"; "wallet__receive_note_placeholder" = "Προαιρετική σημείωση στον πληρωτή"; +"wallet__receive_scan_or_tap" = "Σαρώστε ή ακουμπήστε για πληρωμή"; "wallet__receive_show_qr" = "Εμφάνιση Κωδικού QR"; "wallet__receive_cjit_error" = "Η Συναλλαγή Απέτυχε"; "wallet__activity" = "Δραστηριότητα"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 913c795320..3b452d7ca1 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -602,6 +602,26 @@ "onboarding__multiple_header" = "Caution:\nmultiple devices"; "onboarding__multiple_text" = "Don\'t install your Bitkit recovery phrase into multiple phones simultaneously, as this can corrupt your data."; "other__qr_scan" = "Scan QR Code"; +"other__scan_status_qr" = "Scanning QR"; +"other__scan_status_qr_nfc" = "Scanning QR & NFC"; +"other__scan_status_qr_bluetooth" = "Scanning QR & Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Scanning QR, NFC & Bluetooth"; +"other__scan_to_pay_title" = "Scan\nto pay"; +"other__scan_to_pay_text" = "Allow Camera, Bluetooth, and NFC access to scan bitcoin invoices and pay more quickly."; +"other__nfc_alert" = "Tap payment terminal or phone"; +"other__nfc_read_button" = "Read NFC"; +"other__bluetooth_enable" = "Enable Bluetooth"; +"other__nfc_error_header" = "NFC Read Failed"; +"other__nfc_error_text" = "This tag does not contain a payment request Bitkit can read."; +"other__nfc_error_multiple" = "This tag contains more than one payment request."; +"other__nfc_error_unavailable" = "This device cannot read NFC tags."; +"other__nfc_error_read_failed" = "Bitkit could not read this tag. Hold your phone still and try again."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Pay with\njust one tap"; +"other__nfc_intro__description" = "Bitkit now supports NFC payments. Hold your phone near a compatible payment terminal or phone to pay instantly."; +"other__nfc_intro__quickpay_toggle" = "Use QuickPay for small payments"; +"other__nfc_intro__settings" = "Settings"; +"other__nfc_intro__continue" = "Awesome!"; "other__qr_error_header" = "Unable To Read QR"; "other__qr_error_text" = "Bitkit is not able to read this QR code."; "other__qr_error_detection_description" = "Failed to process the image for QR codes."; @@ -992,6 +1012,8 @@ "settings__security__swipe_balance_to_hide" = "Swipe balance to hide"; "settings__security__hide_balance_on_open" = "Hide balance on open"; "settings__security__clipboard" = "Read clipboard for ease of use"; +"settings__security__nearby_payments" = "Nearby payments"; +"settings__security__nearby_payments_text" = "Offer Receive over Bluetooth"; "settings__security__warn_100" = "Warn when sending over $100"; "settings__security__pin" = "PIN Code"; "settings__security__pin_change" = "Change PIN Code"; @@ -1563,6 +1585,7 @@ "wallet__receive_bitcoin_invoice" = "Bitcoin invoice"; "wallet__receive_lightning_invoice" = "Lightning invoice"; "wallet__receive_note_placeholder" = "Optional note to payer"; +"wallet__receive_scan_or_tap" = "Scan or tap to pay"; "wallet__receive_show_qr" = "QR Code"; "wallet__receive_text_lnfunds" = "Want to receive Lightning funds?"; "wallet__receive_cjit_error" = "Transaction Failed"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 12d4713fd3..ab59037ffd 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -612,6 +612,26 @@ "onboarding__multiple_header" = "Precaución:\nmúltiples dispositivos"; "onboarding__multiple_text" = "No instale su frase de recuperación Bitkit en varios teléfonos simultáneamente, ya que podría corromper sus datos."; "other__qr_scan" = "Escanear código QR"; +"other__scan_status_qr" = "Escaneando QR"; +"other__scan_status_qr_nfc" = "Escaneando QR y NFC"; +"other__scan_status_qr_bluetooth" = "Escaneando QR y Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Escaneando QR, NFC y Bluetooth"; +"other__scan_to_pay_title" = "Escanear\npara pagar"; +"other__scan_to_pay_text" = "Permita el acceso a la cámara, Bluetooth y NFC para escanear facturas de bitcoin y pagar más rápido."; +"other__nfc_alert" = "Acerque la terminal de pago o el teléfono"; +"other__nfc_read_button" = "Leer NFC"; +"other__bluetooth_enable" = "Habilitar Bluetooth"; +"other__nfc_error_header" = "Error de lectura NFC"; +"other__nfc_error_text" = "Esta etiqueta no contiene una solicitud de pago que Bitkit pueda leer."; +"other__nfc_error_multiple" = "Esta etiqueta contiene más de una solicitud de pago."; +"other__nfc_error_unavailable" = "Este dispositivo no puede leer etiquetas NFC."; +"other__nfc_error_read_failed" = "Bitkit no pudo leer esta etiqueta. Mantenga el teléfono quieto e intente de nuevo."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Pague con\nun solo toque"; +"other__nfc_intro__description" = "Bitkit ahora admite pagos NFC. Acerque su teléfono a una terminal de pago o teléfono compatible para pagar al instante."; +"other__nfc_intro__quickpay_toggle" = "Usar QuickPay para pagos pequeños"; +"other__nfc_intro__settings" = "Ajustes"; +"other__nfc_intro__continue" = "¡Genial!"; "other__qr_error_header" = "No se puede leer el QR"; "other__qr_error_text" = "Bitkit no es capaz de leer este código QR."; "other__qr_error_detection_description" = "Error al procesar la imagen para códigos QR."; @@ -1010,6 +1030,8 @@ "settings__security__swipe_balance_to_hide" = "Deslizar la balanza para ocultar"; "settings__security__hide_balance_on_open" = "Ocultar saldo al abrir"; "settings__security__clipboard" = "Lea el portapapeles para facilitar su uso"; +"settings__security__nearby_payments" = "Pagos cercanos"; +"settings__security__nearby_payments_text" = "Ofrecer recepción por Bluetooth"; "settings__security__warn_100" = "Advertir al enviar más de $100 usd"; "settings__security__pin" = "Código PIN"; "settings__security__pin_change" = "Cambiar código PIN"; @@ -1553,6 +1575,7 @@ "wallet__receive_bitcoin_invoice" = "Factura Bitcoin"; "wallet__receive_lightning_invoice" = "Factura Lightning"; "wallet__receive_note_placeholder" = "Nota opcional para el pagador"; +"wallet__receive_scan_or_tap" = "Escanee o acerque para pagar"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_text_lnfunds" = "Quiero recibir"; "wallet__receive_cjit_error" = "Transacción fallida"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 9ce51626a7..8744148577 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -586,6 +586,26 @@ "onboarding__multiple_header" = "Precaución:\nmúltiples dispositivos"; "onboarding__multiple_text" = "No instale su frase de recuperación de Bitkit en múltiples teléfonos simultáneamente, ya que esto puede corromper sus datos."; "other__qr_scan" = "Escanear código QR"; +"other__scan_status_qr" = "Escaneando QR"; +"other__scan_status_qr_nfc" = "Escaneando QR y NFC"; +"other__scan_status_qr_bluetooth" = "Escaneando QR y Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Escaneando QR, NFC y Bluetooth"; +"other__scan_to_pay_title" = "Escanear\npara pagar"; +"other__scan_to_pay_text" = "Permita el acceso a la cámara, Bluetooth y NFC para escanear facturas de bitcoin y pagar más rápido."; +"other__nfc_alert" = "Acerque el terminal de pago o el teléfono"; +"other__nfc_read_button" = "Leer NFC"; +"other__bluetooth_enable" = "Activar Bluetooth"; +"other__nfc_error_header" = "Error de lectura NFC"; +"other__nfc_error_text" = "Esta etiqueta no contiene una solicitud de pago que Bitkit pueda leer."; +"other__nfc_error_multiple" = "Esta etiqueta contiene más de una solicitud de pago."; +"other__nfc_error_unavailable" = "Este dispositivo no puede leer etiquetas NFC."; +"other__nfc_error_read_failed" = "Bitkit no ha podido leer esta etiqueta. Mantenga el teléfono quieto e inténtelo de nuevo."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Pague con\nun solo toque"; +"other__nfc_intro__description" = "Bitkit ahora admite pagos NFC. Acerque su teléfono a un terminal de pago o teléfono compatible para pagar al instante."; +"other__nfc_intro__quickpay_toggle" = "Usar QuickPay para pagos pequeños"; +"other__nfc_intro__settings" = "Ajustes"; +"other__nfc_intro__continue" = "¡Genial!"; "other__qr_error_header" = "Incapaz De Leer QR"; "other__qr_error_text" = "Bitkit no es capaz de leer este código QR."; "other__qr_error_detection_description" = "Error al procesar la imagen para códigos QR."; @@ -958,6 +978,8 @@ "settings__security__swipe_balance_to_hide" = "Desliza el saldo para ocultar"; "settings__security__hide_balance_on_open" = "Ocultar saldo al abrir"; "settings__security__clipboard" = "Leer portapapeles para facilitar uso"; +"settings__security__nearby_payments" = "Pagos cercanos"; +"settings__security__nearby_payments_text" = "Ofrecer recepción por Bluetooth"; "settings__security__warn_100" = "Advertir al enviar más de $100"; "settings__security__pin" = "Código PIN"; "settings__security__pin_change" = "Cambiar código PIN"; @@ -1453,6 +1475,7 @@ "wallet__receive_bitcoin_invoice" = "Factura bitcoin"; "wallet__receive_lightning_invoice" = "Factura Lightning"; "wallet__receive_note_placeholder" = "Nota opcional para el pagador"; +"wallet__receive_scan_or_tap" = "Escanee o acerque para pagar"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_cjit_error" = "Transacción ha fallado"; "wallet__receive_cjit_error_msg" = "Fallo al enviar fondos a la cuenta de gastos."; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index f224453103..d2057783e5 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -612,6 +612,26 @@ "onboarding__multiple_header" = "Attention :\nplusieurs appareils"; "onboarding__multiple_text" = "N\'installez pas votre phrase de récupération Bitkit sur plusieurs téléphones simultanément, car cela pourrait corrompre vos données."; "other__qr_scan" = "Scannez le QR code "; +"other__scan_status_qr" = "Scan QR"; +"other__scan_status_qr_nfc" = "Scan QR et NFC"; +"other__scan_status_qr_bluetooth" = "Scan QR et Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Scan QR, NFC et Bluetooth"; +"other__scan_to_pay_title" = "Scannez\npour payer"; +"other__scan_to_pay_text" = "Autorisez l'accès à l'appareil photo, au Bluetooth et au NFC pour scanner des factures bitcoin et payer plus rapidement."; +"other__nfc_alert" = "Approchez le terminal de paiement ou le téléphone"; +"other__nfc_read_button" = "Lire NFC"; +"other__bluetooth_enable" = "Activer le Bluetooth"; +"other__nfc_error_header" = "Échec de la lecture NFC"; +"other__nfc_error_text" = "Ce tag ne contient pas de demande de paiement lisible par Bitkit."; +"other__nfc_error_multiple" = "Ce tag contient plusieurs demandes de paiement."; +"other__nfc_error_unavailable" = "Cet appareil ne peut pas lire les tags NFC."; +"other__nfc_error_read_failed" = "Bitkit n'a pas pu lire ce tag. Gardez votre téléphone immobile et réessayez."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Payez\nd'un simple geste"; +"other__nfc_intro__description" = "Bitkit prend désormais en charge les paiements NFC. Approchez votre téléphone d'un terminal de paiement ou d'un téléphone compatible pour payer instantanément."; +"other__nfc_intro__quickpay_toggle" = "Utiliser QuickPay pour les petits paiements"; +"other__nfc_intro__settings" = "Paramètres"; +"other__nfc_intro__continue" = "Génial !"; "other__qr_error_header" = "Impossible de lire les QR codes"; "other__qr_error_text" = "Bitkit n\'est pas en mesure de lire ce QR code."; "other__qr_error_detection_description" = "Échec du traitement de l\'image pour les codes QR."; @@ -1010,6 +1030,8 @@ "settings__security__swipe_balance_to_hide" = "Balayer pour masquer la balance"; "settings__security__hide_balance_on_open" = "Masquer le solde à l\'ouverture"; "settings__security__clipboard" = "Lire le presse-papiers pour faciliter l\'utilisation"; +"settings__security__nearby_payments" = "Paiements à proximité"; +"settings__security__nearby_payments_text" = "Proposer la réception par Bluetooth"; "settings__security__warn_100" = "Avertir en cas d\'envoi de plus de 100$"; "settings__security__pin" = "Code PIN"; "settings__security__pin_change" = "Modifier le code PIN"; @@ -1561,6 +1583,7 @@ "wallet__receive_bitcoin_invoice" = "Facture bitcoin"; "wallet__receive_lightning_invoice" = "Facture Lightning"; "wallet__receive_note_placeholder" = "Note facultative à destination du payeur"; +"wallet__receive_scan_or_tap" = "Scannez ou approchez pour payer"; "wallet__receive_show_qr" = "Afficher le QR code"; "wallet__receive_text_lnfunds" = "Vous souhaitez recevoir des fonds Lightning?"; "wallet__receive_cjit_error" = "Échec de la transaction"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index b2f83dae26..e8d67b3f94 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -606,6 +606,26 @@ "onboarding__multiple_header" = "Attenzione:\ndispositivi multipli"; "onboarding__multiple_text" = "Non installare la frase di recupero Bitkit su più telefoni contemporaneamente, per non danneggiare i dati."; "other__qr_scan" = "Scansiona il Codice QR"; +"other__scan_status_qr" = "Scansione QR"; +"other__scan_status_qr_nfc" = "Scansione QR e NFC"; +"other__scan_status_qr_bluetooth" = "Scansione QR e Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Scansione QR, NFC e Bluetooth"; +"other__scan_to_pay_title" = "Scansiona\nper pagare"; +"other__scan_to_pay_text" = "Consenti l'accesso a fotocamera, Bluetooth e NFC per scansionare le fatture bitcoin e pagare più velocemente."; +"other__nfc_alert" = "Avvicina il terminale di pagamento o il telefono"; +"other__nfc_read_button" = "Leggi NFC"; +"other__bluetooth_enable" = "Abilita Bluetooth"; +"other__nfc_error_header" = "Lettura NFC non riuscita"; +"other__nfc_error_text" = "Questo tag non contiene una richiesta di pagamento leggibile da Bitkit."; +"other__nfc_error_multiple" = "Questo tag contiene più di una richiesta di pagamento."; +"other__nfc_error_unavailable" = "Questo dispositivo non può leggere i tag NFC."; +"other__nfc_error_read_failed" = "Bitkit non è riuscito a leggere questo tag. Tieni fermo il telefono e riprova."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Paga con\nun solo tocco"; +"other__nfc_intro__description" = "Bitkit ora supporta i pagamenti NFC. Avvicina il telefono a un terminale di pagamento o a un telefono compatibile per pagare all'istante."; +"other__nfc_intro__quickpay_toggle" = "Usa QuickPay per i piccoli pagamenti"; +"other__nfc_intro__settings" = "Impostazioni"; +"other__nfc_intro__continue" = "Fantastico!"; "other__qr_error_header" = "Impossibile leggere il QR"; "other__qr_error_text" = "Bitkit non è in grado di leggere questo codice QR."; "other__qr_error_detection_description" = "Elaborazione dell'immagine per i codici QR non riuscita."; @@ -991,6 +1011,8 @@ "settings__security__swipe_balance_to_hide" = "Scorri per nascondere il saldo"; "settings__security__hide_balance_on_open" = "Nascondi il saldo all'apertura"; "settings__security__clipboard" = "Leggi gli appunti per facilitare l'uso"; +"settings__security__nearby_payments" = "Pagamenti nelle vicinanze"; +"settings__security__nearby_payments_text" = "Offri la ricezione via Bluetooth"; "settings__security__warn_100" = "Avvisa quando invii più di $100"; "settings__security__pin" = "Codice PIN"; "settings__security__pin_change" = "Cambia codice PIN"; @@ -1526,6 +1548,7 @@ "wallet__receive_bitcoin_invoice" = "Bitcoin invoice"; "wallet__receive_lightning_invoice" = "Lightning invoice"; "wallet__receive_note_placeholder" = "Nota opzionale per chi paga"; +"wallet__receive_scan_or_tap" = "Scansiona o avvicina per pagare"; "wallet__receive_show_qr" = "Visualizza QR Code"; "wallet__receive_text_lnfunds" = "Vuoi ricevere fondi Lightning?"; "wallet__receive_cjit_error" = "Transazione Fallita"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 6bf689654a..9fe026b331 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -609,6 +609,26 @@ "onboarding__multiple_header" = "Let op:\nmeerdere apparaten"; "onboarding__multiple_text" = "Installeer Bitkit niet op meerdere telefoons tegelijk met dezelfde herstelwoorden, dit kan data corruptie veroorzaken."; "other__qr_scan" = "QR Code Scannen"; +"other__scan_status_qr" = "QR scannen"; +"other__scan_status_qr_nfc" = "QR & NFC scannen"; +"other__scan_status_qr_bluetooth" = "QR & Bluetooth scannen"; +"other__scan_status_qr_nfc_bluetooth" = "QR, NFC & Bluetooth scannen"; +"other__scan_to_pay_title" = "Scan\nom te betalen"; +"other__scan_to_pay_text" = "Geef toegang tot camera, Bluetooth en NFC om bitcoinfacturen te scannen en sneller te betalen."; +"other__nfc_alert" = "Houd je telefoon bij de betaalterminal of telefoon"; +"other__nfc_read_button" = "NFC lezen"; +"other__bluetooth_enable" = "Bluetooth inschakelen"; +"other__nfc_error_header" = "NFC lezen mislukt"; +"other__nfc_error_text" = "Deze tag bevat geen betaalverzoek dat Bitkit kan lezen."; +"other__nfc_error_multiple" = "Deze tag bevat meer dan één betaalverzoek."; +"other__nfc_error_unavailable" = "Dit apparaat kan geen NFC-tags lezen."; +"other__nfc_error_read_failed" = "Bitkit kon deze tag niet lezen. Houd je telefoon stil en probeer het opnieuw."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Betaal met\néén tik"; +"other__nfc_intro__description" = "Bitkit ondersteunt nu NFC-betalingen. Houd je telefoon bij een compatibele betaalterminal of telefoon om direct te betalen."; +"other__nfc_intro__quickpay_toggle" = "QuickPay gebruiken voor kleine betalingen"; +"other__nfc_intro__settings" = "Instellingen"; +"other__nfc_intro__continue" = "Top!"; "other__qr_error_header" = "Kan QR Niet Lezen"; "other__qr_error_text" = "Bitkit kan deze QR code niet lezen."; "other__qr_error_detection_description" = "Kon de afbeelding niet verwerken voor QR codes."; @@ -1007,6 +1027,8 @@ "settings__security__swipe_balance_to_hide" = "Veeg de balans om te verbergen"; "settings__security__hide_balance_on_open" = "Saldo verbergen bij open"; "settings__security__clipboard" = "Klembord lezen voor gemak in gebruik"; +"settings__security__nearby_payments" = "Betalingen in de buurt"; +"settings__security__nearby_payments_text" = "Ontvangen aanbieden via Bluetooth"; "settings__security__warn_100" = "Waarschuw mij met betalingen over $100"; "settings__security__pin" = "Pincode"; "settings__security__pin_change" = "Pincode veranderen"; @@ -1556,6 +1578,7 @@ "wallet__receive_bitcoin_invoice" = "Bitcoin factuur"; "wallet__receive_lightning_invoice" = "Lightning factuur"; "wallet__receive_note_placeholder" = "Desgewenst bericht aan de betaler"; +"wallet__receive_scan_or_tap" = "Scan of tik om te betalen"; "wallet__receive_show_qr" = "Toon QR Code"; "wallet__receive_text_lnfunds" = "Wilt u Lightning ₿ ontvangen?"; "wallet__receive_cjit_error" = "Transactie Mislukt"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index b857f4a1d2..a71bf8375e 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -611,6 +611,26 @@ "onboarding__multiple_header" = "Uwaga:\nwiele urządzeń"; "onboarding__multiple_text" = "Nie instaluj swojej frazy odzyskiwania Bitkit na kilku telefonach jednocześnie, ponieważ może to uszkodzić Twoje dane."; "other__qr_scan" = "Skanuj kod QR"; +"other__scan_status_qr" = "Skanowanie QR"; +"other__scan_status_qr_nfc" = "Skanowanie QR i NFC"; +"other__scan_status_qr_bluetooth" = "Skanowanie QR i Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Skanowanie QR, NFC i Bluetooth"; +"other__scan_to_pay_title" = "Skanuj\ni płać"; +"other__scan_to_pay_text" = "Zezwól na dostęp do aparatu, Bluetooth i NFC, aby skanować faktury bitcoin i płacić szybciej."; +"other__nfc_alert" = "Zbliż telefon do terminala płatniczego lub telefonu"; +"other__nfc_read_button" = "Odczytaj NFC"; +"other__bluetooth_enable" = "Włącz Bluetooth"; +"other__nfc_error_header" = "Odczyt NFC nie powiódł się"; +"other__nfc_error_text" = "Ten tag nie zawiera żądania płatności, które Bitkit może odczytać."; +"other__nfc_error_multiple" = "Ten tag zawiera więcej niż jedno żądanie płatności."; +"other__nfc_error_unavailable" = "To urządzenie nie obsługuje odczytu tagów NFC."; +"other__nfc_error_read_failed" = "Bitkit nie mógł odczytać tego tagu. Przytrzymaj telefon nieruchomo i spróbuj ponownie."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Płać\njednym dotknięciem"; +"other__nfc_intro__description" = "Bitkit obsługuje teraz płatności NFC. Zbliż telefon do zgodnego terminala płatniczego lub telefonu, aby zapłacić od razu."; +"other__nfc_intro__quickpay_toggle" = "Używaj QuickPay do małych płatności"; +"other__nfc_intro__settings" = "Ustawienia"; +"other__nfc_intro__continue" = "Super!"; "other__qr_error_header" = "Nie można odczytać kodu QR"; "other__qr_error_text" = "Bitkit nie jest w stanie odczytać tego kodu QR."; "other__qr_error_detection_description" = "Nie udało się przetworzyć obrazu w celu wykrycia kodów QR."; @@ -1009,6 +1029,8 @@ "settings__security__swipe_balance_to_hide" = "Przesuń saldo, aby ukryć"; "settings__security__hide_balance_on_open" = "Ukryj saldo po otwarciu"; "settings__security__clipboard" = "Odczytaj schowek dla wygody użytkowania"; +"settings__security__nearby_payments" = "Płatności w pobliżu"; +"settings__security__nearby_payments_text" = "Udostępniaj odbiór przez Bluetooth"; "settings__security__warn_100" = "Ostrzegaj przy transakcji powyżej 100 USD"; "settings__security__pin" = "Kod PIN"; "settings__security__pin_change" = "Zmień kod PIN"; @@ -1560,6 +1582,7 @@ "wallet__receive_bitcoin_invoice" = "Faktura bitcoinowa"; "wallet__receive_lightning_invoice" = "Faktura Lightning"; "wallet__receive_note_placeholder" = "Opcjonalna notatka dla płatnika"; +"wallet__receive_scan_or_tap" = "Zeskanuj lub zbliż, aby zapłacić"; "wallet__receive_show_qr" = "Skanuj kod QR"; "wallet__receive_text_lnfunds" = "Chcesz otrzymać fundusze Lightning?"; "wallet__receive_cjit_error" = "Transakcja nie powiodła się"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index ced10084b3..22634f786b 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -611,6 +611,26 @@ "onboarding__multiple_header" = "Cuidado:\nvários dispositivos"; "onboarding__multiple_text" = "Não instale sua frase de recuperação do Bitkit em vários telefones simultaneamente, isso pode corromper seus dados."; "other__qr_scan" = "Escanear o Código QR"; +"other__scan_status_qr" = "Escaneando QR"; +"other__scan_status_qr_nfc" = "Escaneando QR e NFC"; +"other__scan_status_qr_bluetooth" = "Escaneando QR e Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Escaneando QR, NFC e Bluetooth"; +"other__scan_to_pay_title" = "Escanear\npara pagar"; +"other__scan_to_pay_text" = "Permita o acesso à câmera, ao Bluetooth e ao NFC para escanear faturas de bitcoin e pagar mais rápido."; +"other__nfc_alert" = "Aproxime da maquininha ou do celular"; +"other__nfc_read_button" = "Ler NFC"; +"other__bluetooth_enable" = "Ativar Bluetooth"; +"other__nfc_error_header" = "Falha na leitura NFC"; +"other__nfc_error_text" = "Esta etiqueta não contém uma solicitação de pagamento que a Bitkit consiga ler."; +"other__nfc_error_multiple" = "Esta etiqueta contém mais de uma solicitação de pagamento."; +"other__nfc_error_unavailable" = "Este dispositivo não consegue ler etiquetas NFC."; +"other__nfc_error_read_failed" = "A Bitkit não conseguiu ler esta etiqueta. Mantenha o celular parado e tente novamente."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Pague com\num só toque"; +"other__nfc_intro__description" = "A Bitkit agora aceita pagamentos por NFC. Aproxime seu celular de uma maquininha ou celular compatível para pagar na hora."; +"other__nfc_intro__quickpay_toggle" = "Usar QuickPay para pagamentos pequenos"; +"other__nfc_intro__settings" = "Ajustes"; +"other__nfc_intro__continue" = "Demais!"; "other__qr_error_header" = "Incapaz de Ler o QR"; "other__qr_error_text" = "A Bitkit não consegue ler este código QR."; "other__qr_error_detection_description" = "Falha ao processar a imagem para códigos QR."; @@ -1009,6 +1029,8 @@ "settings__security__swipe_balance_to_hide" = "Arraste o saldo para ocultar"; "settings__security__hide_balance_on_open" = "Ocultar saldo ao abrir o app"; "settings__security__clipboard" = "Ler área de transferência"; +"settings__security__nearby_payments" = "Pagamentos por proximidade"; +"settings__security__nearby_payments_text" = "Oferecer o recebimento via Bluetooth"; "settings__security__warn_100" = "Avisar ao enviar mais de US$ 100"; "settings__security__pin" = "Código PIN"; "settings__security__pin_change" = "Alterar o código PIN"; @@ -1561,6 +1583,7 @@ "wallet__receive_bitcoin_invoice" = "Invoice Bitcoin"; "wallet__receive_lightning_invoice" = "Invoice Lightning"; "wallet__receive_note_placeholder" = "Comentário opcional para o pagador"; +"wallet__receive_scan_or_tap" = "Escaneie ou aproxime para pagar"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_text_lnfunds" = "Deseja receber via Lightning?"; "wallet__receive_cjit_error" = "Falha na Transação"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 674c417ff4..86a70e88d4 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -588,6 +588,26 @@ "onboarding__multiple_header" = "Cuidado:\nvários dispositivos"; "onboarding__multiple_text" = "Não instale sua frase de recuperação do Bitkit em vários telefones simultaneamente, isso pode corromper seus dados."; "other__qr_scan" = "Escanear o Código QR"; +"other__scan_status_qr" = "A ler QR"; +"other__scan_status_qr_nfc" = "A ler QR e NFC"; +"other__scan_status_qr_bluetooth" = "A ler QR e Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "A ler QR, NFC e Bluetooth"; +"other__scan_to_pay_title" = "Ler\npara pagar"; +"other__scan_to_pay_text" = "Permita o acesso à câmera, ao Bluetooth e ao NFC para ler invoices de bitcoin e pagar mais rapidamente."; +"other__nfc_alert" = "Aproxime o terminal de pagamento ou o telefone"; +"other__nfc_read_button" = "Ler NFC"; +"other__bluetooth_enable" = "Ativar Bluetooth"; +"other__nfc_error_header" = "Falha na leitura NFC"; +"other__nfc_error_text" = "Esta etiqueta não contém um pedido de pagamento que a Bitkit consiga ler."; +"other__nfc_error_multiple" = "Esta etiqueta contém mais do que um pedido de pagamento."; +"other__nfc_error_unavailable" = "Este dispositivo não consegue ler etiquetas NFC."; +"other__nfc_error_read_failed" = "A Bitkit não conseguiu ler esta etiqueta. Mantenha o telefone imóvel e tente novamente."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Pague com\num só toque"; +"other__nfc_intro__description" = "A Bitkit agora suporta pagamentos NFC. Aproxime o telefone de um terminal de pagamento ou telefone compatível para pagar de imediato."; +"other__nfc_intro__quickpay_toggle" = "Usar QuickPay para pagamentos pequenos"; +"other__nfc_intro__settings" = "Ajustes"; +"other__nfc_intro__continue" = "Excelente!"; "other__qr_error_header" = "Incapaz de Ler o QR"; "other__qr_error_text" = "A Bitkit não consegue ler este código QR."; "other__qr_error_detection_description" = "Falha ao processar a imagem para detetar códigos QR."; @@ -908,6 +928,8 @@ "settings__security__swipe_balance_to_hide" = "Arraste o saldo para ocultar"; "settings__security__hide_balance_on_open" = "Ocultar saldo ao abrir o app"; "settings__security__clipboard" = "Ler área de transferência"; +"settings__security__nearby_payments" = "Pagamentos próximos"; +"settings__security__nearby_payments_text" = "Oferecer a receção por Bluetooth"; "settings__security__warn_100" = "Avisar ao enviar mais de US$ 100"; "settings__security__pin" = "Código PIN"; "settings__security__section_backup" = "Cópia de segurança ou repor"; @@ -1280,6 +1302,7 @@ "wallet__receive_bitcoin_invoice" = "Invoice Bitcoin"; "wallet__receive_lightning_invoice" = "Invoice Lightning"; "wallet__receive_note_placeholder" = "Comentário opcional para o pagador"; +"wallet__receive_scan_or_tap" = "Leia ou aproxime para pagar"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__activity" = "Atividade"; "wallet__activity_no" = "Nenhuma atividade ainda"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index 938e498e0a..818adbf08b 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -607,6 +607,26 @@ "onboarding__multiple_header" = "Предупреждение:\nНесколько Устройств"; "onboarding__multiple_text" = "Не устанавливайте вашу фразу восстановления Bitkit на нескольких телефонах одновременно, так как это может привести к повреждению данных."; "other__qr_scan" = "Сканировать QR-код"; +"other__scan_status_qr" = "Сканирование QR"; +"other__scan_status_qr_nfc" = "Сканирование QR и NFC"; +"other__scan_status_qr_bluetooth" = "Сканирование QR и Bluetooth"; +"other__scan_status_qr_nfc_bluetooth" = "Сканирование QR, NFC и Bluetooth"; +"other__scan_to_pay_title" = "Сканируйте\nи платите"; +"other__scan_to_pay_text" = "Разрешите доступ к камере, Bluetooth и NFC, чтобы сканировать счета bitcoin и платить быстрее."; +"other__nfc_alert" = "Поднесите к платёжному терминалу или телефону"; +"other__nfc_read_button" = "Считать NFC"; +"other__bluetooth_enable" = "Включить Bluetooth"; +"other__nfc_error_header" = "Ошибка чтения NFC"; +"other__nfc_error_text" = "Эта метка не содержит запроса на оплату, который может прочитать Bitkit."; +"other__nfc_error_multiple" = "Эта метка содержит более одного запроса на оплату."; +"other__nfc_error_unavailable" = "Это устройство не может читать NFC-метки."; +"other__nfc_error_read_failed" = "Bitkit не удалось прочитать эту метку. Держите телефон неподвижно и попробуйте снова."; +"other__nfc_intro__nav_title" = "TapPay (NFC)"; +"other__nfc_intro__title" = "Платите\nодним касанием"; +"other__nfc_intro__description" = "Bitkit теперь поддерживает NFC-платежи. Поднесите телефон к совместимому платёжному терминалу или телефону, чтобы оплатить мгновенно."; +"other__nfc_intro__quickpay_toggle" = "Использовать QuickPay для небольших платежей"; +"other__nfc_intro__settings" = "Настройки"; +"other__nfc_intro__continue" = "Отлично!"; "other__qr_error_header" = "Не удалось прочитать QR-код"; "other__qr_error_text" = "Bitkit не может прочитать этот QR-код."; "other__qr_error_detection_description" = "Не удалось обработать изображение для поиска QR-кодов."; @@ -1005,6 +1025,8 @@ "settings__security__swipe_balance_to_hide" = "Смахнуть Баланс, чтобы Скрыть"; "settings__security__hide_balance_on_open" = "Скрывать Баланс при Открытии"; "settings__security__clipboard" = "Читать Буфер Обмена для Удобства Использования"; +"settings__security__nearby_payments" = "Платежи поблизости"; +"settings__security__nearby_payments_text" = "Предлагать получение через Bluetooth"; "settings__security__warn_100" = "Предупреждать при Отправке более $100"; "settings__security__pin" = "PIN-код"; "settings__security__pin_change" = "Сменить PIN-код"; @@ -1545,6 +1567,7 @@ "wallet__receive_bitcoin_invoice" = "Биткоин инвойс"; "wallet__receive_lightning_invoice" = "Лайтнинг инвойс"; "wallet__receive_note_placeholder" = "Опциональная заметка для плательщика"; +"wallet__receive_scan_or_tap" = "Отсканируйте или поднесите для оплаты"; "wallet__receive_show_qr" = "Показать QR-код"; "wallet__receive_text_lnfunds" = "Хотите получить Лайтнинг средства?"; "wallet__receive_cjit_error" = "Транзакция не удалась"; diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index bced21a4cf..432faf9c74 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -59,6 +59,9 @@ enum ChannelFreeRailFees { /// The rail runs here but isn't connected, so its payments are unknown rather than none. struct ChannelFreeRailUnavailable: Error {} +/// A caller's `beforeSubmission` check stopped a send before it was submitted, so nothing left the wallet. +struct SendStoppedBeforeSubmission: Error {} + struct ChannelFreeRailSendRefused: LocalizedError { let reason: String var underlying: Error? diff --git a/Bitkit/Services/NearbyPaymentAdvertiser.swift b/Bitkit/Services/NearbyPaymentAdvertiser.swift new file mode 100644 index 0000000000..3ef133ff26 --- /dev/null +++ b/Bitkit/Services/NearbyPaymentAdvertiser.swift @@ -0,0 +1,173 @@ +import CoreBluetooth +import Foundation + +/// Serves the Receive screen's payment request to nearby phones as a Bluetooth LE GATT server. +/// +/// Advertises only the service UUID (no device name) while `start` is in effect. The owner calls `stop` +/// when the Receive screen leaves the foreground or the nearby setting is off. It never asks for Bluetooth +/// permission: it runs only once the user allowed Bluetooth (from a payment scanner's Bluetooth button). +@MainActor +@Observable +final class NearbyPaymentAdvertiser: NSObject { + private(set) var isAdvertising = false + + @ObservationIgnored private var manager: CBPeripheralManager? + @ObservationIgnored private var request: Data? + @ObservationIgnored private var isServiceAdded = false + @ObservationIgnored private var isAddingService = false + /// The request each central started reading, so a request change mid-read cannot mix chunks. + @ObservationIgnored private var requestsByCentral: [UUID: Data] = [:] + @ObservationIgnored private let authorization: () -> CBManagerAuthorization + + init(authorization: @escaping () -> CBManagerAuthorization = { CBManager.authorization }) { + self.authorization = authorization + } + + /// Whether advertising may start without showing the Bluetooth permission prompt. + var canAdvertise: Bool { + authorization() == .allowedAlways + } + + /// Starts serving `request` (a payment URI), or updates the served request while running. + func start(request uri: String) { + guard canAdvertise else { + stop() + return + } + guard let encoded = NearbyProtocol.encodeRequest(uri) else { + Logger.warn("Nearby request is empty or too large to serve", context: "NearbyPaymentAdvertiser") + stop() + return + } + request = encoded + if let manager { + publishIfReady(manager) + } else { + manager = CBPeripheralManager( + delegate: self, + queue: nil, + options: [CBPeripheralManagerOptionShowPowerAlertKey: false] + ) + } + } + + func stop() { + request = nil + requestsByCentral = [:] + if let manager { + manager.stopAdvertising() + manager.removeAllServices() + manager.delegate = nil + } + manager = nil + isServiceAdded = false + isAddingService = false + isAdvertising = false + } + + private func publishIfReady(_ manager: CBPeripheralManager) { + guard manager.state == .poweredOn, request != nil else { + isAdvertising = false + return + } + guard isServiceAdded else { + guard !isAddingService else { return } + isAddingService = true + manager.add(Self.makeService()) + return + } + if !manager.isAdvertising { + manager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [NearbyProtocol.serviceUUID]]) + } + } + + private static func makeService() -> CBMutableService { + let service = CBMutableService(type: NearbyProtocol.serviceUUID, primary: true) + service.characteristics = ([NearbyProtocol.metaUUID] + NearbyProtocol.dataUUIDs).map { + CBMutableCharacteristic(type: $0, properties: [.read], value: nil, permissions: [.readable]) + } + return service + } + + private func handleStateUpdate(_ manager: CBPeripheralManager) { + guard manager === self.manager else { return } + if manager.state == .poweredOn { + publishIfReady(manager) + } else { + isServiceAdded = false + isAddingService = false + isAdvertising = false + } + } + + private func handleServiceAdded(_ manager: CBPeripheralManager, error: Error?) { + guard manager === self.manager else { return } + isAddingService = false + if let error { + Logger.error(error, context: "Nearby GATT service") + return + } + isServiceAdded = true + publishIfReady(manager) + } + + private func handleAdvertisingStarted(_ manager: CBPeripheralManager, error: Error?) { + guard manager === self.manager else { return } + if let error { + Logger.error(error, context: "Nearby advertising") + isAdvertising = false + return + } + isAdvertising = request != nil + } + + /// Test seam: sets the served request without Bluetooth. + func setServedRequestForTesting(_ uri: String) { + request = NearbyProtocol.encodeRequest(uri) + } + + /// The request a central reads. It is snapshotted when the central reads meta, so its chunks always match the + /// length it was told, even if Receive changes the request mid-read. + func servedRequest(for central: UUID, characteristic: CBUUID) -> Data? { + if characteristic == NearbyProtocol.metaUUID, let request { + requestsByCentral[central] = request + return request + } + return requestsByCentral[central] ?? request + } + + private func handleRead(_ manager: CBPeripheralManager, request read: CBATTRequest) { + let uuid = read.characteristic.uuid + guard let request = servedRequest(for: read.central.identifier, characteristic: uuid), + let value = NearbyProtocol.value(for: uuid, request: request) + else { + manager.respond(to: read, withResult: .attributeNotFound) + return + } + guard let served = NearbyProtocol.read(value, at: read.offset) else { + manager.respond(to: read, withResult: .invalidOffset) + return + } + read.value = served + manager.respond(to: read, withResult: .success) + } +} + +/// The manager delivers callbacks on the main queue (queue: nil), so they run on the main actor. +extension NearbyPaymentAdvertiser: CBPeripheralManagerDelegate { + nonisolated func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { + MainActor.assumeIsolated { handleStateUpdate(peripheral) } + } + + nonisolated func peripheralManager(_ peripheral: CBPeripheralManager, didAdd _: CBService, error: Error?) { + MainActor.assumeIsolated { handleServiceAdded(peripheral, error: error) } + } + + nonisolated func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { + MainActor.assumeIsolated { handleAdvertisingStarted(peripheral, error: error) } + } + + nonisolated func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { + MainActor.assumeIsolated { handleRead(peripheral, request: request) } + } +} diff --git a/Bitkit/Services/NearbyPaymentScanner.swift b/Bitkit/Services/NearbyPaymentScanner.swift new file mode 100644 index 0000000000..42215fb205 --- /dev/null +++ b/Bitkit/Services/NearbyPaymentScanner.swift @@ -0,0 +1,322 @@ +import CoreBluetooth +import Foundation +import UIKit + +/// Reads a payment request from the closest Bitkit phone showing its Receive screen over Bluetooth LE. +/// +/// Scans for the nearby service while a payment scanner is open, connects to the strongest advertiser at +/// or above `NearbyProtocol.minRssi`, reads meta and the needed chunks, disconnects and delivers the request. +/// A peripheral is not retried for `retryInterval` after an attempt. Scanning pauses while a request is handled, +/// resumes when the handler did not take it, and otherwise waits for the next `start`. +@MainActor +@Observable +final class NearbyPaymentScanner: NSObject { + private(set) var authorization: CBManagerAuthorization = CBManager.authorization + private(set) var isScanning = false + + nonisolated static let retryInterval: TimeInterval = 10 + private static let selectionWindow: TimeInterval = 0.3 + private static let connectTimeout: TimeInterval = 8 + + @ObservationIgnored private var central: CBCentralManager? + @ObservationIgnored private var onRequest: ((String, @escaping () -> Bool) async -> Bool)? + @ObservationIgnored private var candidates: [UUID: (peripheral: CBPeripheral, rssi: Int)] = [:] + @ObservationIgnored private var lastAttempts: [UUID: Date] = [:] + @ObservationIgnored private var selectionTask: Task? + @ObservationIgnored private var timeoutTask: Task? + @ObservationIgnored private var connected: CBPeripheral? + @ObservationIgnored private var expectedLength: Int? + @ObservationIgnored private var chunks: [Data] = [] + /// The delivery in progress. `stop` clears it, so a request handed over before then can no longer act. + @ObservationIgnored private var deliveryID: UUID? + + var isAuthorized: Bool { + authorization == .allowedAlways + } + + /// Starts scanning when Bluetooth is already authorized. It never prompts; see `requestAuthorization`. + /// `onRequest` gets the request and a check that turns false once the scanner stops (for example when the app + /// goes inactive), and returns whether the request was taken; scanning resumes when it was not. + func start(onRequest: @escaping (String, @escaping () -> Bool) async -> Bool) { + self.onRequest = onRequest + authorization = CBManager.authorization + guard isAuthorized else { return } + startCentral() + } + + func stop() { + onRequest = nil + deliveryID = nil + selectionTask?.cancel() + selectionTask = nil + disconnect() + if let central { + if central.state == .poweredOn { + central.stopScan() + } + central.delegate = nil + } + central = nil + candidates = [:] + isScanning = false + } + + /// Asks for Bluetooth permission, or opens Settings when it was denied before. + func requestAuthorization() { + authorization = CBManager.authorization + switch authorization { + case .notDetermined: + // Creating the manager shows the system prompt; scanning starts once it is allowed. + startCentral() + case .denied, .restricted: + if let url = URL(string: UIApplication.openSettingsURLString) { + UIApplication.shared.open(url) + } + default: + startCentral() + } + } + + private func startCentral() { + if let central { + scanIfReady(central) + } else { + central = CBCentralManager( + delegate: self, + queue: nil, + options: [CBCentralManagerOptionShowPowerAlertKey: false] + ) + } + } + + private func scanIfReady(_ central: CBCentralManager) { + guard central.state == .poweredOn, onRequest != nil, connected == nil, deliveryID == nil else { + isScanning = false + return + } + central.scanForPeripherals( + withServices: [NearbyProtocol.serviceUUID], + options: [CBCentralManagerScanOptionAllowDuplicatesKey: true] + ) + isScanning = true + } + + private func handleStateUpdate(_ central: CBCentralManager) { + guard central === self.central else { return } + authorization = CBManager.authorization + if central.state == .poweredOn { + scanIfReady(central) + } else { + isScanning = false + } + } + + private func handleDiscovery(_ peripheral: CBPeripheral, rssi: Int) { + guard connected == nil, Self.isEligible(rssi: rssi), + !Self.isDebounced(lastAttempts[peripheral.identifier], now: Date()) + else { return } + if let existing = candidates[peripheral.identifier], existing.rssi >= rssi { + return + } + candidates[peripheral.identifier] = (peripheral, rssi) + guard selectionTask == nil else { return } + selectionTask = Task { [weak self] in + try? await Task.sleep(nanoseconds: UInt64(Self.selectionWindow * 1_000_000_000)) + guard !Task.isCancelled else { return } + self?.connectToStrongest() + } + } + + nonisolated static func isEligible(rssi: Int) -> Bool { + // CoreBluetooth reports 127 when the RSSI is unavailable. + rssi >= NearbyProtocol.minRssi && rssi < 127 + } + + nonisolated static func isDebounced(_ lastAttempt: Date?, now: Date) -> Bool { + guard let lastAttempt else { return false } + return now.timeIntervalSince(lastAttempt) < retryInterval + } + + private func connectToStrongest() { + selectionTask = nil + guard let central, connected == nil, + let best = candidates.values.max(by: { $0.rssi < $1.rssi }) + else { return } + candidates = [:] + let peripheral = best.peripheral + lastAttempts[peripheral.identifier] = Date() + connected = peripheral + expectedLength = nil + chunks = [] + central.stopScan() + isScanning = false + peripheral.delegate = self + central.connect(peripheral) + timeoutTask = Task { [weak self] in + try? await Task.sleep(nanoseconds: UInt64(Self.connectTimeout * 1_000_000_000)) + guard !Task.isCancelled else { return } + self?.fail("timed out") + } + } + + private func fail(_ reason: String) { + Logger.warn("Nearby read failed: \(reason)", context: "NearbyPaymentScanner") + disconnect() + if let central { + scanIfReady(central) + } + } + + private func disconnect() { + timeoutTask?.cancel() + timeoutTask = nil + if let connected { + connected.delegate = nil + central?.cancelPeripheralConnection(connected) + } + connected = nil + expectedLength = nil + chunks = [] + } + + private func characteristic(_ uuid: CBUUID, of peripheral: CBPeripheral) -> CBCharacteristic? { + peripheral.services? + .first { $0.uuid == NearbyProtocol.serviceUUID }? + .characteristics? + .first { $0.uuid == uuid } + } + + private func readNext(_ peripheral: CBPeripheral) { + guard let length = expectedLength else { + guard let meta = characteristic(NearbyProtocol.metaUUID, of: peripheral) else { + return fail("missing meta characteristic") + } + peripheral.readValue(for: meta) + return + } + if chunks.count < NearbyProtocol.chunks(for: length) { + guard let data = characteristic(NearbyProtocol.dataUUIDs[chunks.count], of: peripheral) else { + return fail("missing data characteristic \(chunks.count)") + } + peripheral.readValue(for: data) + return + } + guard let request = NearbyProtocol.decode(chunks: chunks, length: length) else { + return fail("request does not match its announced length") + } + deliver(request) + } + + private func deliver(_ request: String) { + guard let onRequest else { return } + disconnect() + let id = UUID() + deliveryID = id + isScanning = false + Task { [weak self] in + // The scanner may have stopped before this task ran; the request then reaches no handler. + guard self?.deliveryID == id else { return } + let wasTaken = await onRequest(request) { [weak self] in self?.deliveryID == id } + guard let self, deliveryID == id else { return } + deliveryID = nil + if wasTaken { + // Wait for the scanner to be shown again (`start`) before reading another phone. + self.onRequest = nil + } else if let central { + scanIfReady(central) + } + } + } + + /// Test seam: hands `request` to the handler as a completed read would. + func deliverForTesting(_ request: String) { + deliver(request) + } + + private func handleValue(_ peripheral: CBPeripheral, characteristic: CBCharacteristic, error: Error?) { + guard peripheral === connected else { return } + if let error { + return fail(error.localizedDescription) + } + let value = characteristic.value ?? Data() + if characteristic.uuid == NearbyProtocol.metaUUID { + guard let length = NearbyProtocol.requestLength(meta: value) else { + return fail("unsupported meta") + } + expectedLength = length + } else { + chunks.append(value) + } + readNext(peripheral) + } +} + +/// The manager delivers callbacks on the main queue (queue: nil), so they run on the main actor. +extension NearbyPaymentScanner: CBCentralManagerDelegate { + nonisolated func centralManagerDidUpdateState(_ central: CBCentralManager) { + MainActor.assumeIsolated { handleStateUpdate(central) } + } + + nonisolated func centralManager( + _: CBCentralManager, + didDiscover peripheral: CBPeripheral, + advertisementData _: [String: Any], + rssi RSSI: NSNumber + ) { + let rssi = RSSI.intValue + MainActor.assumeIsolated { handleDiscovery(peripheral, rssi: rssi) } + } + + nonisolated func centralManager(_: CBCentralManager, didConnect peripheral: CBPeripheral) { + MainActor.assumeIsolated { + guard peripheral === connected else { return } + peripheral.discoverServices([NearbyProtocol.serviceUUID]) + } + } + + nonisolated func centralManager(_: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { + let reason = error?.localizedDescription ?? "connection failed" + MainActor.assumeIsolated { + guard peripheral === connected else { return } + fail(reason) + } + } + + nonisolated func centralManager(_: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error _: Error?) { + MainActor.assumeIsolated { + guard peripheral === connected else { return } + fail("disconnected before the request was read") + } + } +} + +extension NearbyPaymentScanner: CBPeripheralDelegate { + nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + let reason = error?.localizedDescription + MainActor.assumeIsolated { + guard peripheral === connected else { return } + if let reason { + return fail(reason) + } + guard let service = peripheral.services?.first(where: { $0.uuid == NearbyProtocol.serviceUUID }) else { + return fail("service not found") + } + peripheral.discoverCharacteristics([NearbyProtocol.metaUUID] + NearbyProtocol.dataUUIDs, for: service) + } + } + + nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor _: CBService, error: Error?) { + let reason = error?.localizedDescription + MainActor.assumeIsolated { + guard peripheral === connected else { return } + if let reason { + return fail(reason) + } + readNext(peripheral) + } + } + + nonisolated func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { + MainActor.assumeIsolated { handleValue(peripheral, characteristic: characteristic, error: error) } + } +} diff --git a/Bitkit/Services/NfcReader.swift b/Bitkit/Services/NfcReader.swift new file mode 100644 index 0000000000..3056b25666 --- /dev/null +++ b/Bitkit/Services/NfcReader.swift @@ -0,0 +1,122 @@ +import CoreNFC +import Foundation + +enum NfcReadError: Error, Equatable { + case unavailable + case busy + case cancelled + case timedOut + case noPaymentRequest + case multiplePaymentRequests + case failed(String) + + /// Cancelling or letting the system sheet time out is a user choice, not an error worth a toast. + var isSilent: Bool { + self == .cancelled || self == .timedOut + } + + /// Message for the app toast and the system NFC sheet. + var message: String { + switch self { + case .unavailable: t("other__nfc_error_unavailable") + case .multiplePaymentRequests: t("other__nfc_error_multiple") + case .noPaymentRequest: t("other__nfc_error_text") + case .busy, .cancelled, .timedOut, .failed: t("other__nfc_error_read_failed") + } + } +} + +@MainActor +protocol NfcPaymentReading: AnyObject { + var isAvailable: Bool { get } + func readPaymentRequest(alertMessage: String) async throws -> String +} + +/// Reads one payment request from an NFC tag, or from an Android phone emulating one, through the +/// system NFC sheet. iOS cannot detect tags in the background for custom schemes, so a read always +/// starts from a user action. +@MainActor +final class NfcReader: NSObject, NfcPaymentReading { + static let shared = NfcReader() + + private var session: NFCNDEFReaderSession? + private var continuation: CheckedContinuation? + + var isAvailable: Bool { + NFCNDEFReaderSession.readingAvailable + } + + func readPaymentRequest(alertMessage: String) async throws -> String { + guard isAvailable else { throw NfcReadError.unavailable } + guard continuation == nil else { throw NfcReadError.busy } + + return try await withCheckedThrowingContinuation { continuation in + self.continuation = continuation + // Kept open after a read so a tag without a payment request can be refused on the system sheet. + let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false) + session.alertMessage = alertMessage + self.session = session + session.begin() + } + } + + private func finish(_ result: Result) { + guard let continuation else { return } + self.continuation = nil + session = nil + continuation.resume(with: result.mapError { $0 as Error }) + } + + private func complete(_ session: NFCNDEFReaderSession, with result: Result) { + guard session === self.session else { return } + switch result { + case .success: + session.invalidate() + case let .failure(error): + session.invalidate(errorMessage: error.message) + } + finish(result) + } + + nonisolated static func readError(for error: Error) -> NfcReadError? { + guard let readerError = error as? NFCReaderError else { + return .failed(error.localizedDescription) + } + switch readerError.code { + case .readerSessionInvalidationErrorFirstNDEFTagRead: + // Expected after a successful read; the result is delivered by didDetectNDEFs. + return nil + case .readerSessionInvalidationErrorUserCanceled: + return .cancelled + case .readerSessionInvalidationErrorSessionTimeout: + return .timedOut + default: + return .failed(readerError.localizedDescription) + } + } +} + +extension NfcReader: NFCNDEFReaderSessionDelegate { + nonisolated func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) { + let records = messages.flatMap(\.records).map { + NdefRecord(typeNameFormat: $0.typeNameFormat.rawValue, type: $0.type, payload: $0.payload) + } + let result = NdefPayloadParser.paymentRequest(from: records).mapError { error -> NfcReadError in + switch error { + case .empty: .noPaymentRequest + case .multiplePayloads: .multiplePaymentRequests + } + } + Task { @MainActor in + self.complete(session, with: result) + } + } + + nonisolated func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) { + guard let readError = Self.readError(for: error) else { return } + Task { @MainActor in + guard session === self.session else { return } + self.finish(.failure(readError)) + } + } +} diff --git a/Bitkit/Utilities/NdefPayloadParser.swift b/Bitkit/Utilities/NdefPayloadParser.swift new file mode 100644 index 0000000000..cfd76a8c8a --- /dev/null +++ b/Bitkit/Utilities/NdefPayloadParser.swift @@ -0,0 +1,85 @@ +import Foundation + +/// One NDEF record, decoupled from Core NFC so it can be parsed and tested without a reader session. +struct NdefRecord: Equatable, Sendable { + let typeNameFormat: UInt8 + let type: Data + let payload: Data +} + +enum NdefPayloadError: Error, Equatable, Sendable { + /// The tag held no record carrying text or a URI. + case empty + /// The tag held more than one different payment request, so the intended one is ambiguous. + case multiplePayloads +} + +/// Extracts the payment request (a URI, invoice or address) carried by an NFC tag. +/// +/// Payment terminals and Android wallets that emulate a tag publish one NDEF record: either a well-known +/// URI record (`lightning:lnbc…`, `bitcoin:…?lightning=…`, `lnurlw://…`, `ethereum:…`) or a well-known +/// Text record holding the same string. The result goes to the same handling as a scanned QR code. +enum NdefPayloadParser { + static let tnfWellKnown: UInt8 = 0x01 + static let tnfAbsoluteUri: UInt8 = 0x03 + + private static let uriRecordType = Data([0x55]) // "U" + private static let textRecordType = Data([0x54]) // "T" + + /// URI identifier codes from the NFC Forum URI Record Type Definition, indexed by code. + static let uriPrefixes: [String] = [ + "", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", + "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", "ftp://", + "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", "sips:", "tftp:", + "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", "file://", "urn:epc:id:", + "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:", + ] + + static func paymentRequest(from records: [NdefRecord]) -> Result { + var values: [String] = [] + for record in records { + guard let value = decode(record)?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { + continue + } + if !values.contains(value) { + values.append(value) + } + } + + switch values.count { + case 0: return .failure(.empty) + case 1: return .success(values[0]) + default: return .failure(.multiplePayloads) + } + } + + static func decode(_ record: NdefRecord) -> String? { + switch record.typeNameFormat { + case tnfWellKnown where record.type == uriRecordType: + return decodeUri(record.payload) + case tnfWellKnown where record.type == textRecordType: + return decodeText(record.payload) + case tnfAbsoluteUri: + return String(data: record.type, encoding: .utf8) + default: + return nil + } + } + + static func decodeUri(_ payload: Data) -> String? { + guard let code = payload.first else { return nil } + let prefix = Int(code) < uriPrefixes.count ? uriPrefixes[Int(code)] : "" + guard let body = String(data: payload.dropFirst(), encoding: .utf8) else { return nil } + return prefix + body + } + + static func decodeText(_ payload: Data) -> String? { + guard let status = payload.first else { return nil } + let isUtf16 = status & 0x80 != 0 + let languageLength = Int(status & 0x3F) + let textStart = 1 + languageLength + guard payload.count >= textStart else { return nil } + let text = payload.dropFirst(textStart) + return String(data: Data(text), encoding: isUtf16 ? .utf16 : .utf8) + } +} diff --git a/Bitkit/Utilities/NearbyProtocol.swift b/Bitkit/Utilities/NearbyProtocol.swift new file mode 100644 index 0000000000..1faf759fa9 --- /dev/null +++ b/Bitkit/Utilities/NearbyProtocol.swift @@ -0,0 +1,96 @@ +import CoreBluetooth +import Foundation + +/// Bitkit nearby payments over Bluetooth LE, version 1. See docs/nearby-payments.md. +/// +/// The receiving phone serves its payment request from a GATT service; a paying phone reads the meta +/// characteristic for the length and then as many 512-byte data chunks as it needs. +enum NearbyProtocol { + static let serviceUUID = CBUUID(string: "CB0E128B-1CA5-4959-94DF-A4FE588E3E98") + static let metaUUID = CBUUID(string: "69A713E5-B0A7-42F1-8B7F-FA0BDA119C00") + static let dataUUIDs: [CBUUID] = (1 ... chunkCount).map { + CBUUID(string: String(format: "69A713E5-B0A7-42F1-8B7F-FA0BDA119C%02X", $0)) + } + + static let version: UInt8 = 0x01 + static let chunkSize = 512 + static let chunkCount = 8 + static let maxRequestBytes = chunkSize * chunkCount + static let minRssi = -60 + + /// The request as served, or nil when it is empty or too large to serve. + static func encodeRequest(_ request: String) -> Data? { + let bytes = Data(request.utf8) + guard !bytes.isEmpty, bytes.count <= maxRequestBytes else { return nil } + return bytes + } + + static func meta(for request: Data) -> Data { + Data([version, UInt8((request.count >> 8) & 0xFF), UInt8(request.count & 0xFF)]) + } + + /// Chunk `index` of `request`; empty past the end of the request. + static func chunk(_ request: Data, index: Int) -> Data { + let start = index * chunkSize + guard (0 ..< chunkCount).contains(index), start < request.count else { return Data() } + let end = min(request.count, start + chunkSize) + return request.subdata(in: (request.startIndex + start) ..< (request.startIndex + end)) + } + + /// The request length announced by `meta`, or nil for an unknown version or bad length. + static func requestLength(meta: Data) -> Int? { + let bytes = [UInt8](meta) + guard bytes.count >= 3, bytes[0] == version else { return nil } + let length = (Int(bytes[1]) << 8) | Int(bytes[2]) + return (1 ... maxRequestBytes).contains(length) ? length : nil + } + + static func chunks(for length: Int) -> Int { + (length + chunkSize - 1) / chunkSize + } + + /// Value served for a read at `offset` of a characteristic whose full value is `value`. + static func read(_ value: Data, at offset: Int) -> Data? { + guard (0 ... value.count).contains(offset) else { return nil } + return value.subdata(in: (value.startIndex + offset) ..< value.endIndex) + } + + static func decode(chunks: [Data], length: Int) -> String? { + let bytes = chunks.reduce(Data(), +) + guard bytes.count == length, let text = String(data: bytes, encoding: .utf8) else { return nil } + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + + /// The value served for `uuid`, or nil when it is not one of the protocol's characteristics. + static func value(for uuid: CBUUID, request: Data) -> Data? { + if uuid == metaUUID { + return meta(for: request) + } + guard let index = dataUUIDs.firstIndex(of: uuid) else { return nil } + return chunk(request, index: index) + } +} + +/// Turns a receive request into the URI offered to nearby phones (NFC tag or Bluetooth). +/// +/// Other wallets need a scheme to recognise the request, so a bare BOLT11 invoice, offer or LNURL gets +/// `lightning:` and a bare address gets `bitcoin:`. Requests that already carry a payment scheme are +/// returned unchanged. +enum NearbyPaymentUri { + private static let uriSchemes = ["bitcoin:", "lightning:", "ethereum:", "lnurlp:", "lnurlw:", "lnurlc:"] + private static let lightningPrefixes = ["lnbc", "lntb", "lntbs", "lnbcrt", "lnsb", "lno1", "lnurl"] + + static func from(_ request: String?) -> String? { + let trimmed = request?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !trimmed.isEmpty else { return nil } + let lowercase = trimmed.lowercased() + if uriSchemes.contains(where: { lowercase.hasPrefix($0) }) { + return trimmed + } + if lightningPrefixes.contains(where: { lowercase.hasPrefix($0) }) { + return "lightning:\(trimmed)" + } + return "bitcoin:\(trimmed)" + } +} diff --git a/Bitkit/Utilities/PaymentNavigationHelper.swift b/Bitkit/Utilities/PaymentNavigationHelper.swift index 65c819df8b..850e570b68 100644 --- a/Bitkit/Utilities/PaymentNavigationHelper.swift +++ b/Bitkit/Utilities/PaymentNavigationHelper.swift @@ -17,12 +17,15 @@ struct PaymentNavigationHelper { spendStore: QuickPaySpendStore = .shared, coordinator: QuickPayPaymentCoordinator? = nil ) -> Bool { - guard !app.isRoutingDeepLinkFromLock, let amountSats = QuickPayLimits.paymentAmountSats(app: app), amountSats > 0 else { + guard !app.isRoutingDeepLinkFromLock, !app.isQuickPaySuppressed, let amountSats = QuickPayLimits.paymentAmountSats(app: app), + amountSats > 0 + else { return false } let coordinator = coordinator ?? .shared if let hash = app.scannedLightningInvoice?.paymentHash.hex, coordinator.hasOpen(hash) { + app.noteQuickPayChosen() return true } // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. @@ -30,13 +33,17 @@ struct PaymentNavigationHelper { return false } - return spendStore.canApply( + let canApply = spendStore.canApply( amountSats: amountSats, enabled: settings.enableQuickpay, thresholdUsd: settings.quickpayAmount, multiplier: settings.quickpayDailyLimitMultiplier, rates: .live(currency) ) + if canApply { + app.noteQuickPayChosen() + } + return canApply } /// Centralized method to open the appropriate sheet based on the current state diff --git a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift index 0b410281d5..02a35dae54 100644 --- a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift +++ b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift @@ -22,6 +22,9 @@ final class QuickPayPaymentCoordinator { let invoiceHash: String let bolt11: String var presentation: Presentation? + /// The send state that owns the screen in `presentation`: the run that started the payment, or a rescan that + /// attached to it since. + var ownerSendStateGeneration: UUID? var paymentId: String? var dispatched = false var emitted = false @@ -44,7 +47,8 @@ final class QuickPayPaymentCoordinator { } private let store: QuickPaySpendStore - private let sendBolt11: (String) async throws -> String + /// Submits a BOLT11 payment, running the check it is given right before the payment leaves. + private let submit: (String, @escaping () throws -> Void) async throws -> String private let listRows: () async throws -> [QuickPayReconcileRow]? private let needsUpdateToSend: (UInt64) -> Bool @@ -63,13 +67,24 @@ final class QuickPayPaymentCoordinator { init( store: QuickPaySpendStore = .shared, sendBolt11: ((String) async throws -> String)? = nil, + submit: ((String, @escaping () throws -> Void) async throws -> String)? = nil, listRows: (() async throws -> [QuickPayReconcileRow]?)? = nil, needsUpdateToSend: ((UInt64) -> Bool)? = nil ) { self.store = store self.needsUpdateToSend = needsUpdateToSend ?? { MoveToSparkMath.needsUpdateToSend(amountSats: $0) } - self.sendBolt11 = sendBolt11 ?? { bolt11 in - try await String(LightningService.shared.send(bolt11: bolt11)) + if let submit { + self.submit = submit + } else if let sendBolt11 { + // A test that fakes only the send runs the check right before it. + self.submit = { bolt11, beforeSubmission in + try beforeSubmission() + return try await sendBolt11(bolt11) + } + } else { + self.submit = { bolt11, beforeSubmission in + try await String(LightningService.shared.send(bolt11: bolt11, beforeSubmission: beforeSubmission)) + } } self.listRows = listRows ?? { try await Self.reconcileRows( @@ -79,6 +94,12 @@ final class QuickPayPaymentCoordinator { } } + /// Whether a send stopped at its submission check. The LDK send runs that check on `ServiceQueue`, which wraps + /// what it throws in `AppError`. + nonisolated static func isStoppedBeforeSubmission(_ error: Error) -> Bool { + ((error as? AppError)?.underlyingError ?? error) is SendStoppedBeforeSubmission + } + /// Both rails' payments, nil while the node can't list its own, so reconciling waits rather than reading them as none. static func reconcileRows( railPayments: () async throws -> [ChannelFreeRailPayment], @@ -90,6 +111,11 @@ final class QuickPayPaymentCoordinator { return ldkRows + railRows } + /// Whether `sessionID` is the session whose payment this coordinator already started. + func isAttached(to sessionID: SessionID) -> Bool { + payRequested && self.sessionID == sessionID + } + func hasOpen(_ paymentHash: String) -> Bool { guard !paymentHash.isEmpty else { return false } return operations[paymentHash] != nil || store.record(matching: paymentHash) != nil @@ -113,7 +139,8 @@ final class QuickPayPaymentCoordinator { settings: SettingsViewModel, currency: CurrencyViewModel, presentation: Presentation, - sessionID: SessionID? = nil + sessionID: SessionID? = nil, + recoveryOnly: Bool = false ) { if let sessionID { if self.sessionID == sessionID { @@ -136,7 +163,8 @@ final class QuickPayPaymentCoordinator { app: app, wallet: wallet, settings: settings, - currency: currency + currency: currency, + recoveryOnly: recoveryOnly ) } } @@ -241,7 +269,8 @@ final class QuickPayPaymentCoordinator { app: AppViewModel, wallet: WalletViewModel, settings: SettingsViewModel, - currency: CurrencyViewModel + currency: CurrencyViewModel, + recoveryOnly: Bool ) async { guard generation == self.generation, app.sendStateGeneration == sendStateGeneration else { return } @@ -290,6 +319,7 @@ final class QuickPayPaymentCoordinator { if let existing = operations[invoiceHash] { currentOperation = existing existing.presentation = presentation + existing.ownerSendStateGeneration = sendStateGeneration if existing.emitted { replayPending(existing) } else if !existing.runActive { @@ -308,6 +338,14 @@ final class QuickPayPaymentCoordinator { return } + // Allowed only to replay a payment already tracked: if it is gone by now, the payer reviews it instead. The same + // holds when the app locked while the invoice was prepared (for example an LNURL fetch) after the screen started. + if recoveryOnly || app.didLockSinceQuickPayWasChosen { + app.resetQuickPay() + presentation.replaceQuickPay(PaymentNavigationHelper.confirmRouteAfterQuickPayCap(app: app)) + return + } + guard generation == self.generation else { return } let amountSats = wallet.sendAmountSats ?? 0 @@ -318,6 +356,7 @@ final class QuickPayPaymentCoordinator { return } let op = InFlightOp(invoiceHash: invoiceHash, bolt11: bolt11, presentation: presentation) + op.ownerSendStateGeneration = sendStateGeneration op.runActive = true register(op) defer { op.runActive = false } @@ -352,14 +391,25 @@ final class QuickPayPaymentCoordinator { return } + let beforeSubmission = app.quickPaySubmissionCheck() op.dispatched = true do { - let paymentId = try await sendBolt11(bolt11) + let paymentId = try await submit(bolt11, beforeSubmission) store.markSubmitted(invoicePaymentHash: invoiceHash, paymentId: paymentId) op.paymentId = paymentId if !paymentId.isEmpty, paymentId != invoiceHash { operations[paymentId] = op } + } catch where Self.isStoppedBeforeSubmission(error) { + // The app locked while the payment waited to be submitted. Nothing left, so the payer reviews it on the + // QuickPay screen attached now, and only while the send that attached it still owns the send state. + let attached = op.presentation + store.releaseBound(paymentHash: invoiceHash) + removeOp(op) + guard let attached, app.sendStateGeneration == op.ownerSendStateGeneration else { return } + app.resetQuickPay() + attached.replaceQuickPay(PaymentNavigationHelper.confirmRouteAfterQuickPayCap(app: app)) + return } catch { await handleDispatchError(error, op: op) return diff --git a/Bitkit/Utilities/ScannedPaymentRequest.swift b/Bitkit/Utilities/ScannedPaymentRequest.swift new file mode 100644 index 0000000000..7d81c3c8f8 --- /dev/null +++ b/Bitkit/Utilities/ScannedPaymentRequest.swift @@ -0,0 +1,170 @@ +import Foundation + +/// Prepares a payment request read from an NFC tag or a nearby device for the scanner. +enum ScannedPaymentRequest { + private static let bitcoinWithoutAddress = "bitcoin:?" + private static let lightningParams = ["lightning", "lno"] + private static let requiredParamPrefix = "req-" + /// Keys BIP 321 ("Query Keys") says must not repeat. `pop` with `req-pop` also counts as a repeat, and any + /// `req-` key already keeps the URI. Unknown optional keys may repeat. + private static let singletonParams: Set = ["amount", "label", "message", "pop"] + /// BOLT11 prefixes, longest first so `lnbcrt` is not read as `lnbc` with an amount. + private static let bolt11Prefixes = ["lnbcrt", "lntbs", "lnbc", "lntb", "lnsb"] + private static let bolt11Multipliers: [Character: Decimal] = [ + "m": Decimal(string: "0.001")!, + "u": Decimal(string: "0.000001")!, + "n": Decimal(string: "0.000000001")!, + "p": Decimal(string: "0.000000000001")!, + ] + + /// A BIP 321 URI may leave the address out and carry only a Lightning request + /// (`bitcoin:?lightning=`, used by Numo and planned by Square). The scanner rejects a `bitcoin:` URI + /// without an address, so that form becomes `lightning:`. A URI with a required (`req-`) parameter is + /// kept, since BIP 321 forbids paying it without handling that parameter and the rewrite would drop it. So is a URI + /// that repeats `amount`, `label`, `message` or `pop`, which BIP 321 makes invalid, so the scanner rejects it + /// instead of paying the invoice alone. A repeated `lightning` invoice is valid BIP 321 but not supported here, + /// since the rewrite would have to pick one of them, so that URI is kept too. Offers (`lno`), which the decoder + /// does not read, may repeat and are skipped when an invoice is present. A URI whose `amount` differs from the + /// invoice's, or that sets an amount for an amountless invoice, is kept too: the scanner cannot carry the outer + /// amount, so it rejects the request instead of asking for a different one. + /// Anything else is returned trimmed and unchanged. + static func normalized(_ text: String) -> String { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard hasLiteralPrefix(trimmed.lowercased(), bitcoinWithoutAddress) else { return trimmed } + var params: [String: String] = [:] + var keys: Set = [] + for pair in queryFields(trimmed) { + let parts = pair.unicodeScalars.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) + .map { String(String.UnicodeScalarView($0)) } + let key = parts[0].lowercased() + // Checked before empty pairs are skipped, since BIP 321 allows a required key with an empty or no value. + if hasLiteralPrefix(key, requiredParamPrefix) { + return trimmed + } + guard !key.isEmpty else { continue } + // An `amount` key with no value is a malformed amount, not a missing one. + if key == "amount", parts.count < 2 || parts[1].isEmpty { + return trimmed + } + // BOLT12 offers (`lno`) may repeat beside the invoice; only a second BOLT11 invoice is ambiguous. + guard keys.insert(key).inserted || (!singletonParams.contains(key) && key != "lightning") else { + return trimmed + } + guard parts.count == 2, !parts[1].isEmpty else { continue } + params[key] = parts[1] + } + guard let request = lightningParams.lazy.compactMap({ params[$0] }).first else { return trimmed } + if let amount = params["amount"] { + guard let btc = btcAmount(amount), btc == bolt11Amount(request) else { return trimmed } + } + return "lightning:\(request)" + } + + /// A BIP 321 `amount` in BTC: digits with an optional decimal point. `Decimal(string:)` alone would read the + /// leading number of `0.0000799BTC` or `0.0000799,50`. + private static func btcAmount(_ value: String) -> Decimal? { + let parts = value.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: false) + guard value.contains(where: \.isNumber), + parts.allSatisfy({ $0.allSatisfy { $0.isASCII && $0.isNumber } }) + else { return nil } + return Decimal(string: value) + } + + /// The amount in BTC that a BOLT11 invoice states in its human-readable part, or nil when it states none. + private static func bolt11Amount(_ invoice: String) -> Decimal? { + let lowercase = invoice.lowercased() + guard let separator = lowercase.lastIndex(of: "1") else { return nil } + let hrp = lowercase[.. [String] { + let scalars = uri.unicodeScalars + guard let mark = scalars.firstIndex(of: "?") else { return [] } + return scalars[scalars.index(after: mark)...].split(separator: "&").map { String(String.UnicodeScalarView($0)) } + } + + /// Whether `text` starts with `prefix`, compared by Unicode scalar as bitkit-core compares bytes. + nonisolated static func hasLiteralPrefix(_ text: some StringProtocol, _ prefix: String) -> Bool { + text.unicodeScalars.starts(with: prefix.unicodeScalars) + } + + /// `text` without its first `prefix.unicodeScalars.count` scalars. + nonisolated static func droppingLiteralPrefix(_ text: some StringProtocol, _ prefix: String) -> String { + String(String.UnicodeScalarView(text.unicodeScalars.dropFirst(prefix.unicodeScalars.count))) + } + + /// Whether a `bitcoin:` request carries a required (`req-`) parameter. The app does not support any, and + /// bitkit-core rc15 ignores them on a URI with an address, so a request from a nearby source that has one is + /// refused rather than paid without the parameter. The app and the decoder strip wrappers (`bitkit://` and the + /// Lightning schemes) before decoding, repeatedly in the decoder's case, so every wrapper is removed here and the + /// request is checked as the `bitcoin:` URI the decoder receives. + nonisolated static func hasRequiredParameter(_ uri: String) -> Bool { + // The app and the decoder strip the Lightning wrappers from the front. While the text starts with `bitkit://`, + // the decoder deletes every `bitkit://` in it, which can turn a key into `req-`, and decodes again. Its deletion + // is case-sensitive, so it runs on the text as read. + var text = uri.trimmingCharacters(in: .whitespacesAndNewlines) + while true { + let lowercaseText = text.lowercased() + if let wrapper = decoderWrappers.first(where: { hasLiteralPrefix(lowercaseText, $0) }) { + text = droppingLiteralPrefix(text, wrapper).trimmingCharacters(in: .whitespacesAndNewlines) + } else if text.hasPrefix("bitkit://") { + text = text.replacingOccurrences(of: "bitkit://", with: "").trimmingCharacters(in: .whitespacesAndNewlines) + } else { + break + } + } + let lowercase = text.lowercased() + guard hasLiteralPrefix(lowercase, "bitcoin:") else { return false } + return queryFields(lowercase).contains { hasLiteralPrefix($0, requiredParamPrefix) } + } + + /// Whether `value` is a BOLT11 invoice for a network the decoder reads as one (`lnbc`, `lnbcrt`, `lntb`, + /// `lntbs`): its human-readable part is the network and an optional amount, and its bech32 checksum holds. Checked + /// without the decoder, which would resolve a Lightning address such as `lnbc@example.com` over the network. + nonisolated static func isBolt11Invoice(_ value: some StringProtocol) -> Bool { + let lowercase = value.lowercased() + guard let separator = lowercase.lastIndex(of: "1") else { return false } + let hrp = lowercase[..= 6, data.count == lowercase.distance(from: separator, to: lowercase.endIndex) - 1 else { + return false + } + let hrpBytes = hrp.unicodeScalars.map { UInt32($0.value) } + let values = hrpBytes.map { $0 >> 5 } + [0] + hrpBytes.map { $0 & 31 } + data.map { UInt32($0) } + var checksum: UInt32 = 1 + for value in values { + let top = checksum >> 25 + checksum = (checksum & 0x1FFFFFF) << 5 ^ value + for (bit, generator) in bech32Generator.enumerated() where (top >> bit) & 1 == 1 { + checksum ^= generator + } + } + return checksum == 1 + } +} diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index af77fca76f..6f30010377 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1,6 +1,7 @@ import BitkitCore import Combine import LDKNode +import os import enum Paykit.PaykitError import SwiftUI @@ -211,6 +212,70 @@ class AppViewModel: ObservableObject { lockedDeepLinkRoutesInFlight > 0 } + private var quickPaySuppressions: Set = [] + /// Raised each time the app locks behind the PIN. + private var appLockGeneration = 0 + /// The lock generation when QuickPay was last chosen for a request. + private var quickPayChosenAtLockGeneration: Int? + + /// Counts app locks for checks that run off the main actor, such as the one right before a payment is submitted. + private let appLocks = OSAllocatedUnfairLock(initialState: 0) + + /// True until the app locks behind the PIN after this call, so work that outlasts a lock can drop its result. + func lockCheck() -> () -> Bool { + let lockGeneration = appLockGeneration + return { [weak self] in + self?.appLockGeneration == lockGeneration + } + } + + /// Called when the app locks behind the PIN. + func noteAppLocked() { + appLockGeneration += 1 + appLocks.withLock { $0 += 1 } + } + + /// A check for the moment a QuickPay payment is submitted, which can come after waits that outlast a lock and runs + /// off the main actor: it throws once the app has locked since this call. + func quickPaySubmissionCheck() -> @Sendable () throws -> Void { + let appLocks = appLocks + let seen = Self.count(appLocks) + return { + if Self.count(appLocks) != seen { + throw SendStoppedBeforeSubmission() + } + } + } + + private nonisolated static func count(_ locks: OSAllocatedUnfairLock) -> Int { + locks.withLock { $0 } + } + + /// Called when a request is routed to QuickPay. + func noteQuickPayChosen() { + quickPayChosenAtLockGeneration = appLockGeneration + } + + /// Whether the app locked after QuickPay was chosen. The QuickPay screen can appear only later (for example once + /// the node is ready), and a payment chosen before a lock must not start on its own after the unlock. + var didLockSinceQuickPayWasChosen: Bool { + quickPayChosenAtLockGeneration.map { $0 != appLockGeneration } ?? false + } + + /// True while a payment request that must always be reviewed (for example one read over Bluetooth) routes. + var isQuickPaySuppressed: Bool { + !quickPaySuppressions.isEmpty + } + + func suppressQuickPay(_ id: UUID) { + quickPaySuppressions.insert(id) + } + + /// Releasing an id that is no longer held does nothing. + func releaseQuickPaySuppression(_ id: UUID) { + quickPaySuppressions.remove(id) + } + /// The last routed deep link. On a cold start the same link reaches the app twice (`onOpenURL` and the scene /// delegate replay), and the startup gates can route the first delivery before the second arrives. private var lastRoutedDeepLink: (url: URL, date: Date)? @@ -223,6 +288,7 @@ class AppViewModel: ObservableObject { @AppStorage("hasSeenProfileIntro") var hasSeenProfileIntro: Bool = false @AppStorage("hasSeenNotificationsIntro") var hasSeenNotificationsIntro: Bool = false @AppStorage("hasSeenQuickpayIntro") var hasSeenQuickpayIntro: Bool = false + @AppStorage("hasSeenNfcIntro") var hasSeenNfcIntro: Bool = false @AppStorage("hasSeenMoveToSparkIntro") var hasSeenMoveToSparkIntro: Bool = false @AppStorage("hasSeenShopIntro") var hasSeenShopIntro: Bool = false @AppStorage("hasSeenTransferIntro") var hasSeenTransferIntro: Bool = false @@ -579,6 +645,7 @@ class AppViewModel: ObservableObject { hasSeenProfileIntro = false hasSeenNotificationsIntro = false hasSeenQuickpayIntro = false + hasSeenNfcIntro = false hasSeenMoveToSparkIntro = false hasSeenShopIntro = false hasSeenTransferIntro = false diff --git a/Bitkit/ViewModels/NavigationViewModel.swift b/Bitkit/ViewModels/NavigationViewModel.swift index 47a9bccae1..39ad82d9c8 100644 --- a/Bitkit/ViewModels/NavigationViewModel.swift +++ b/Bitkit/ViewModels/NavigationViewModel.swift @@ -210,7 +210,16 @@ func resolveUsdtPaymentRoute(input: String, isEnabled: Bool = Env.isUsdtEnabled) @MainActor class NavigationViewModel: ObservableObject { - @Published var path: [Route] = [] + @Published var path: [Route] = [] { + didSet { + if path != oldValue { + pathGeneration += 1 + } + } + } + + /// Changes with every change to `path`, so leaving a screen and coming back is not the same visit. + private(set) var pathGeneration = 0 var currentRoute: Route? { path.last diff --git a/Bitkit/ViewModels/SettingsViewModel.swift b/Bitkit/ViewModels/SettingsViewModel.swift index 23a9cf5df8..ab9bc539aa 100644 --- a/Bitkit/ViewModels/SettingsViewModel.swift +++ b/Bitkit/ViewModels/SettingsViewModel.swift @@ -112,6 +112,7 @@ class SettingsViewModel: NSObject, ObservableObject { @AppStorage("warnWhenSendingOver100") var warnWhenSendingOver100: Bool = false // QuickPay: change only through `changeQuickpaySetting`, which asks for the payment PIN before QuickPay may spend more. @AppStorage("enableQuickpay") private(set) var enableQuickpay: Bool = false + @AppStorage("enableNearbyPayments") var enableNearbyPayments: Bool = true @AppStorage("quickpayAmount") private(set) var quickpayAmount: Double = 5 @AppStorage("quickpayDailyLimitMultiplier") private(set) var quickpayDailyLimitMultiplier: Double = 5 private var pendingQuickpayChangeID: UUID? @@ -234,6 +235,7 @@ class SettingsViewModel: NSObject, ObservableObject { readClipboard = false warnWhenSendingOver100 = false enableQuickpay = false + enableNearbyPayments = true quickpayAmount = 5 quickpayDailyLimitMultiplier = 5 enableNotifications = false @@ -1050,6 +1052,7 @@ class SettingsViewModel: NSObject, ObservableObject { readClipboard = defaults.bool(forKey: "readClipboard") warnWhenSendingOver100 = defaults.bool(forKey: "warnWhenSendingOver100") reloadQuickpaySettingsFromDefaults() + enableNearbyPayments = defaults.object(forKey: "enableNearbyPayments") as? Bool ?? true enableNotifications = defaults.bool(forKey: "enableNotifications") requirePinForPayments = defaults.bool(forKey: "requirePinForPayments") useBiometrics = defaults.bool(forKey: "useBiometrics") diff --git a/Bitkit/ViewModels/SheetViewModel.swift b/Bitkit/ViewModels/SheetViewModel.swift index 728459caf2..fe32f02e1c 100644 --- a/Bitkit/ViewModels/SheetViewModel.swift +++ b/Bitkit/ViewModels/SheetViewModel.swift @@ -16,6 +16,7 @@ enum SheetID: String, CaseIterable { case paymentRequests case subscription case quickpay + case nfcIntro case usdtIntro case moveToSpark case receive @@ -69,6 +70,11 @@ class SheetViewModel: ObservableObject { @Published var hardwareConnectHandlesPairing = false @Published private(set) var isReplacingSheet = false @Published private(set) var replacingSheetID: SheetID? + /// Deferred replacements that have not run yet, by id. An owner can cancel its own with `cancelReplacement`. + private var pendingReplacements: Set = [] + private var nextReplacementID = 0 + /// The id of the most recent deferred replacement. + private(set) var latestReplacementID: Int? var isPubkyAuthApprovalShownOrPending: Bool { activeSheetConfiguration?.id == .pubkyAuthApproval || replacingSheetID == .pubkyAuthApproval @@ -85,6 +91,7 @@ class SheetViewModel: ObservableObject { isReplacingSheet = true replacingSheetID = id hideSheet() + let replacement = beginReplacement() DispatchQueue.main.asyncAfter(deadline: .now() + Self.replacementDelaySeconds) { [weak self] in guard let self else { return } @@ -92,6 +99,7 @@ class SheetViewModel: ObservableObject { if replacingSheetID == id { replacingSheetID = nil } + guard pendingReplacements.remove(replacement) != nil else { return } Logger.debug("Showing sheet \(id.rawValue) after delay", context: "SheetViewModel") activeSheetConfiguration = SheetConfiguration(id: id, data: data) playHaptics(for: id) @@ -144,14 +152,27 @@ class SheetViewModel: ObservableObject { isReplacingSheet = true hideSheet(reason: reason) + let replacement = beginReplacement() DispatchQueue.main.asyncAfter(deadline: .now() + Self.replacementDelaySeconds) { [weak self] in guard let self else { return } isReplacingSheet = false - guard activeSheetConfiguration == nil else { return } + guard pendingReplacements.remove(replacement) != nil, activeSheetConfiguration == nil else { return } action() } } + private func beginReplacement() -> Int { + nextReplacementID += 1 + pendingReplacements.insert(nextReplacementID) + latestReplacementID = nextReplacementID + return nextReplacementID + } + + /// Stops a deferred replacement that has not run yet: its sheet is not shown and its action does not run. + func cancelReplacement(_ id: Int) { + pendingReplacements.remove(id) + } + func hideSheetIfActive(_ id: SheetID, reason: String? = nil, file: String = #file, function: String = #function, line: Int = #line) { guard activeSheetConfiguration?.id == id else { let fallback = "\(URL(fileURLWithPath: file).lastPathComponent):\(line) \(function)" @@ -420,6 +441,18 @@ class SheetViewModel: ObservableObject { } } + var nfcIntroSheetItem: NfcIntroSheetItem? { + get { + guard let config = activeSheetConfiguration, config.id == .nfcIntro else { return nil } + return NfcIntroSheetItem() + } + set { + if newValue == nil { + activeSheetConfiguration = nil + } + } + } + var receiveSheetItem: ReceiveSheetItem? { get { guard let config = activeSheetConfiguration, config.id == .receive else { return nil } diff --git a/Bitkit/Views/Offline/OfflineSheetScreen.swift b/Bitkit/Views/Offline/OfflineSheetScreen.swift index 093145d8fa..df9a4d16e9 100644 --- a/Bitkit/Views/Offline/OfflineSheetScreen.swift +++ b/Bitkit/Views/Offline/OfflineSheetScreen.swift @@ -35,6 +35,7 @@ private struct OfflineSheetOverlayModifier: ViewModifier { func body(content: Content) -> some View { ZStack(alignment: .top) { content + .environment(\.isCoveredByOfflineSheet, isShowing) if isShowing { OfflineSheetScreen(title: title) @@ -51,10 +52,23 @@ private struct OfflineSheetOverlayModifier: ViewModifier { } } +private struct IsCoveredByOfflineSheetKey: EnvironmentKey { + static let defaultValue = false +} + +extension EnvironmentValues { + /// True while `offlineSheetOverlay` covers the view, which stays mounted underneath. + var isCoveredByOfflineSheet: Bool { + get { self[IsCoveredByOfflineSheetKey.self] } + set { self[IsCoveredByOfflineSheetKey.self] = newValue } + } +} + extension View { /// Overlays a `OfflineSheetScreen` when the device is offline, or whenever `forceShow` is true /// (e.g. connection issues beyond device connectivity, like an unreachable Lightning peer). - /// The underlying content remains mounted so navigation state and inputs are preserved. + /// The underlying content remains mounted so navigation state and inputs are preserved; it can read + /// `isCoveredByOfflineSheet` to pause what should not run while hidden. func offlineSheetOverlay(title: String, forceShow: Bool = false, isEnabled: Bool = true) -> some View { modifier(OfflineSheetOverlayModifier(title: title, forceShow: forceShow, isEnabled: isEnabled)) } diff --git a/Bitkit/Views/Scanner/ScannerScreen.swift b/Bitkit/Views/Scanner/ScannerScreen.swift index 1b2a4e121b..0b6de090f8 100644 --- a/Bitkit/Views/Scanner/ScannerScreen.swift +++ b/Bitkit/Views/Scanner/ScannerScreen.swift @@ -26,6 +26,23 @@ struct ScannerScreen: View { return .main } + /// Whether the scanner reads payment requests over NFC and Bluetooth: only when it scans for a payment, not for + /// a node to connect to during manual channel setup. + static func readsNearby(context: ScannerContext, path: [Route]) -> Bool { + context == .main && !path.contains(where: isNodeSetup) + } + + private static func isNodeSetup(_ route: Route) -> Bool { + if case .fundManual = route { + return true + } + return false + } + + private var readsNearby: Bool { + Self.readsNearby(context: scannerContext, path: navigation.path) + } + var body: some View { VStack(alignment: .leading, spacing: 0) { NavigationBar(title: t("other__qr_scan")) @@ -36,7 +53,14 @@ struct ScannerScreen: View { }, onImageSelection: { item in await scanner.handleImageSelection(item, context: scannerContext) - } + }, + onNfcRead: readsNearby && scanner.isNfcReadingAvailable + ? { await scanner.handleNfcRead(context: scannerContext) } + : nil, + onNearbyRequest: readsNearby + ? { await scanner.handleNearbyRequest($0, context: scannerContext, isCurrent: $1) } + : nil, + isNearbyPaused: sheets.activeSheetConfiguration != nil ) .padding(.bottom, 16) diff --git a/Bitkit/Views/Scanner/ScannerSheet.swift b/Bitkit/Views/Scanner/ScannerSheet.swift index 14731bea4b..6cb9713940 100644 --- a/Bitkit/Views/Scanner/ScannerSheet.swift +++ b/Bitkit/Views/Scanner/ScannerSheet.swift @@ -33,7 +33,12 @@ struct ScannerSheet: View { }, onImageSelection: { item in await scanner.handleImageSelection(item, context: .main) - } + }, + onNfcRead: scanner.isNfcReadingAvailable + ? { await scanner.handleNfcRead(context: .main) } + : nil, + onNearbyRequest: { await scanner.handleNearbyRequest($0, context: .main, isCurrent: $1) }, + isNearbyPaused: sheets.activeSheetConfiguration?.id != .scanner ) .padding(.bottom, 16) diff --git a/Bitkit/Views/Settings/SecuritySettingsView.swift b/Bitkit/Views/Settings/SecuritySettingsView.swift index 70a2c4653c..4adefee064 100644 --- a/Bitkit/Views/Settings/SecuritySettingsView.swift +++ b/Bitkit/Views/Settings/SecuritySettingsView.swift @@ -132,6 +132,14 @@ struct SecuritySettingsView: View { toggle: $settings.readClipboard, testIdentifier: "AutoReadClipboard" ) + + SettingsRow( + title: t("settings__security__nearby_payments"), + subtitle: t("settings__security__nearby_payments_text"), + iconName: "broadcast", + toggle: $settings.enableNearbyPayments, + testIdentifier: "NearbyPayments" + ) } .padding(.top, 16) .padding(.horizontal, 16) diff --git a/Bitkit/Views/Sheets/NfcIntroSheet.swift b/Bitkit/Views/Sheets/NfcIntroSheet.swift new file mode 100644 index 0000000000..6038c89dcb --- /dev/null +++ b/Bitkit/Views/Sheets/NfcIntroSheet.swift @@ -0,0 +1,114 @@ +import SwiftUI + +struct NfcIntroSheetItem: SheetItem { + let id: SheetID = .nfcIntro + let size: SheetSize = .large +} + +/// Announces NFC payments once, after updating to a version that supports them. +struct NfcIntroSheet: View { + @EnvironmentObject private var app: AppViewModel + @EnvironmentObject private var navigation: NavigationViewModel + @EnvironmentObject private var settings: SettingsViewModel + @EnvironmentObject private var sheets: SheetViewModel + let config: NfcIntroSheetItem + @State private var authorization = PaymentAuthorization(pinMessage: t("security__pin_quickpay")) + /// Bumped when a change is not saved at once, so the toggle redraws at the stored value. + @State private var toggleRevision = 0 + + var body: some View { + Sheet(id: .nfcIntro, data: config) { + NfcIntroContent( + isQuickpayEnabled: quickpayBinding, + onSettings: onSettings, + onContinue: onContinue + ) + .id(toggleRevision) + .paymentAuthorization(authorization) + } + } + + /// Turning QuickPay on asks for the payment PIN, as in QuickPay settings. + private var quickpayBinding: Binding { + Binding( + get: { settings.enableQuickpay }, + set: { isEnabled in + settings.changeQuickpaySetting(.enabled(isEnabled)) { + await authorization.authorize(settings: settings) + } + if settings.enableQuickpay != isEnabled { + toggleRevision += 1 + } + } + ) + } + + private func onSettings() { + app.hasSeenNfcIntro = true + sheets.hideSheet() + navigation.navigate(app.hasSeenQuickpayIntro ? .quickpay : .quickpayIntro) + } + + private func onContinue() { + app.hasSeenNfcIntro = true + sheets.hideSheet() + } +} + +struct NfcIntroContent: View { + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @Binding var isQuickpayEnabled: Bool + let onSettings: () -> Void + let onContinue: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + SheetHeader(title: t("other__nfc_intro__nav_title")) + + GeometryReader { geometry in + ScrollView(showsIndicators: false) { + VStack(alignment: .leading, spacing: 0) { + Image("nfc") + .resizable() + .aspectRatio(contentMode: .fit) + .frame(maxWidth: 256, maxHeight: 256) + .frame(maxWidth: .infinity) + .padding(.bottom, 32) + + DisplayText(t("other__nfc_intro__title"), accentColor: .purpleAccent) + .padding(.bottom, 8) + + BodyMText(t("other__nfc_intro__description"), textColor: .textSecondary) + .padding(.bottom, 16) + + SettingsRow( + title: t("other__nfc_intro__quickpay_toggle"), + toggle: $isQuickpayEnabled, + testIdentifier: "NfcIntroQuickpayToggle" + ) + } + .frame(minHeight: geometry.size.height, alignment: .bottom) + } + } + + let buttonLayout = dynamicTypeSize.isAccessibilitySize + ? AnyLayout(VStackLayout(spacing: 16)) + : AnyLayout(HStackLayout(spacing: 16)) + buttonLayout { + CustomButton(title: t("other__nfc_intro__settings"), variant: .secondary, shouldExpand: true, action: onSettings) + .accessibilityIdentifier("NfcIntroSettings") + CustomButton(title: t("other__nfc_intro__continue"), shouldExpand: true, action: onContinue) + .accessibilityIdentifier("NfcIntroContinue") + } + .padding(.top, 24) + } + .padding(.horizontal, 16) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("NfcIntro") + } +} + +#Preview { + NfcIntroContent(isQuickpayEnabled: .constant(true), onSettings: {}, onContinue: {}) + .preferredColorScheme(.dark) +} diff --git a/Bitkit/Views/Wallets/Receive/QrArea.swift b/Bitkit/Views/Wallets/Receive/QrArea.swift index cfa88ae593..57261c19a1 100644 --- a/Bitkit/Views/Wallets/Receive/QrArea.swift +++ b/Bitkit/Views/Wallets/Receive/QrArea.swift @@ -7,6 +7,8 @@ struct QrArea: View { var copyValue: String? var shareText: String? var copyMessage: String? + /// Shown while the request is offered to nearby phones over Bluetooth. + var showsTapToPay = false var onEdit: (() -> Void)? @State private var showCopyTooltip = false @@ -79,6 +81,10 @@ struct QrArea: View { // Generate the QR image for sharing shareQRImage = QR.shareImage(content: uri) } + + if showsTapToPay { + ReceiveTapToPayLabel() + } } private func onCopy() { @@ -98,3 +104,20 @@ struct QrArea: View { } } } + +/// "Scan or tap to pay" under the receive actions, shown while nearby phones can read the request. +struct ReceiveTapToPayLabel: View { + var body: some View { + HStack(spacing: 8) { + Image("broadcast") + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 16, height: 16) + .foregroundColor(.textSecondary) + CaptionMText(t("wallet__receive_scan_or_tap"), textColor: .textSecondary) + } + .frame(maxWidth: .infinity) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("ReceiveTapToPay") + } +} diff --git a/Bitkit/Views/Wallets/Receive/ReceiveQr.swift b/Bitkit/Views/Wallets/Receive/ReceiveQr.swift index ac2023a4b2..67174e3556 100644 --- a/Bitkit/Views/Wallets/Receive/ReceiveQr.swift +++ b/Bitkit/Views/Wallets/Receive/ReceiveQr.swift @@ -30,6 +30,13 @@ struct ReceiveQr: View { @State private var verifyTask: Task? @State private var passphraseTask: Task? @State private var engagedSession = HwEngagedSession() + @State private var nearbyAdvertiser = NearbyPaymentAdvertiser() + /// Whether the QR page is on screen. The view stays mounted as the navigation root while Edit or another route is + /// pushed, and still sees app and request changes then. + @State private var isShown = false + @Environment(\.scenePhase) private var scenePhase + @Environment(TrezorManager.self) private var trezorManager + @Environment(\.isCoveredByOfflineSheet) private var isCoveredByOfflineSheet init( navigationPath: Binding<[ReceiveRoute]>, @@ -270,6 +277,17 @@ struct ReceiveQr: View { .sheetBackground() .accessibilityElement(children: .contain) .accessibilityIdentifier("ReceiveScreen") + .onAppear { + isShown = true + updateNearbyAdvertising() + } + .onChange(of: nearbyRequest) { updateNearbyAdvertising() } + .onChange(of: scenePhase) { updateNearbyAdvertising() } + .onChange(of: isQrCovered) { updateNearbyAdvertising() } + .onDisappear { + isShown = false + nearbyAdvertiser.stop() + } .sheet(isPresented: passphrasePromptBinding) { HwPassphrasePromptSheet( isVerifying: isVerifyingPassphrase, @@ -412,6 +430,7 @@ struct ReceiveQr: View { imageAsset: "btc-circle-blue", accentColor: .blueAccent, copyValue: uri.contains("?") ? uri : hardwareAddress.address, + showsTapToPay: nearbyAdvertiser.isAdvertising, onEdit: { navigationPath.append(.edit(tab: .hardware, onchainOnly: true)) } ) } else if hardwareAddressLoadFailed { @@ -435,6 +454,7 @@ struct ReceiveQr: View { uri: config.uri, imageAsset: config.imageAsset, accentColor: config.accentColor, + showsTapToPay: nearbyAdvertiser.isAdvertising, onEdit: editRoute(for: tab).map { route in { navigationPath.append(route) } } @@ -446,6 +466,60 @@ struct ReceiveQr: View { } } + /// The request offered to nearby phones over Bluetooth, or nil when nothing should be advertised. Only a request + /// the payer can check on screen is offered: none while the connection-issues screen covers Receive or the page + /// shows a spinner, Retry or an error in its place, and none for a tab that is hidden but not yet left. + private var nearbyRequest: String? { + guard settings.enableNearbyPayments, + Self.tab(selectedTab, canShowUnifiedReceive: canShowUnifiedReceive) == selectedTab, + !isCoveredByOfflineSheet else { return nil } + switch selectedTab { + case .usdt: + return nil + case .hardware: + guard let address = displayedHardwareAddress?.address else { return nil } + return NearbyPaymentUri.from(Bip21Utils.hardwareInvoice( + address: address, + amountSats: wallet.invoiceAmountSats, + message: wallet.invoiceNote + )) + default: + guard Self.showsRequest( + needsInvoiceRefresh: needsInvoiceRefresh, + isReceiveUnavailable: receiveUnavailable(for: selectedTab) + ) else { return nil } + return NearbyPaymentUri.from(qrConfig(for: selectedTab).uri) + } + } + + /// Whether a Savings, Spending or Unified page shows its request, as `tabContent` decides: a page waiting for + /// its first refresh shows a spinner or Retry, and an updating or failed invoice shows its status instead. + static func showsRequest(needsInvoiceRefresh: Bool, isReceiveUnavailable: Bool) -> Bool { + !needsInvoiceRefresh && !isReceiveUnavailable + } + + /// The request to advertise: only while the QR page is on screen, with nothing pushed or presented over it, and + /// the app active. + static func advertisedRequest(_ request: String?, isShown: Bool, isCovered: Bool, isActive: Bool) -> String? { + isShown && !isCovered && isActive ? request : nil + } + + /// Whether a pushed route (Edit), the passphrase prompt or the hardware pairing sheet covers the QR page. A + /// presented sheet or a pop by swipe does not trigger `onAppear` or `onDisappear` when it changes. + private var isQrCovered: Bool { + !navigationPath.isEmpty || isPassphraseRequired || trezorManager.showPairingCode + } + + private func updateNearbyAdvertising() { + if let request = Self.advertisedRequest( + nearbyRequest, isShown: isShown, isCovered: isQrCovered, isActive: scenePhase == .active + ) { + nearbyAdvertiser.start(request: request) + } else { + nearbyAdvertiser.stop() + } + } + private func receiveUnavailable(for tab: ReceiveTab) -> Bool { guard tab == .unified || tab == .spending else { return false } return wallet.isReceiveInvoiceUpdating || wallet.receiveInvoiceError != nil || diff --git a/Bitkit/Views/Wallets/Send/SendEnterManuallyView.swift b/Bitkit/Views/Wallets/Send/SendEnterManuallyView.swift index 4571274d12..9f2db083c2 100644 --- a/Bitkit/Views/Wallets/Send/SendEnterManuallyView.swift +++ b/Bitkit/Views/Wallets/Send/SendEnterManuallyView.swift @@ -96,6 +96,9 @@ struct SendEnterManuallyView: View { return } + // A lookup (LNURL, Lightning address) can outlast a PIN lock; its result must not route, or choose QuickPay, + // after the unlock. + let isBeforeLock = app.lockCheck() do { wallet.resetSendState(speed: settings.defaultTransactionSpeed) @@ -105,14 +108,16 @@ struct SendEnterManuallyView: View { Logger.error("Failed to set default fee rate: \(error)") } - guard sheets.activeSheetConfiguration?.presentationID == presentationID else { return } + guard sheets.activeSheetConfiguration?.presentationID == presentationID, isBeforeLock() else { return } try await app.handleScannedData( uri, scope: hwSend.isActive ? .onchainPayments : .unrestricted, alternativeOnchainBalanceSats: hwWalletManager.maximumFundingBalanceSats, - sendPresentationID: presentationID + sendPresentationID: presentationID, + isCurrentScan: isBeforeLock ) + guard isBeforeLock() else { return } if let route = PaymentNavigationHelper.appropriateSendRoute( app: app, currency: currency, @@ -122,6 +127,8 @@ struct SendEnterManuallyView: View { } } catch { Logger.error(error, context: "Failed to read data from clipboard") + // A lookup from before a lock that fails after the unlock is dropped without a toast. + guard isBeforeLock() else { return } app.toast(error) } } diff --git a/Bitkit/Views/Wallets/Send/SendOptionsView.swift b/Bitkit/Views/Wallets/Send/SendOptionsView.swift index 84532d3f35..589920831a 100644 --- a/Bitkit/Views/Wallets/Send/SendOptionsView.swift +++ b/Bitkit/Views/Wallets/Send/SendOptionsView.swift @@ -14,10 +14,14 @@ struct SendOptionsView: View { @EnvironmentObject var sheets: SheetViewModel @EnvironmentObject var wallet: WalletViewModel @Environment(HwWalletManager.self) private var hwWalletManager + @Environment(\.isCoveredByOfflineSheet) private var isCoveredByOfflineSheet @Binding var navigationPath: [SendRoute] let hwSend: HwSendCoordinator @State private var selectedItem: PhotosPickerItem? + /// Bumped each time Send leaves Options or the connection-issues screen covers it, so a read started before + /// can't route after the user comes back. + @State private var scannerVisit = 0 private var scanScope: ScanHandlingScope { hwSend.isActive ? .onchainPayments : .unrestricted @@ -42,16 +46,42 @@ struct SendOptionsView: View { } }, onImageSelection: { item in + // Moving on (e.g. to Enter Manually) keeps the sheet open, so check its own path too. await scanner.handleImageSelection( item, context: .send, + isCurrent: isOnThisScannerVisit(), scope: scanScope ) { route in if let route { handleRoute(route) } } - } + }, + onNfcRead: scanner.isNfcReadingAvailable + ? { + // Moving on (e.g. to Enter Manually) keeps the sheet open, so check its own path too. + await scanner.handleSendNfcRead(scope: scanScope, isCurrent: isOnThisScannerVisit()) { route in + if let route { + handleRoute(route) + } + } + } + : nil, + onNearbyRequest: { request, isScanning in + // Moving on (e.g. to Enter Manually) keeps the sheet open, so check its own path too. + let isOnVisit = isOnThisScannerVisit() + return await scanner.handleSendNearbyRequest( + request, + scope: scanScope, + isCurrent: { isOnVisit() && isScanning() } + ) { route in + if let route { + handleRoute(route) + } + } + }, + isNearbyPaused: !navigationPath.isEmpty || isCoveredByOfflineSheet ) RectangleButton( @@ -100,6 +130,24 @@ struct SendOptionsView: View { hwWalletManager: hwWalletManager ) } + .onChange(of: navigationPath.isEmpty) { _, isOnOptions in + if !isOnOptions { + scannerVisit += 1 + } + } + .onChange(of: isCoveredByOfflineSheet) { _, isCovered in + // A read that started before the connection-issues screen covered Options can't route behind it. + if isCovered { + scannerVisit += 1 + } + } + } + + /// True while Send still shows Options in the same visit as when this is called. A visit ends when Send moves on + /// or the connection-issues screen covers Options. + private func isOnThisScannerVisit() -> () -> Bool { + let visit = scannerVisit + return { navigationPath.isEmpty && scannerVisit == visit } } func handlePaste() { diff --git a/Bitkit/Views/Wallets/Send/SendQuickpay.swift b/Bitkit/Views/Wallets/Send/SendQuickpay.swift index c3f95a0d65..f669d52c1c 100644 --- a/Bitkit/Views/Wallets/Send/SendQuickpay.swift +++ b/Bitkit/Views/Wallets/Send/SendQuickpay.swift @@ -41,9 +41,15 @@ struct SendQuickpay: View { .frame(maxWidth: .infinity, maxHeight: .infinity) .onAppear { guard isCurrentPresentation(), !app.isHandlingScannedData else { return } + guard Self.startsAutomatically(app: app, sessionID: sessionID) else { + // Chosen before the app locked: the payer reviews it instead. + replaceQuickPay(PaymentNavigationHelper.confirmRouteAfterQuickPayCap(app: app)) + return + } if displayedSats == nil { displayedSats = app.lnurlPayData?.minSendableSat ?? app.scannedLightningInvoice?.amountSatoshis } + let recoveryOnly = Self.isRecoveryOnly(app: app, sessionID: sessionID) QuickPayPaymentCoordinator.shared.pay( app: app, wallet: wallet, @@ -55,8 +61,35 @@ struct SendQuickpay: View { addPendingPaymentHash: { app.addPendingPaymentHash($0) }, routingCacheResetAttempted: routingCacheResetAttempted ), - sessionID: sessionID + sessionID: sessionID, + recoveryOnly: recoveryOnly ) } } + + /// Whether the payment starts as the screen appears. A payment already started reattaches, and an invoice the + /// coordinator already tracks (a rescan of a payment in progress) replays its status. Only a new submission chosen + /// before the app locked waits for review. + @MainActor + static func startsAutomatically( + app: AppViewModel, + sessionID: QuickPayPaymentCoordinator.SessionID, + coordinator: QuickPayPaymentCoordinator? = nil + ) -> Bool { + let coordinator = coordinator ?? .shared + let paymentHash = app.scannedLightningInvoice?.paymentHash.hex ?? "" + return coordinator.isAttached(to: sessionID) || coordinator.hasOpen(paymentHash) || !app.didLockSinceQuickPayWasChosen + } + + /// Whether a start may only replay a tracked payment: after a lock, a new submission needs review, so a payment + /// that is no longer tracked by the time the coordinator runs falls back to it instead of being sent. + @MainActor + static func isRecoveryOnly( + app: AppViewModel, + sessionID: QuickPayPaymentCoordinator.SessionID, + coordinator: QuickPayPaymentCoordinator? = nil + ) -> Bool { + let coordinator = coordinator ?? .shared + return !coordinator.isAttached(to: sessionID) && app.didLockSinceQuickPayWasChosen + } } diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index 32a1e70843..34cf2ce178 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -1464,6 +1464,8 @@ struct SendSheet: View { let route = retryRoute.sendRoute if retryRoute == .quickpay { app.resetQuickPay() + // Retrying is the payer's own choice, made after any lock. + app.noteQuickPayChosen() flow.quickPaySession += 1 } if route == config.initialRoute || currentRoot == route { diff --git a/Bitkit/Views/Wallets/UsdtReceiveView.swift b/Bitkit/Views/Wallets/UsdtReceiveView.swift index 5a8269bd87..245fbf636e 100644 --- a/Bitkit/Views/Wallets/UsdtReceiveView.swift +++ b/Bitkit/Views/Wallets/UsdtReceiveView.swift @@ -9,6 +9,9 @@ struct UsdtReceiveView: View { @EnvironmentObject private var navigation: NavigationViewModel @EnvironmentObject private var sheets: SheetViewModel @Environment(\.scenePhase) private var scenePhase + @Environment(\.isCoveredByOfflineSheet) private var isCoveredByOfflineSheet + @EnvironmentObject private var settings: SettingsViewModel + @State private var nearbyAdvertiser = NearbyPaymentAdvertiser() @State private var networks: [UsdtDepositNetwork] = [] @State private var network: UsdtDepositNetwork? @State private var page = Page.address @@ -70,6 +73,36 @@ struct UsdtReceiveView: View { do { networks = try await usdt.depositNetworks() } catch is CancellationError {} catch { self.error = t("usdt__deposit_unavailable") } } + .onAppear { updateNearbyAdvertising() } + .onChange(of: nearbyRequest) { updateNearbyAdvertising() } + .onChange(of: scenePhase) { updateNearbyAdvertising() } + .onDisappear { nearbyAdvertiser.stop() } + } + + private var nearbyRequest: String? { + Self.nearbyRequest( + receiveUri: receiveUri, + isEnabled: settings.enableNearbyPayments, + showsAddress: page == .address, + hasDeposit: deposit != nil, + isCovered: isCoveredByOfflineSheet + ) + } + + /// The Arbitrum EIP-681 request offered to nearby phones over Bluetooth. Deposit addresses on other networks + /// are not offered, because nearby phones pay USDT on Arbitrum only. Nothing is offered while the + /// connection-issues screen covers the QR, so the payer cannot read a request the receiver cannot see. + static func nearbyRequest(receiveUri: String, isEnabled: Bool, showsAddress: Bool, hasDeposit: Bool, isCovered: Bool) -> String? { + guard isEnabled, showsAddress, !hasDeposit, !isCovered, !receiveUri.isEmpty else { return nil } + return NearbyPaymentUri.from(receiveUri) + } + + private func updateNearbyAdvertising() { + if scenePhase == .active, let nearbyRequest { + nearbyAdvertiser.start(request: nearbyRequest) + } else { + nearbyAdvertiser.stop() + } } private var pageContent: some View { @@ -88,6 +121,7 @@ struct UsdtReceiveView: View { network: networkName, amount: amount, error: error ?? usdt.errorMessage, + showsTapToPay: nearbyAdvertiser.isAdvertising, onEdit: { draftAmount = amount; show(.amount) }, onNetwork: { show(.networks) } ) @@ -227,6 +261,7 @@ struct UsdtReceiveAddressContent: View { let network: String var amount = "" var error: String? + var showsTapToPay = false let onEdit: () -> Void let onNetwork: () -> Void @State private var showDetails = false @@ -243,7 +278,8 @@ struct UsdtReceiveAddressContent: View { var body: some View { if !uri.isEmpty, !showDetails { QrArea(uri: uri, imageAsset: "tether-circle", accentColor: .usdtAccent, - copyValue: address, shareText: shareText, copyMessage: t("usdt__receive_copied"), onEdit: onEdit) + copyValue: address, shareText: shareText, copyMessage: t("usdt__receive_copied"), + showsTapToPay: showsTapToPay, onEdit: onEdit) } else { ScrollView(showsIndicators: false) { if !uri.isEmpty { diff --git a/BitkitTests/AddressTypeSettingsTests.swift b/BitkitTests/AddressTypeSettingsTests.swift index 849a901338..c3705041b6 100644 --- a/BitkitTests/AddressTypeSettingsTests.swift +++ b/BitkitTests/AddressTypeSettingsTests.swift @@ -350,6 +350,22 @@ final class AddressTypeSettingsTests: XCTestCase { XCTAssertEqual(backupDict["quickPayDailyLimitMultiplier"] as? Int, 10) } + func testNearbyPaymentsFollowARestoredBackup() { + settings.enableNearbyPayments = false + var backupDict = settings.getSettingsDictionary() + XCTAssertEqual(backupDict["isNearbyPaymentsEnabled"] as? Bool, false) + + settings.resetToDefaults() + XCTAssertTrue(settings.enableNearbyPayments) + + settings.restoreSettingsDictionary(backupDict) + XCTAssertFalse(settings.enableNearbyPayments, "A restored off must apply without a relaunch") + + backupDict.removeValue(forKey: "isNearbyPaymentsEnabled") + settings.restoreSettingsDictionary(backupDict) + XCTAssertTrue(settings.enableNearbyPayments, "A backup without the key restores the default on") + } + func testRestoresQuickpayAmountFromAndroidKey() { settings.restoreSettingsDictionary(["quickPayAmount": 1]) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index f6130a12ba..1f4aba0746 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1082,6 +1082,30 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + private nonisolated static func stopBeforeSubmission() throws { + throw Bitkit.SendStoppedBeforeSubmission() + } + + func testASendStoppedBeforeSubmissionIsNotHeldWhileSparkCannotList() async { + rail.balanceSats = 100_000 + _ = try? await Bitkit.LightningService.shared.send(bolt11: Self.invoice, beforeSubmission: Self.stopBeforeSubmission) + XCTAssertEqual(rail.sends, 0) + rail.listError = NSError(domain: "spark", code: 1) + rail.balanceSats = 0 + + await assertReachesTheNode() + } + + func testASendStoppedBeforeSubmissionLeavesNoHold() async { + rail.balanceSats = 100_000 + _ = try? await Bitkit.LightningService.shared.send(bolt11: Self.invoice, beforeSubmission: Self.stopBeforeSubmission) + XCTAssertEqual(rail.sends, 0) + + // The payer reviews it and swipes: the same invoice goes out over Spark, with no unknown send held from the stop. + _ = try? await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTAssertEqual(rail.sends, 1, "A send stopped before submission must not hold the invoice") + } + func testSparkHistoryReadsAsUnavailableWhileSparkIsDisconnected() async { Bitkit.LightningService.shared.channelFreeRail = nil diff --git a/BitkitTests/NdefPayloadParserTests.swift b/BitkitTests/NdefPayloadParserTests.swift new file mode 100644 index 0000000000..951744efb6 --- /dev/null +++ b/BitkitTests/NdefPayloadParserTests.swift @@ -0,0 +1,87 @@ +@testable import Bitkit +import XCTest + +final class NdefPayloadParserTests: XCTestCase { + private let invoice = "lnbcrt10u1pjexample" + + func testUriRecordWithoutPrefixCodeKeepsTheFullUri() { + let record = uriRecord(code: 0x00, "lightning:\(invoice)") + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: [record]), .success("lightning:\(invoice)")) + } + + func testUriRecordExpandsPrefixCode() { + let record = uriRecord(code: 0x04, "example.com/lnurlp/alice") + XCTAssertEqual(NdefPayloadParser.decode(record), "https://example.com/lnurlp/alice") + } + + func testUnknownPrefixCodeIsTreatedAsNoPrefix() { + let record = uriRecord(code: 0xFE, "bitcoin:bcrt1qexample") + XCTAssertEqual(NdefPayloadParser.decode(record), "bitcoin:bcrt1qexample") + } + + func testUtf8TextRecordSkipsLanguageCode() { + let record = textRecord(language: "en", " lightning:\(invoice)\n") + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: [record]), .success("lightning:\(invoice)")) + } + + func testUtf16TextRecordIsDecoded() throws { + let text = "bitcoin:bcrt1qexample?lightning=\(invoice)" + var payload = Data([0x80 | 0x02]) + payload.append(contentsOf: Array("en".utf8)) + try payload.append(XCTUnwrap(text.data(using: .utf16))) + let record = NdefRecord(typeNameFormat: NdefPayloadParser.tnfWellKnown, type: Data([0x54]), payload: payload) + XCTAssertEqual(NdefPayloadParser.decode(record), text) + } + + func testAbsoluteUriRecordUsesTheTypeField() { + let uri = "ethereum:0x18503bD685aF84E6A7bC289898bAa1C3f5d8527E@42161" + let record = NdefRecord(typeNameFormat: NdefPayloadParser.tnfAbsoluteUri, type: Data(uri.utf8), payload: Data()) + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: [record]), .success(uri)) + } + + func testOtherRecordsAreIgnored() { + let androidAppRecord = NdefRecord( + typeNameFormat: 0x04, + type: Data("android.com:pkg".utf8), + payload: Data("to.bitkit".utf8) + ) + let records = [androidAppRecord, uriRecord(code: 0x00, "lightning:\(invoice)")] + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: records), .success("lightning:\(invoice)")) + } + + func testDuplicateRecordsCollapseToOneRequest() { + let records = [uriRecord(code: 0x00, "lightning:\(invoice)"), textRecord(language: "en", "lightning:\(invoice)")] + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: records), .success("lightning:\(invoice)")) + } + + func testDifferentRequestsAreRejected() { + let records = [uriRecord(code: 0x00, "lightning:\(invoice)"), uriRecord(code: 0x00, "bitcoin:bcrt1qexample")] + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: records), .failure(.multiplePayloads)) + } + + func testEmptyTagIsRejected() { + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: []), .failure(.empty)) + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: [textRecord(language: "en", " ")]), .failure(.empty)) + XCTAssertEqual(NdefPayloadParser.paymentRequest(from: [uriRecordPayload(Data())]), .failure(.empty)) + } + + func testTruncatedTextRecordIsIgnored() { + let record = NdefRecord(typeNameFormat: NdefPayloadParser.tnfWellKnown, type: Data([0x54]), payload: Data([0x05, 0x65])) + XCTAssertNil(NdefPayloadParser.decode(record)) + } + + private func uriRecord(code: UInt8, _ body: String) -> NdefRecord { + uriRecordPayload(Data([code]) + Data(body.utf8)) + } + + private func uriRecordPayload(_ payload: Data) -> NdefRecord { + NdefRecord(typeNameFormat: NdefPayloadParser.tnfWellKnown, type: Data([0x55]), payload: payload) + } + + private func textRecord(language: String, _ text: String) -> NdefRecord { + var payload = Data([UInt8(language.utf8.count)]) + payload.append(contentsOf: Array(language.utf8)) + payload.append(contentsOf: Array(text.utf8)) + return NdefRecord(typeNameFormat: NdefPayloadParser.tnfWellKnown, type: Data([0x54]), payload: payload) + } +} diff --git a/BitkitTests/NearbyPaymentScannerTests.swift b/BitkitTests/NearbyPaymentScannerTests.swift new file mode 100644 index 0000000000..b1a9215187 --- /dev/null +++ b/BitkitTests/NearbyPaymentScannerTests.swift @@ -0,0 +1,49 @@ +@testable import Bitkit +import XCTest + +@MainActor +final class NearbyPaymentScannerTests: XCTestCase { + func testStoppingRevokesARequestStillBeingHandled() async { + let scanner = NearbyPaymentScanner() + let handed = expectation(description: "Request handed to the scanner's owner") + var release: CheckedContinuation? + var isCurrent: (() -> Bool)? + scanner.start { _, check in + isCurrent = check + await withCheckedContinuation { + release = $0 + handed.fulfill() + } + return check() + } + + scanner.deliverForTesting("bitcoin:bcrt1qexample") + await fulfillment(of: [handed], timeout: 2) + XCTAssertEqual(isCurrent?(), true) + + // The app goes inactive (Control Center) while the request is decoding, then comes back. + scanner.stop() + XCTAssertEqual(isCurrent?(), false, "A stopped scanner's request must not route") + scanner.start { _, _ in false } + XCTAssertEqual(isCurrent?(), false, "Scanning again must not revive the earlier request") + release?.resume() + } + + func testARequestDeliveredJustBeforeStoppingReachesNoHandler() async { + let scanner = NearbyPaymentScanner() + var handled: [String] = [] + scanner.start { request, _ in + handled.append(request) + return false + } + + // The read completes, then the scene goes inactive before the delivery task runs. + scanner.deliverForTesting("pubkyauth://signin") + scanner.stop() + for _ in 0 ..< 10 { + await Task.yield() + } + + XCTAssertEqual(handled, [], "A revoked request must not reach the handler or show its error") + } +} diff --git a/BitkitTests/NearbyProtocolTests.swift b/BitkitTests/NearbyProtocolTests.swift new file mode 100644 index 0000000000..831e69c25b --- /dev/null +++ b/BitkitTests/NearbyProtocolTests.swift @@ -0,0 +1,140 @@ +@testable import Bitkit +import CoreBluetooth +import XCTest + +final class NearbyProtocolTests: XCTestCase { + func testUuidsMatchTheSharedSpec() { + XCTAssertEqual(NearbyProtocol.serviceUUID.uuidString, "CB0E128B-1CA5-4959-94DF-A4FE588E3E98") + XCTAssertEqual(NearbyProtocol.metaUUID.uuidString, "69A713E5-B0A7-42F1-8B7F-FA0BDA119C00") + XCTAssertEqual( + NearbyProtocol.dataUUIDs.map(\.uuidString), + (1 ... 8).map { String(format: "69A713E5-B0A7-42F1-8B7F-FA0BDA119C%02X", $0) } + ) + XCTAssertEqual(NearbyProtocol.minRssi, -60) + XCTAssertEqual(NearbyProtocol.maxRequestBytes, 4096) + } + + func testMetaIsVersionThenBigEndianLength() { + XCTAssertEqual([UInt8](NearbyProtocol.meta(for: Data(repeating: 0x61, count: 5))), [0x01, 0x00, 0x05]) + XCTAssertEqual([UInt8](NearbyProtocol.meta(for: Data(repeating: 0x61, count: 4096))), [0x01, 0x10, 0x00]) + XCTAssertEqual([UInt8](NearbyProtocol.meta(for: Data(repeating: 0x61, count: 513))), [0x01, 0x02, 0x01]) + } + + func testRequestLengthRejectsUnknownVersionAndBadLengths() { + XCTAssertEqual(NearbyProtocol.requestLength(meta: Data([0x01, 0x02, 0x01])), 513) + XCTAssertNil(NearbyProtocol.requestLength(meta: Data([0x02, 0x00, 0x05]))) + XCTAssertNil(NearbyProtocol.requestLength(meta: Data([0x01, 0x00, 0x00]))) + XCTAssertNil(NearbyProtocol.requestLength(meta: Data([0x01, 0x10, 0x01]))) + XCTAssertNil(NearbyProtocol.requestLength(meta: Data([0x01, 0x00]))) + } + + func testEncodeRejectsEmptyAndOversizedRequests() { + XCTAssertNil(NearbyProtocol.encodeRequest("")) + XCTAssertNil(NearbyProtocol.encodeRequest(String(repeating: "a", count: 4097))) + XCTAssertEqual(NearbyProtocol.encodeRequest(String(repeating: "a", count: 4096))?.count, 4096) + } + + func testChunksSplitAt512Bytes() { + let request = Data((0 ..< 1100).map { UInt8($0 % 251) }) + XCTAssertEqual(NearbyProtocol.chunks(for: request.count), 3) + XCTAssertEqual(NearbyProtocol.chunk(request, index: 0), request.subdata(in: 0 ..< 512)) + XCTAssertEqual(NearbyProtocol.chunk(request, index: 1), request.subdata(in: 512 ..< 1024)) + XCTAssertEqual(NearbyProtocol.chunk(request, index: 2), request.subdata(in: 1024 ..< 1100)) + XCTAssertEqual(NearbyProtocol.chunk(request, index: 3), Data()) + XCTAssertEqual(NearbyProtocol.chunk(request, index: 8), Data()) + XCTAssertEqual(NearbyProtocol.chunks(for: 512), 1) + XCTAssertEqual(NearbyProtocol.chunks(for: 4096), 8) + } + + func testRoundTripThroughMetaAndChunks() throws { + let uri = "lightning:lnbcrt" + String(repeating: "q", count: 1500) + let request = try XCTUnwrap(NearbyProtocol.encodeRequest(uri)) + let length = try XCTUnwrap(NearbyProtocol.requestLength(meta: NearbyProtocol.meta(for: request))) + let chunks = (0 ..< NearbyProtocol.chunks(for: length)).map { NearbyProtocol.chunk(request, index: $0) } + XCTAssertEqual(NearbyProtocol.decode(chunks: chunks, length: length), uri) + } + + func testDecodeRejectsLengthMismatch() { + XCTAssertNil(NearbyProtocol.decode(chunks: [Data("abc".utf8)], length: 4)) + } + + func testReadsHonourTheAttOffset() { + let value = Data([1, 2, 3, 4]) + XCTAssertEqual(NearbyProtocol.read(value, at: 0), value) + XCTAssertEqual(NearbyProtocol.read(value, at: 3), Data([4])) + XCTAssertEqual(NearbyProtocol.read(value, at: 4), Data()) + XCTAssertNil(NearbyProtocol.read(value, at: 5)) + XCTAssertNil(NearbyProtocol.read(value, at: -1)) + } + + func testValueForCharacteristic() { + let request = Data(repeating: 0x62, count: 600) + XCTAssertEqual(NearbyProtocol.value(for: NearbyProtocol.metaUUID, request: request), Data([0x01, 0x02, 0x58])) + XCTAssertEqual(NearbyProtocol.value(for: NearbyProtocol.dataUUIDs[1], request: request)?.count, 88) + XCTAssertEqual(NearbyProtocol.value(for: NearbyProtocol.dataUUIDs[7], request: request), Data()) + XCTAssertNil(NearbyProtocol.value(for: NearbyProtocol.serviceUUID, request: request)) + } + + func testPaymentUriAddsMissingSchemes() { + XCTAssertEqual(NearbyPaymentUri.from("lnbcrt10u1pjexample"), "lightning:lnbcrt10u1pjexample") + XCTAssertEqual(NearbyPaymentUri.from("LNBC10U1PJEXAMPLE"), "lightning:LNBC10U1PJEXAMPLE") + XCTAssertEqual(NearbyPaymentUri.from("lno1qexample"), "lightning:lno1qexample") + XCTAssertEqual(NearbyPaymentUri.from("LNURL1DP68GURN8GHJ7"), "lightning:LNURL1DP68GURN8GHJ7") + XCTAssertEqual(NearbyPaymentUri.from("bcrt1qexample"), "bitcoin:bcrt1qexample") + XCTAssertEqual(NearbyPaymentUri.from(" bitcoin:bcrt1q?lightning=lnbcrt1 "), "bitcoin:bcrt1q?lightning=lnbcrt1") + XCTAssertEqual(NearbyPaymentUri.from("ethereum:0xabc@42161"), "ethereum:0xabc@42161") + XCTAssertEqual(NearbyPaymentUri.from("LIGHTNING:LNBC1"), "LIGHTNING:LNBC1") + XCTAssertEqual(NearbyPaymentUri.from("lnurlw://example.com/w"), "lnurlw://example.com/w") + XCTAssertNil(NearbyPaymentUri.from(" ")) + XCTAssertNil(NearbyPaymentUri.from(nil)) + } + + func testScannerEligibilityAndDebounce() { + XCTAssertTrue(NearbyPaymentScanner.isEligible(rssi: -60)) + XCTAssertTrue(NearbyPaymentScanner.isEligible(rssi: -40)) + XCTAssertFalse(NearbyPaymentScanner.isEligible(rssi: -61)) + XCTAssertFalse(NearbyPaymentScanner.isEligible(rssi: 127)) + let now = Date() + XCTAssertFalse(NearbyPaymentScanner.isDebounced(nil, now: now)) + XCTAssertTrue(NearbyPaymentScanner.isDebounced(now.addingTimeInterval(-9.9), now: now)) + XCTAssertFalse(NearbyPaymentScanner.isDebounced(now.addingTimeInterval(-10), now: now)) + } + + @MainActor + func testAdvertiserServesTheRequestEachCentralStartedReading() throws { + let advertiser = NearbyPaymentAdvertiser(authorization: { .allowedAlways }) + let first = UUID() + let second = UUID() + let original = "lightning:lnbcrt" + String(repeating: "a", count: 700) + advertiser.setServedRequestForTesting(original) + XCTAssertNotNil(advertiser.servedRequest(for: first, characteristic: NearbyProtocol.metaUUID)) + + advertiser.setServedRequestForTesting("bitcoin:bcrt1qnew") + + let firstRequest = try XCTUnwrap(advertiser.servedRequest(for: first, characteristic: NearbyProtocol.dataUUIDs[1])) + XCTAssertEqual(firstRequest, Data(original.utf8)) + let secondMeta = try XCTUnwrap(advertiser.servedRequest(for: second, characteristic: NearbyProtocol.metaUUID)) + XCTAssertEqual(secondMeta, Data("bitcoin:bcrt1qnew".utf8)) + + advertiser.stop() + XCTAssertNil(advertiser.servedRequest(for: first, characteristic: NearbyProtocol.dataUUIDs[0])) + } + + @MainActor + func testAdvertiserDoesNotStartWithoutBluetoothPermission() { + for authorization in [CBManagerAuthorization.notDetermined, .denied, .restricted] { + let advertiser = NearbyPaymentAdvertiser(authorization: { authorization }) + XCTAssertFalse(advertiser.canAdvertise) + advertiser.start(request: "bitcoin:bcrt1qexample") + XCTAssertFalse(advertiser.isAdvertising) + XCTAssertNil(advertiser.servedRequest(for: UUID(), characteristic: NearbyProtocol.metaUUID)) + } + } + + func testScannerStatusTextBySources() { + XCTAssertEqual(ScannerSources(nfc: true, bluetooth: true).statusKey, "other__scan_status_qr_nfc_bluetooth") + XCTAssertEqual(ScannerSources(nfc: true, bluetooth: false).statusKey, "other__scan_status_qr_nfc") + XCTAssertEqual(ScannerSources(nfc: false, bluetooth: true).statusKey, "other__scan_status_qr_bluetooth") + XCTAssertEqual(ScannerSources(nfc: false, bluetooth: false).statusKey, "other__scan_status_qr") + } +} diff --git a/BitkitTests/OfflineSheetOverlayTests.swift b/BitkitTests/OfflineSheetOverlayTests.swift new file mode 100644 index 0000000000..374711c939 --- /dev/null +++ b/BitkitTests/OfflineSheetOverlayTests.swift @@ -0,0 +1,34 @@ +@testable import Bitkit +import SwiftUI +import XCTest + +@MainActor +final class OfflineSheetOverlayTests: XCTestCase { + private final class Box { + var isCovered: Bool? + } + + private struct Probe: View { + @Environment(\.isCoveredByOfflineSheet) private var isCovered + let box: Box + + var body: some View { + box.isCovered = isCovered + return Color.clear.frame(width: 10, height: 10) + } + } + + private func isCovered(forceShow: Bool, isEnabled: Bool) -> Bool? { + let box = Box() + let view = Probe(box: box) + .offlineSheetOverlay(title: "Send", forceShow: forceShow, isEnabled: isEnabled) + .environmentObject(NetworkMonitor()) + _ = UIHostingController(rootView: view).sizeThatFits(in: CGSize(width: 320, height: 640)) + return box.isCovered + } + + func testCoveredContentKnowsItIsCovered() { + XCTAssertEqual(isCovered(forceShow: true, isEnabled: true), true) + XCTAssertEqual(isCovered(forceShow: true, isEnabled: false), false) + } +} diff --git a/BitkitTests/PaymentNavigationHelperTests.swift b/BitkitTests/PaymentNavigationHelperTests.swift index ede550853b..82e4ef5067 100644 --- a/BitkitTests/PaymentNavigationHelperTests.swift +++ b/BitkitTests/PaymentNavigationHelperTests.swift @@ -73,10 +73,45 @@ final class PaymentNavigationHelperTests: XCTestCase { XCTAssertEqual(PaymentNavigationHelper.contactPaymentErrorDescription(error), error.localizedDescription) } + func testLockCheckTurnsFalseOnceTheAppLocks() { + let app = AppViewModel() + let isBeforeLock = app.lockCheck() + XCTAssertTrue(isBeforeLock()) + app.noteAppLocked() + XCTAssertFalse(isBeforeLock(), "Work started before the lock must drop its result") + XCTAssertTrue(app.lockCheck()()) + } + + func testQuickpayChosenBeforeALockWaitsForReview() { + let app = appWithEligibleInvoice + let session = QuickPayPaymentCoordinator.SessionID(presentationID: UUID(), sendStateGeneration: UUID(), attempt: 0) + let coordinator = QuickPayPaymentCoordinator(store: spendStore, sendBolt11: { _ in "" }, listRows: { [] }) + XCTAssertEqual(sendRoute(for: app), .quickpay) + XCTAssertTrue(SendQuickpay.startsAutomatically(app: app, sessionID: session, coordinator: coordinator)) + + // The Send sheet waits for the node, and the app locks and unlocks before the QuickPay screen appears. + app.noteAppLocked() + XCTAssertFalse(SendQuickpay.startsAutomatically(app: app, sessionID: session, coordinator: coordinator)) + + // A request routed after the unlock starts as usual. + XCTAssertEqual(sendRoute(for: app), .quickpay) + XCTAssertTrue(SendQuickpay.startsAutomatically(app: app, sessionID: session, coordinator: coordinator)) + } + func testEligibleInvoiceUsesQuickpayUnderDailyCap() { XCTAssertEqual(sendRoute(for: appWithEligibleInvoice), .quickpay) } + func testSuppressedRequestNeverChoosesQuickpay() { + let app = appWithEligibleInvoice + let scanID = UUID() + // A Bluetooth request routes with QuickPay suppressed: the payer reviews it. + app.suppressQuickPay(scanID) + XCTAssertNotEqual(sendRoute(for: app), .quickpay) + app.releaseQuickPaySuppression(scanID) + XCTAssertEqual(sendRoute(for: app), .quickpay) + } + func testSkipsQuickpayWhenDailySpendCapIsExceeded() throws { let rates = QuickPaySpendRates.live(CurrencyViewModel(currencyService: OfflineCurrencyService())) for i in 0 ..< 5 { @@ -127,6 +162,31 @@ final class PaymentNavigationHelperTests: XCTestCase { XCTAssertEqual(sendRoute(for: appWithInvoice(paymentHash: hash), coordinator: coordinator), .quickpay) } + func testRescanOfAnOpenQuickpayAfterALockStaysOnRecovery() throws { + settings.storeQuickpaySettings(enabled: false) + let hash = "aabbccdd" + let rates = QuickPaySpendRates.live(CurrencyViewModel(currencyService: OfflineCurrencyService())) + XCTAssertNotNil(try spendStore.reserveBound(paymentHash: hash, amountSats: 1000, enabled: true, thresholdUsd: 5, multiplier: 5, rates: rates)) + let coordinator = QuickPayPaymentCoordinator(store: spendStore, sendBolt11: { _ in hash }, listRows: { [] }) + let app = appWithInvoice(paymentHash: hash) + // A new Send presentation for the rescanned invoice, so a session the coordinator has not seen. + let session = QuickPayPaymentCoordinator.SessionID(presentationID: UUID(), sendStateGeneration: UUID(), attempt: 0) + XCTAssertEqual(sendRoute(for: app, coordinator: coordinator), .quickpay) + + // The app locks while the new Send sheet waits for the node. + app.noteAppLocked() + + XCTAssertTrue( + SendQuickpay.startsAutomatically(app: app, sessionID: session, coordinator: coordinator), + "The payment in progress must replay its status, not ask to pay again" + ) + settings.storeQuickpaySettings(enabled: true) + let newInvoice = appWithInvoice(paymentHash: "eeff0011") + XCTAssertEqual(sendRoute(for: newInvoice, coordinator: coordinator), .quickpay) + newInvoice.noteAppLocked() + XCTAssertFalse(SendQuickpay.startsAutomatically(app: newInvoice, sessionID: session, coordinator: coordinator)) + } + func testUsesQuickpayWhenHashIsOpenEvenIfDailyCapIsExceeded() throws { settings.storeQuickpaySettings(dailyLimitMultiplier: 1) let rates = QuickPaySpendRates.live(CurrencyViewModel(currencyService: OfflineCurrencyService())) diff --git a/BitkitTests/PosNfcFixtures.swift b/BitkitTests/PosNfcFixtures.swift new file mode 100644 index 0000000000..6770c64f20 --- /dev/null +++ b/BitkitTests/PosNfcFixtures.swift @@ -0,0 +1,17 @@ +import Foundation + +/// Requests as point-of-sale terminals present them over NFC. +/// +/// A Square Register (2nd generation) serves `lightning:` and the uppercase BOLT11 invoice from its QR code as one +/// long-format NDEF URI record with identifier code 0x00. Numo, and Square in a later release, serve the BIP 321 form +/// without an address. `squareInvoice` is a real signet invoice of the size Square serves (a 465-byte NDEF message). +enum PosNfcFixtures { + static let squareInvoice = + "LNTBS79900N1P4TZWUQD962DCH2CTJV5S9YET8D9EHGETJYP8YVSEQWFJKWUN9WDEKJMMWYPNXJ7R5W4EX2GZNW96KZUN9YPFX2E" + + "MFWD6X2U3QFERYXGRJV4NHYETNWD5K7M3QVE5HSAR4WFJJQ5M3W4SHYEFQ2FJKW6TNW3JHYGZWGEPJQUN9VAEX2UMND9HKUGRXD9" + + "U8GATJV5PP5QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSSP5PYYSJZGFPYYSJZGFPYYSJZGFPYYSJZGFPY" + + "YSJZGFPYYSJZGFPYYS9QRSGQXQ97ZVUQCQZYSKUAHP9D6GKX2H8ERFH5E9NZZ52SY0UFR2F6VGK43QEJ0ZJU7FTYQYJTQE8705R2" + + "KM9QS5NYFM3ZPR330ML3S3HWJP5D0RERD49QGT5CPUXAWEL" + static let squareUri = "lightning:\(squareInvoice)" + static let bip321Uri = "bitcoin:?lightning=\(squareInvoice)" +} diff --git a/BitkitTests/QuickPayPaymentCoordinatorTests.swift b/BitkitTests/QuickPayPaymentCoordinatorTests.swift index 84c88208ba..d1300063e3 100644 --- a/BitkitTests/QuickPayPaymentCoordinatorTests.swift +++ b/BitkitTests/QuickPayPaymentCoordinatorTests.swift @@ -172,6 +172,225 @@ final class QuickPayPaymentCoordinatorTests: XCTestCase { XCTAssertNotNil(store.record(matching: invoiceHash)) } + func testLockWhileTheInvoiceIsPreparedOpensReviewWithoutSending() async throws { + let invoiceHash = try Self.invoiceHash + var sendCount = 0 + let app = appWithInvoice + app.noteQuickPayChosen() + // The screen allowed the start; the app then locked while the invoice was prepared (for example an LNURL + // fetch), so whoever unlocks did not choose this payment. + app.noteAppLocked() + let coordinator = QuickPayPaymentCoordinator(store: store, sendBolt11: { _ in + sendCount += 1 + return invoiceHash + }, listRows: { [] }) + let outcome = await firstOutcome(from: coordinator, app: app) + guard case .confirm = outcome else { + return XCTFail("Expected the review, got \(String(describing: outcome))") + } + XCTAssertEqual(sendCount, 0) + XCTAssertNil(store.record(matching: invoiceHash)) + } + + func testLockWhileTheRailWaitsToSubmitOpensReviewWithoutSending() async throws { + let invoiceHash = try Self.invoiceHash + var sendCount = 0 + let app = appWithInvoice + app.noteQuickPayChosen() + let coordinator = QuickPayPaymentCoordinator(store: store, submit: { _, beforeSubmission in + // The app locks while the rail prepares the payment or waits for its queue. + app.noteAppLocked() + try beforeSubmission() + sendCount += 1 + return invoiceHash + }, listRows: { [] }) + let outcome = await firstOutcome(from: coordinator, app: app) + guard case .confirm = outcome else { + return XCTFail("Expected the review, got \(String(describing: outcome))") + } + XCTAssertEqual(sendCount, 0) + XCTAssertNil(store.record(matching: invoiceHash)) + } + + func testStopWrappedByTheLdkQueueOpensReviewWithoutSending() async throws { + let invoiceHash = try Self.invoiceHash + var sendCount = 0 + let app = appWithInvoice + app.noteQuickPayChosen() + let coordinator = QuickPayPaymentCoordinator(store: store, submit: { _, beforeSubmission in + app.noteAppLocked() + // The LDK send runs its check on `ServiceQueue`, which wraps what it throws. + return try await Bitkit.LightningService.submitPayment(beforeSubmission: beforeSubmission) { + sendCount += 1 + return invoiceHash + } + }, listRows: { [] }) + let outcome = await firstOutcome(from: coordinator, app: app) + guard case .confirm = outcome else { + return XCTFail("Expected the review, got \(String(describing: outcome))") + } + XCTAssertEqual(sendCount, 0) + XCTAssertNil(store.record(matching: invoiceHash)) + } + + func testLockStopOnAReattachedQuickPayOpensReviewOnTheCurrentScreen() async throws { + let invoiceHash = try Self.invoiceHash + let app = appWithInvoice + app.noteQuickPayChosen() + let session = QuickPayPaymentCoordinator.SessionID( + presentationID: UUID(), sendStateGeneration: app.sendStateGeneration, attempt: 0 + ) + let started = expectation(description: "Submission waiting") + let reviewed = expectation(description: "Current screen opens the review") + var continuation: CheckedContinuation? + func waitToSubmit() async { + await withCheckedContinuation { + continuation = $0 + started.fulfill() + } + } + let coordinator = QuickPayPaymentCoordinator(store: store, submit: { _, beforeSubmission in + await waitToSubmit() + try beforeSubmission() + return invoiceHash + }, listRows: { [] }) + defer { coordinator.detach() } + let wallet = WalletViewModel() + let currency = CurrencyViewModel(currencyService: OfflineCurrencyService()) + coordinator.pay(app: app, wallet: wallet, settings: settings, currency: currency, + presentation: presentation(onRoute: { _ in }, onConfirm: { _ in XCTFail("Retired screen must not navigate") }), + sessionID: session) + await fulfillment(of: [started], timeout: 2) + // The QuickPay screen reattaches while the payment waits to be submitted, then the app locks. + coordinator.pay(app: app, wallet: wallet, settings: settings, currency: currency, + presentation: presentation(onRoute: { _ in }, onConfirm: { _ in reviewed.fulfill() }), + sessionID: session) + app.noteAppLocked() + try XCTUnwrap(continuation).resume() + + await fulfillment(of: [reviewed], timeout: 2) + XCTAssertNil(store.record(matching: invoiceHash)) + } + + func testLockStopAfterARescanOpensReviewOnTheRescannedScreen() async throws { + let invoiceHash = try Self.invoiceHash + let app = appWithInvoice + let invoice = app.scannedLightningInvoice + app.noteQuickPayChosen() + let started = expectation(description: "Submission waiting") + let reviewed = expectation(description: "Rescanned screen opens the review") + var continuation: CheckedContinuation? + func waitToSubmit() async { + await withCheckedContinuation { + continuation = $0 + started.fulfill() + } + } + let coordinator = QuickPayPaymentCoordinator(store: store, submit: { _, beforeSubmission in + await waitToSubmit() + try beforeSubmission() + return invoiceHash + }, listRows: { [] }) + defer { coordinator.detach() } + let wallet = WalletViewModel() + let currency = CurrencyViewModel(currencyService: OfflineCurrencyService()) + let firstSession = QuickPayPaymentCoordinator.SessionID( + presentationID: UUID(), sendStateGeneration: app.sendStateGeneration, attempt: 0 + ) + coordinator.pay(app: app, wallet: wallet, settings: settings, currency: currency, + presentation: presentation(onRoute: { _ in }, onConfirm: { _ in XCTFail("Retired screen must not navigate") }), + sessionID: firstSession) + await fulfillment(of: [started], timeout: 2) + + // The payer rescans the same invoice while its payment waits: a new send attaches to the open payment. + app.resetSendState() + app.scannedLightningInvoice = invoice + app.noteQuickPayChosen() + let rescanSession = QuickPayPaymentCoordinator.SessionID( + presentationID: UUID(), sendStateGeneration: app.sendStateGeneration, attempt: 0 + ) + coordinator.pay(app: app, wallet: wallet, settings: settings, currency: currency, + presentation: presentation(onRoute: { _ in }, onConfirm: { _ in reviewed.fulfill() }), + sessionID: rescanSession) + try await Task.sleep(nanoseconds: 200_000_000) + app.noteAppLocked() + try XCTUnwrap(continuation).resume() + + await fulfillment(of: [reviewed], timeout: 2) + XCTAssertFalse(app.isQuickPayActive) + XCTAssertNil(store.record(matching: invoiceHash)) + } + + func testLockStopAfterAnotherSendTookOverLeavesItAlone() async throws { + let invoiceHash = try Self.invoiceHash + let app = appWithInvoice + app.noteQuickPayChosen() + let started = expectation(description: "Submission waiting") + let stopped = expectation(description: "Submission stopped") + var continuation: CheckedContinuation? + func waitToSubmit() async { + await withCheckedContinuation { + continuation = $0 + started.fulfill() + } + } + let coordinator = QuickPayPaymentCoordinator(store: store, submit: { _, beforeSubmission in + await waitToSubmit() + defer { stopped.fulfill() } + try beforeSubmission() + return invoiceHash + }, listRows: { [] }) + defer { coordinator.detach() } + coordinator.pay( + app: app, wallet: WalletViewModel(), settings: settings, + currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + presentation: presentation(onRoute: { _ in }, onConfirm: { _ in XCTFail("A replaced send must not navigate") }) + ) + await fulfillment(of: [started], timeout: 2) + // Another send takes over and starts its own QuickPay, then the app locks. + app.resetSendState() + app.beginQuickPay(paymentHash: "other") + app.noteAppLocked() + try XCTUnwrap(continuation).resume() + await fulfillment(of: [stopped], timeout: 2) + try await Task.sleep(nanoseconds: 200_000_000) + + XCTAssertTrue(app.isQuickPayActive, "The other send's QuickPay must stay marked") + XCTAssertNil(store.record(matching: invoiceHash)) + } + + func testRecoveryOnlyStartWhoseRecordIsGoneOpensReviewWithoutSending() async throws { + let invoiceHash = try Self.invoiceHash + var sendCount = 0 + // The screen allowed the start only because the invoice was tracked after a lock; reconciliation removed + // the record before the coordinator ran. + XCTAssertNil(store.record(matching: invoiceHash)) + let coordinator = QuickPayPaymentCoordinator(store: store, sendBolt11: { _ in + sendCount += 1 + return invoiceHash + }, listRows: { [] }) + let reviewed = expectation(description: "Falls back to review") + coordinator.pay( + app: appWithInvoice, + wallet: WalletViewModel(), + settings: settings, + currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + presentation: presentation(onRoute: { XCTFail("Unexpected route \($0)") }, onConfirm: { _ in reviewed.fulfill() }), + recoveryOnly: true + ) + await fulfillment(of: [reviewed], timeout: 2) + XCTAssertEqual(sendCount, 0) + XCTAssertNil(store.record(matching: invoiceHash)) + + // A normal start still sends. + let route = await firstRoute(sendBolt11: { [store] _ in + sendCount += 1 + store?.signalCompletion(paymentId: nil, paymentHash: invoiceHash, success: true) + return invoiceHash + }) + XCTAssertEqual(sendCount, 1, "A normal start sends; got \(String(describing: route))") + } + func testSendAfterSignalCompletionGoesToSuccess() async throws { let invoiceHash = try Self.invoiceHash let route = await firstRoute( diff --git a/BitkitTests/ReceiveNearbyOfferTests.swift b/BitkitTests/ReceiveNearbyOfferTests.swift new file mode 100644 index 0000000000..aeaf067a3d --- /dev/null +++ b/BitkitTests/ReceiveNearbyOfferTests.swift @@ -0,0 +1,31 @@ +@testable import Bitkit +import XCTest + +final class ReceiveNearbyOfferTests: XCTestCase { + func testOnlyARequestShownOnScreenIsOffered() { + XCTAssertTrue(ReceiveQr.showsRequest(needsInvoiceRefresh: false, isReceiveUnavailable: false)) + // Savings after leaving USDT: the refresh is pending or failed, so the page shows a spinner or Retry. + XCTAssertFalse(ReceiveQr.showsRequest(needsInvoiceRefresh: true, isReceiveUnavailable: false)) + XCTAssertFalse(ReceiveQr.showsRequest(needsInvoiceRefresh: false, isReceiveUnavailable: true)) + } + + func testUsdtRequestIsNotOfferedBehindTheConnectionIssuesScreen() { + let uri = "ethereum:0xabc@42161" + func offered(isCovered: Bool) -> String? { + UsdtReceiveView.nearbyRequest(receiveUri: uri, isEnabled: true, showsAddress: true, hasDeposit: false, isCovered: isCovered) + } + XCTAssertNotNil(offered(isCovered: false)) + XCTAssertNil(offered(isCovered: true)) + } + + func testRequestIsNotOfferedWhileEditCoversTheQr() { + let uri = "bitcoin:bcrt1qexample" + XCTAssertEqual(ReceiveQr.advertisedRequest(uri, isShown: true, isCovered: false, isActive: true), uri) + // Edit pushed, or a passphrase or pairing sheet presented, over the QR: the view stays mounted and still sees + // the app become active again. + XCTAssertNil(ReceiveQr.advertisedRequest(uri, isShown: false, isCovered: true, isActive: true)) + XCTAssertNil(ReceiveQr.advertisedRequest(uri, isShown: true, isCovered: true, isActive: true)) + XCTAssertNil(ReceiveQr.advertisedRequest(uri, isShown: false, isCovered: false, isActive: true)) + XCTAssertNil(ReceiveQr.advertisedRequest(uri, isShown: true, isCovered: false, isActive: false)) + } +} diff --git a/BitkitTests/ScannedPaymentRequestTests.swift b/BitkitTests/ScannedPaymentRequestTests.swift new file mode 100644 index 0000000000..c3f1011e69 --- /dev/null +++ b/BitkitTests/ScannedPaymentRequestTests.swift @@ -0,0 +1,161 @@ +@testable import Bitkit +import BitkitCore +import XCTest + +final class ScannedPaymentRequestTests: XCTestCase { + private let invoice = PosNfcFixtures.squareInvoice + + func testSquareRequestIsKept() { + XCTAssertEqual(invoice.count, 447) + XCTAssertEqual(ScannedPaymentRequest.normalized(PosNfcFixtures.squareUri), PosNfcFixtures.squareUri) + XCTAssertEqual(ScannedPaymentRequest.normalized(" LIGHTNING:LNTBS1P\n"), "LIGHTNING:LNTBS1P") + } + + func testBip321RequestWithoutAddressBecomesItsLightningRequest() { + XCTAssertEqual(ScannedPaymentRequest.normalized(PosNfcFixtures.bip321Uri), "lightning:\(invoice)") + XCTAssertEqual(ScannedPaymentRequest.normalized("BITCOIN:?LIGHTNING=\(invoice)"), "lightning:\(invoice)") + XCTAssertEqual( + ScannedPaymentRequest.normalized("bitcoin:?amount=0.0000799&lightning=\(invoice)&creq=x"), + "lightning:\(invoice)" + ) + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?lno=lno1qgsq"), "lightning:lno1qgsq") + } + + func testRequestWithRequiredParameterIsKept() { + let required = "bitcoin:?lightning=\(invoice)&req-pop=callback%3a" + XCTAssertEqual(ScannedPaymentRequest.normalized(required), required) + let uppercase = "BITCOIN:?REQ-FOO=bar&LIGHTNING=\(invoice)" + XCTAssertEqual(ScannedPaymentRequest.normalized(uppercase), uppercase) + for empty in ["bitcoin:?lightning=\(invoice)&req-foo=", "bitcoin:?lightning=\(invoice)&req-foo"] { + XCTAssertEqual(ScannedPaymentRequest.normalized(empty), empty) + } + } + + func testRequestWithARepeatedParameterIsKept() { + for repeated in [ + "bitcoin:?amount=0.01&AMOUNT=0.02&lightning=\(invoice)", + "bitcoin:?lightning=\(invoice)&amount=0.0000799&amount=0.0000799", + // Valid BIP 321, but which invoice to pay is not chosen here. + "bitcoin:?lightning=\(invoice)&lightning=\(invoice)", + "bitcoin:?amount=&amount=0.02&lightning=\(invoice)", + "bitcoin:?label=a&lightning=\(invoice)&Label=a", + "bitcoin:?message=a&message=b&lightning=\(invoice)", + "bitcoin:?pop=a%3a&pop=b%3a&lightning=\(invoice)", + ] { + XCTAssertEqual(ScannedPaymentRequest.normalized(repeated), repeated) + } + } + + func testRequestRepeatingAnOptionalExtensionIsUnwrapped() { + XCTAssertEqual( + ScannedPaymentRequest.normalized("bitcoin:?x-shop=a&lightning=\(invoice)&X-SHOP=b&amount=0.0000799"), + "lightning:\(invoice)" + ) + } + + func testRepeatedOffersBesideOneInvoiceAreSkipped() { + let offers = "lno=lno1qgsqvgnwgcg35z6ee2h3yczraddm72xrfua9uve2rlrm9deu7xyfzr&LNO=lno1pqps7sjqpgt" + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?\(offers)&lightning=\(invoice)"), "lightning:\(invoice)") + XCTAssertTrue(ScannerManager.isNearbyPaymentRequest(ScannedPaymentRequest.normalized("bitcoin:?lightning=\(invoice)&\(offers)"))) + // Offers alone are still refused over Bluetooth. + XCTAssertFalse(ScannerManager.isNearbyPaymentRequest(ScannedPaymentRequest.normalized("bitcoin:?\(offers)"))) + } + + func testScannerRejectsARepeatedParameter() async { + await assertScannerRejects("bitcoin:?amount=0.01&AMOUNT=0.02&lightning=\(invoice)") + } + + func testRequestWithAnEmptyAmountIsKept() { + for empty in ["bitcoin:?amount=&lightning=\(invoice)", "bitcoin:?lightning=\(invoice)&amount"] { + XCTAssertEqual(ScannedPaymentRequest.normalized(empty), empty) + } + } + + func testRequestWhoseAmountTheInvoiceDoesNotStateIsKept() { + XCTAssertEqual( + ScannedPaymentRequest.normalized("bitcoin:?amount=0.000799&lightning=\(invoice)"), + "bitcoin:?amount=0.000799&lightning=\(invoice)" + ) + XCTAssertEqual( + ScannedPaymentRequest.normalized("bitcoin:?amount=0.00007990&lightning=\(invoice)"), + "lightning:\(invoice)" + ) + let amountless = "lnbcrt1pjqwerty" + XCTAssertEqual( + ScannedPaymentRequest.normalized("bitcoin:?amount=0.0001&lightning=\(amountless)"), + "bitcoin:?amount=0.0001&lightning=\(amountless)" + ) + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?lightning=\(amountless)"), "lightning:\(amountless)") + XCTAssertEqual( + ScannedPaymentRequest.normalized("bitcoin:?amount=0.0025&lightning=lnbcrt2500u1pjq"), + "lightning:lnbcrt2500u1pjq" + ) + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?amount=x&lightning=\(invoice)"), "bitcoin:?amount=x&lightning=\(invoice)") + } + + func testRequestWithAMalformedAmountIsKept() { + for amount in ["0.0000799BTC", "0.0000799,50", "0.0000799.0", "-0.0000799", ".", "0x1"] { + let request = "bitcoin:?amount=\(amount)&lightning=\(invoice)" + XCTAssertEqual(ScannedPaymentRequest.normalized(request), request, amount) + } + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?amount=.0000799&lightning=\(invoice)"), "lightning:\(invoice)") + } + + func testScannerRejectsAnAmountTheInvoiceDoesNotState() async { + await assertScannerRejects("bitcoin:?amount=0.000799&lightning=\(invoice)") + } + + private func assertScannerRejects(_ request: String, file: StaticString = #filePath, line: UInt = #line) async { + do { + let decoded = try await decode(invoice: ScannedPaymentRequest.normalized(request)) + XCTFail("Decoded \(decoded)", file: file, line: line) + } catch {} + } + + func testOtherBitcoinRequestsAreKept() { + let unified = "bitcoin:bc1qtest?lightning=lnbc1" + XCTAssertEqual(ScannedPaymentRequest.normalized(unified), unified) + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?amount=0.001"), "bitcoin:?amount=0.001") + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?lightning="), "bitcoin:?lightning=") + } + + func testRequiredParameterIsFoundBehindALightningScheme() { + let request = "bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a" + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter(request)) + // The scanner strips `lightning:` before decoding, so the wrapped request is checked as a Bitcoin one. + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("lightning:\(request)")) + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("LIGHTNING:\(request)")) + for wrapped in ["bitkit://\(request)", "bitkit://lightning:\(request)", "lightning:lightning:\(request)", "lnurl:lightning:\(request)"] { + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter(wrapped), wrapped) + } + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter("lightning:bitcoin:bcrt1qtest?amount=0.001")) + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter("bitkit://bitcoin:bcrt1qtest?amount=0.001")) + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter("https://pay.example.com/lnurlp?req-x=1")) + } + + func testRequiredParameterIsFoundBehindAnInnerBitkitScheme() { + // The decoder deletes every `bitkit://` in a deep link, which can turn a key into `req-`. + let address = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("\(address)&bitkit://req-pop=callback")) + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("\(address)&rebitkit://q-pop=callback")) + // The decoder deletes only lowercase `bitkit://`, so a mixed-case one stays part of an optional key. + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter("bitkit://bitkit://bitcoin:bcrt1qtest?REBITKIT://Q-POP=callback")) + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter("\(address)&reBitkit://q-x=1")) + // The decoder deletes them again while the text starts with `bitkit://`, so a nested one is removed too. + let required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=x" + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("bitkit://bitbitkit://kit://\(required)")) + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("bitkit://lightning:bitbitkit://kit://\(required)")) + // Once the text starts with `bitcoin:` the decoder deletes nothing more, so this key is not `req-`. + let payable = "bitcoin:bcrt1qtest?amount=0.001&bitbitkit://kit://req-pop=x" + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter(payable)) + XCTAssertFalse(ScannedPaymentRequest.hasRequiredParameter("bitkit://\(payable)")) + } + + /// A combining mark right after `?` or `&` joins the delimiter into a larger `Character`; bitkit-core still splits + /// on it. + func testDelimiterFollowedByACombiningMarkStillSplitsTheQuery() { + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("bitcoin:bcrt1qtest?\u{301}&req-pop=x")) + XCTAssertTrue(ScannedPaymentRequest.hasRequiredParameter("bitcoin:bcrt1qtest?amount=0.001&\u{301}&req-pop=x")) + XCTAssertEqual(ScannedPaymentRequest.normalized("bitcoin:?lightning=\(invoice)&\u{301}"), "lightning:\(invoice)") + } +} diff --git a/BitkitTests/ScannerManagerTests.swift b/BitkitTests/ScannerManagerTests.swift index 762c1fbdf3..6c5c5c56c1 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -379,3 +379,961 @@ final class ScannerManagerTests: XCTestCase { return app } } + +// MARK: - NFC + +extension ScannerManagerTests { + func testNfcAvailabilityFollowsReader() { + let reader = FakeNfcReader(.success("")) + reader.isAvailable = false + XCTAssertFalse(ScannerManager(nfcReader: reader) {}.isNfcReadingAvailable) + reader.isAvailable = true + XCTAssertTrue(ScannerManager(nfcReader: reader) {}.isNfcReadingAvailable) + } + + func testNfcSendReadRoutesLikeAScannedQrCode() async { + var hapticCount = 0 + let reader = FakeNfcReader(.success(paymentURI)) + let scanner = ScannerManager(nfcReader: reader) { hapticCount += 1 } + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var routes: [SendRoute?] = [] + + await scanner.handleSendNfcRead { routes.append($0) } + + XCTAssertEqual(reader.alertMessages, [t("other__nfc_alert")]) + XCTAssertEqual(routes, [.amount]) + XCTAssertEqual(hapticCount, 1) + XCTAssertNotNil(app.scannedOnchainInvoice) + } + + func testNfcGenericReadRoutesLikeAScannedQrCode() async { + var hapticCount = 0 + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) { hapticCount += 1 } + let app = configure(scanner) + + await scanner.handleNfcRead(context: .send) + + XCTAssertEqual(hapticCount, 1) + XCTAssertNotNil(app.scannedOnchainInvoice) + } + + func testFailedNfcReadCompletesWithoutRoute() async { + let previousToast = ToastWindowManager.shared.currentToast + defer { ToastWindowManager.shared.currentToast = previousToast } + for error in [NfcReadError.cancelled, .timedOut, .noPaymentRequest, .multiplePaymentRequests, .unavailable] { + ToastWindowManager.shared.currentToast = nil + let scanner = ScannerManager(nfcReader: FakeNfcReader(.failure(error))) { + XCTFail("A failed NFC read must not play a success haptic") + } + let app = configure(scanner) + var routes: [SendRoute?] = [] + + await scanner.handleSendNfcRead { routes.append($0) } + + XCTAssertEqual(routes, [nil], "\(error)") + XCTAssertNil(app.scannedOnchainInvoice, "\(error)") + // The payer sees why the read failed, except when they cancelled it or it timed out. + let shown = ToastWindowManager.shared.currentToast + if error.isSilent { + XCTAssertNil(shown, "\(error)") + } else { + XCTAssertEqual(shown?.title, t("other__nfc_error_header"), "\(error)") + XCTAssertEqual(shown?.description, error.message, "\(error)") + } + } + } + + func testNfcReadErrorAfterTheScannerVisitEndsShowsNoToast() async { + let previousToast = ToastWindowManager.shared.currentToast + defer { ToastWindowManager.shared.currentToast = previousToast } + ToastWindowManager.shared.currentToast = nil + let scanner = ScannerManager(nfcReader: FakeNfcReader(.failure(.noPaymentRequest))) {} + _ = configure(scanner) + var checks = 0 + // The payer leaves the scanner, or the app locks, while the NFC sheet is up. + func isOnVisit() -> Bool { + checks += 1 + return checks == 1 + } + + await scanner.handleSendNfcRead(isCurrent: isOnVisit) { _ in } + + XCTAssertNil(ToastWindowManager.shared.currentToast, "A read that ends after its visit must not show an error") + } + + func testCameraScanFromBeforeALockDoesNotRoute() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let started = expectation(description: "Lookup suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let scan = Task { await scanner.handleScan(paymentURI, context: .main) } + await fulfillment(of: [started], timeout: 2) + + // The app locks while the lookup runs, and the payer unlocks before it returns. + scanner.invalidateScansForAppLock() + try XCTUnwrap(continuation).resume(returning: decoded) + await scan.value + + XCTAssertNil(app.scannedOnchainInvoice, "A scan from before the lock must not open Send after the unlock") + } + + func testSendScanFromBeforeALockDoesNotRoute() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let started = expectation(description: "Lookup suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var routes: [SendRoute?] = [] + func record(_ route: SendRoute?) { + routes.append(route) + } + let scan = Task { await scanner.handleSendScan(paymentURI, completion: record) } + await fulfillment(of: [started], timeout: 2) + + scanner.invalidateScansForAppLock() + try XCTUnwrap(continuation).resume(returning: decoded) + await scan.value + + XCTAssertTrue(routes.allSatisfy { $0 == nil }, "A scan from before the lock must not route after the unlock") + XCTAssertNil(app.scannedOnchainInvoice) + } + + func testNearbyRequestWithARequiredParameterIsRefused() async { + let required = "\(paymentURI)?amount=0.001&REQ-POP=callback%3a" + XCTAssertFalse(ScannerManager.isNearbyPaymentRequest(required)) + XCTAssertFalse(ScannerManager.isNearbyPaymentRequest("\(paymentURI)?\u{301}&req-pop=callback%3a")) + XCTAssertTrue(ScannerManager.isNearbyPaymentRequest("\(paymentURI)?amount=0.001&pop=callback%3a")) + + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(required))) { + XCTFail("An NFC request with a required parameter must not play a success haptic") + } + let app = configure(scanner) + var routes: [SendRoute?] = [] + await scanner.handleSendNfcRead { routes.append($0) } + XCTAssertEqual(routes, [nil]) + XCTAssertNil(app.scannedOnchainInvoice) + } + + func testNearbyRequestRoutesWithQuickPaySuppressed() async { + var hapticCount = 0 + let scanner = ScannerManager { hapticCount += 1 } + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var suppressedAtRoute: [Bool] = [] + var routes: [SendRoute?] = [] + + await scanner.handleSendNearbyRequest(paymentURI) { route in + routes.append(route) + suppressedAtRoute.append(app.isQuickPaySuppressed) + } + + XCTAssertEqual(routes, [.amount]) + XCTAssertEqual(suppressedAtRoute, [true]) + XCTAssertFalse(app.isQuickPaySuppressed) + XCTAssertEqual(hapticCount, 1) + } + + func testNearbyAllowlistAcceptsPaymentSchemesOnly() { + let invoice = PosNfcFixtures.squareInvoice + for uri in ["bitcoin:bcrt1qexample", "BITCOIN:BCRT1Q", "lightning:\(invoice)", "lightning:\(invoice.lowercased())", + "ethereum:0xabc@42161", " bitcoin:bcrt1q?lightning=\(invoice) ", "bitcoin:bcrt1q?amount=0.1&label=lightning", + "lightning:\(ChannelFreeRailTests.invoice)", PosNfcFixtures.squareUri, PosNfcFixtures.bip321Uri] + { + XCTAssertTrue(ScannerManager.isNearbyPaymentRequest(uri), uri) + } + for uri in authURIs + nearbyNetworkLookups + ["lnurlw://example.com/w", "lnurlc://example.com/c", "LNURL1DP68GURN8GHJ7", + "lightning:lno1qgsqvgnwgcg35z6ee2h3yczraddm72xrfua9uve2rlrm9deu7xyfzr", + "bcrt1qexample", + "lnbcrt10u1pjexample", "lightning:lnbcrt1", "lightning:lnsb1qqqqqq", + "lightning:\(PosNfcFixtures.squareInvoice.dropLast())x", + "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw374y", + "https://example.com", "bitkit://contact/abc", "02aaaa@127.0.0.1:9735", ""] + { + XCTAssertFalse(ScannerManager.isNearbyPaymentRequest(uri), uri) + } + } + + /// Requests the decoder would resolve over the network before the user picked them. + private var nearbyNetworkLookups: [String] { + [ + "LIGHTNING:LNURL1DP68GURN8GHJ7", "lnurlp://example.com/pay", "lightning:alice@example.com", + "bitcoin:bcrt1q?amount=0.1&lightning=LNURL1DP68GURN8GHJ7", "bitcoin:?lightning=lnurl1dp68gurn8ghj7", + "lightning:lnsb@example.com", "bitcoin:?lightning=lnsb@example.com", "bitcoin:bcrt1q?lightning=lnsb@example.com", + "lightning:lnbc@example.com", "bitcoin:bcrt1q?lightning=lntb1@example.com", + // A combining mark after `?` or `&` hides the delimiter from a `Character` split, not from the decoder. + "bitcoin:?\u{301}&lightning=alice@example.com", "bitcoin:bcrt1q?amount=0.1&\u{301}&lightning=LNURL1DP68GURN8GHJ7", + // Each repeated Lightning value is checked, since the decoder takes the last one. + "bitcoin:bcrt1q?lightning=\(PosNfcFixtures.squareInvoice)&lightning=LNURL1DP68GURN8GHJ7", + ] + } + + func testNearbyRequestDoesNotResolveAnLnurlBeforeReview() async { + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { uri in + XCTFail("Bluetooth discovery alone must not decode \(uri)") + return .gift(code: "gift-code", amount: 1000) + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + + for uri in nearbyNetworkLookups { + let sendWasTaken = await scanner.handleSendNearbyRequest(uri) { XCTAssertNil($0, uri) } + let mainWasTaken = await scanner.handleNearbyRequest(uri, context: .main) + XCTAssertFalse(sendWasTaken, uri) + XCTAssertFalse(mainWasTaken, uri) + } + } + + func testNearbyRequestRefusesNonPaymentPayloads() async { + let scanner = ScannerManager { XCTFail("A refused Bluetooth payload must not play a success haptic") } + let app = configure(scanner) + var routes: [SendRoute?] = [] + + for uri in authURIs + ["lnurlw://example.com/withdraw", "bitkit://contact/abc"] { + let wasTaken = await scanner.handleSendNearbyRequest(uri) { routes.append($0) } + XCTAssertFalse(wasTaken, uri) + } + let mainWasTaken = await scanner.handleNearbyRequest("pubkyauth://signin", context: .main) + + XCTAssertFalse(mainWasTaken) + XCTAssertEqual(routes, Array(repeating: nil, count: authURIs.count + 2)) + XCTAssertNil(app.scannedOnchainInvoice) + } + + func testNearbyRequestRefusesDecodedNonPaymentTypes() async { + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in .gift(code: "gift-code", amount: 1000) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var routes: [SendRoute?] = [] + + let wasTaken = await scanner.handleSendNearbyRequest("lightning:\(PosNfcFixtures.squareInvoice)") { routes.append($0) } + + XCTAssertFalse(wasTaken) + XCTAssertEqual(routes, [nil]) + } + + func testNearbyRequestCannotRouteAfterItsScannerCloses() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let started = expectation(description: "Nearby request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var routes: [SendRoute?] = [] + let task = Task { await scanner.handleSendNearbyRequest(paymentURI) { routes.append($0) } } + + await fulfillment(of: [started], timeout: 2) + sheets.hideSheet(reason: "User left the scanner during a nearby request") + try XCTUnwrap(continuation).resume(returning: decoded) + let wasTaken = await task.value + + XCTAssertFalse(wasTaken) + XCTAssertTrue(routes.isEmpty) + XCTAssertNil(app.scannedOnchainInvoice) + } + + func testNearbyRequestCannotRouteAfterTheSendSheetMovesOn() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let started = expectation(description: "Nearby request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var navigationPath: [SendRoute] = [] + var routes: [SendRoute?] = [] + let task = Task { + await scanner.handleSendNearbyRequest(paymentURI, isCurrent: { navigationPath.isEmpty }) { routes.append($0) } + } + + await fulfillment(of: [started], timeout: 2) + navigationPath.append(.manual) + try XCTUnwrap(continuation).resume(returning: decoded) + let wasTaken = await task.value + + XCTAssertFalse(wasTaken) + XCTAssertTrue(routes.isEmpty) + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .send) + } + + func testNfcReadCannotRouteAfterItsSendSheetCloses() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let started = expectation(description: "NFC request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var routes: [SendRoute?] = [] + let task = Task { await scanner.handleSendNfcRead { routes.append($0) } } + + await fulfillment(of: [started], timeout: 2) + sheets.hideSheet(reason: "User left the Send sheet during an NFC request") + try XCTUnwrap(continuation).resume(returning: decoded) + await task.value + + XCTAssertTrue(routes.allSatisfy { $0 == nil }) + XCTAssertNil(app.scannedOnchainInvoice) + } + + func testNfcReadCannotRouteAfterTheAppLocks() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let started = expectation(description: "NFC request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var routes: [SendRoute?] = [] + let task = Task { await scanner.handleSendNfcRead { routes.append($0) } } + + await fulfillment(of: [started], timeout: 2) + // The payer leaves the app mid-decode, and it locks behind the PIN with the Send sheet still set. + scanner.invalidateScansForAppLock() + try XCTUnwrap(continuation).resume(returning: decoded) + await task.value + + XCTAssertTrue(routes.allSatisfy { $0 == nil }) + XCTAssertNil(app.scannedOnchainInvoice) + } + + func testMainScannerRouteDoesNotOpenOnceTheAppLocks() async throws { + func routeFromTheScanner(lockingBeforeTheSheetOpens: Bool) async throws -> SheetConfiguration? { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + await scanner.handleNearbyRequest(paymentURI, context: .main) + // The scanner sheet is closing; the payment sheet opens after the replacement delay. + XCTAssertNil(sheets.activeSheetConfiguration) + if lockingBeforeTheSheetOpens { + scanner.invalidateScansForAppLock() + } + try await Task.sleep(nanoseconds: UInt64((SheetViewModel.replacementDelaySeconds + 0.3) * 1_000_000_000)) + return sheets.activeSheetConfiguration + } + + let unlocked = try await routeFromTheScanner(lockingBeforeTheSheetOpens: false) + XCTAssertNotNil(unlocked, "Without a lock the request opens its payment sheet") + let locked = try await routeFromTheScanner(lockingBeforeTheSheetOpens: true) + XCTAssertNil(locked, "A request routed just before the lock must not open after it") + } + + func testASheetThatReplacedTheScannerDuringADecodeSurvivesALock() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let started = expectation(description: "Nearby request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let task = Task { await scanner.handleNearbyRequest(paymentURI, context: .main) } + await fulfillment(of: [started], timeout: 2) + + // A received payment replaces the scanner while the request decodes; the request then routes nothing. + sheets.showSheet(.receivedTx) + try XCTUnwrap(continuation).resume(returning: decoded) + _ = await task.value + scanner.invalidateScansForAppLock() + try await Task.sleep(nanoseconds: UInt64((SheetViewModel.replacementDelaySeconds + 0.3) * 1_000_000_000)) + + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .receivedTx, "A lock must cancel only the scan's own route") + } + + func testNfcReadCannotRouteAfterTheSendSheetMovesOn() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let started = expectation(description: "NFC request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var navigationPath: [SendRoute] = [] + var routes: [SendRoute?] = [] + let task = Task { + await scanner.handleSendNfcRead(isCurrent: { navigationPath.isEmpty }) { routes.append($0) } + } + + await fulfillment(of: [started], timeout: 2) + navigationPath.append(.manual) + try XCTUnwrap(continuation).resume(returning: decoded) + await task.value + + XCTAssertTrue(routes.allSatisfy { $0 == nil }) + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .send) + } + + func testNfcReadCannotRouteAfterLeavingAndReturningToTheScanner() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let navigation = NavigationViewModel() + let started = expectation(description: "NFC request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, navigation: navigation, sheets: sheets + ) + sheets.showSheet(.scanner) + let task = Task { await scanner.handleNfcRead(context: .main) } + + await fulfillment(of: [started], timeout: 2) + navigation.path.append(.savingsWallet) + navigation.path.removeLast() + try XCTUnwrap(continuation).resume(returning: decoded) + await task.value + + XCTAssertTrue(navigation.path.isEmpty) + XCTAssertNil(app.scannedOnchainInvoice, "A read from an earlier visit must not route") + } + + func testRefusedNearbyRequestOnMainScannerIsNotTaken() async { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let expired = LightningInvoice( + bolt11: "lnbcrt1expired", + paymentHash: Data(repeating: 1, count: 32), + amountSatoshis: 1000, + timestampSeconds: 0, + expirySeconds: 0, + isExpired: true, + description: nil, + networkType: .regtest, + payeeNodeId: nil + ) + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in .lightning(invoice: expired) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + + let wasTaken = await scanner.handleNearbyRequest("lightning:\(PosNfcFixtures.squareInvoice)", context: .main) + + XCTAssertFalse(wasTaken) + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .scanner) + } + + func testNearbyRequestReportsTakenWhenItRoutes() async { + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + + let wasTaken = await scanner.handleSendNearbyRequest(paymentURI) { _ in } + + XCTAssertTrue(wasTaken) + } + + func testUserScanTakesOverFromADecodingNearbyRequest() async throws { + let decoded = try await decode(invoice: paymentURI) + let nearbyURI = "bitcoin:bcrt1qnearbyrequest" + let sheets = SheetViewModel() + let started = expectation(description: "Nearby request decoding suspended") + var continuation: CheckedContinuation? + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { input in + guard input.contains("nearbyrequest") else { return decoded } + return try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var nearbyRoutes: [SendRoute?] = [] + let task = Task { + await scanner.handleSendNearbyRequest(nearbyURI) { nearbyRoutes.append($0) } + } + await fulfillment(of: [started], timeout: 2) + + var routes: [SendRoute?] = [] + var suppressedAtUserRoute: [Bool] = [] + await scanner.handleSendNfcRead { route in + routes.append(route) + suppressedAtUserRoute.append(app.isQuickPaySuppressed) + } + try XCTUnwrap(continuation).resume(returning: decoded) + let wasTaken = await task.value + + XCTAssertEqual(routes, [.amount]) + XCTAssertEqual(suppressedAtUserRoute, [false], "QuickPay must apply to the user's own read") + XCTAssertFalse(wasTaken) + XCTAssertTrue(nearbyRoutes.allSatisfy { $0 == nil }) + XCTAssertFalse(app.isQuickPaySuppressed) + + // The lock is free again for the next read. + var nextRoutes: [SendRoute?] = [] + await scanner.handleSendScan(paymentURI) { nextRoutes.append($0) } + XCTAssertEqual(nextRoutes, [.amount]) + } + + func testNearbyRequestWaitsForASelectedPhoto() async throws { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let started = expectation(description: "Photo loading suspended") + var continuation: CheckedContinuation? + func loadPhoto() async throws -> QRCodePayload { + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + } + let photo = Task { await scanner.handleImageScan(context: .main, decode: loadPhoto) } + await fulfillment(of: [started], timeout: 2) + + let nearbyURI = "bitcoin:bcrt1q59y53uy2h02dlqn76n824ns3maupd3mx4lfm0y" + let wasTaken = await scanner.handleNearbyRequest(nearbyURI, context: .main) + XCTAssertFalse(wasTaken, "A nearby request must not open while the selected photo loads") + + try XCTUnwrap(continuation).resume(returning: QRCodePayload(string: paymentURI, data: nil)) + await photo.value + XCTAssertEqual(app.scannedOnchainInvoice?.address, "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + } + + func testPhotoTakesOverABluetoothRequestAlreadyDecoding() async throws { + let nearbyURI = "bitcoin:bcrt1q59y53uy2h02dlqn76n824ns3maupd3mx4lfm0y" + let nearbyDecoded = try await decode(invoice: nearbyURI) + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let nearbyStarted = expectation(description: "Bluetooth request decoding suspended") + var nearbyContinuation: CheckedContinuation? + let app = configure(scanner, sheets: sheets, decodeInvoice: { input in + guard input.contains("59y53uy2") else { return try await decode(invoice: input) } + return try await withCheckedThrowingContinuation { + nearbyContinuation = $0 + nearbyStarted.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let nearby = Task { await scanner.handleNearbyRequest(nearbyURI, context: .main) } + await fulfillment(of: [nearbyStarted], timeout: 2) + + let photoStarted = expectation(description: "Photo loading suspended") + var photoContinuation: CheckedContinuation? + func loadPhoto() async throws -> QRCodePayload { + try await withCheckedThrowingContinuation { + photoContinuation = $0 + photoStarted.fulfill() + } + } + let photo = Task { await scanner.handleImageScan(context: .main, decode: loadPhoto) } + await fulfillment(of: [photoStarted], timeout: 2) + + // The Bluetooth request finishes decoding while the photo still loads. + try XCTUnwrap(nearbyContinuation).resume(returning: nearbyDecoded) + let wasTaken = await nearby.value + XCTAssertFalse(wasTaken, "The picked photo takes over a Bluetooth request still decoding") + + try XCTUnwrap(photoContinuation).resume(returning: QRCodePayload(string: paymentURI, data: nil)) + await photo.value + XCTAssertEqual(app.scannedOnchainInvoice?.address, "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + } + + func testPhotoStillLoadingFromAClosedScannerDoesNotHoldTheNextOne() async throws { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let started = expectation(description: "Photo loading suspended") + var continuation: CheckedContinuation? + func loadPhoto() async throws -> QRCodePayload { + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + } + let photo = Task { await scanner.handleImageScan(context: .main, decode: loadPhoto) } + await fulfillment(of: [started], timeout: 2) + + // The user closes that scanner and opens it again; the old photo is still loading. + sheets.hideSheet() + sheets.showSheet(.scanner) + let wasTaken = await scanner.handleNearbyRequest(paymentURI, context: .main) + XCTAssertTrue(wasTaken, "A photo from a closed scanner must not hold Bluetooth on the next visit") + + try XCTUnwrap(continuation).resume(returning: QRCodePayload(string: paymentURI, data: nil)) + await photo.value + } + + func testPhotoFromAnEarlierSendOptionsVisitNeitherHoldsNorRoutes() async throws { + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var isOnFirstVisit = true + let started = expectation(description: "Photo loading suspended") + var continuation: CheckedContinuation? + func loadPhoto() async throws -> QRCodePayload { + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + } + var photoRoutes: [SendRoute?] = [] + func isOnVisit() -> Bool { + isOnFirstVisit + } + func record(_ route: SendRoute?) { + photoRoutes.append(route) + } + let photo = Task { await scanner.handleImageScan(context: .send, isCurrent: isOnVisit, decode: loadPhoto, completion: record) } + await fulfillment(of: [started], timeout: 2) + + // Enter Manually and Back: the sheet stays open, but Send Options starts a new scanner visit. + isOnFirstVisit = false + let wasTaken = await scanner.handleSendNearbyRequest(paymentURI) { _ in } + XCTAssertTrue(wasTaken, "A photo from an earlier Send Options visit must not hold Bluetooth") + + try XCTUnwrap(continuation).resume(returning: QRCodePayload(string: paymentURI, data: nil)) + await photo.value + XCTAssertTrue(photoRoutes.allSatisfy { $0 == nil }, "The earlier visit's photo must not route") + } + + func testPhotoFromAnEarlierFullScreenScannerVisitDoesNotRoute() async throws { + let navigation = NavigationViewModel() + navigation.path = [.scanner] + let scanner = ScannerManager {} + let app = configure(scanner) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, navigation: navigation, sheets: SheetViewModel() + ) + let started = expectation(description: "Photo loading suspended") + var continuation: CheckedContinuation? + func loadPhoto() async throws -> QRCodePayload { + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + } + let photo = Task { await scanner.handleImageScan(context: .main, decode: loadPhoto) } + await fulfillment(of: [started], timeout: 2) + + // The user leaves the scanner and opens it again: the same path, but a new visit. + navigation.path = [] + navigation.path = [.scanner] + + try XCTUnwrap(continuation).resume(returning: QRCodePayload(string: paymentURI, data: nil)) + await photo.value + XCTAssertNil(app.scannedOnchainInvoice, "The earlier visit's photo must not open its payment") + } + + func testBluetoothWaitsForEveryPickedPhoto() async throws { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let started = expectation(description: "First photo loading suspended") + var continuation: CheckedContinuation? + func loadSlowPhoto() async throws -> QRCodePayload { + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + } + func loadPhotoWithoutQrCode() async throws -> QRCodePayload { + throw QRCodeImageDecoderError.noQRCode + } + let slowPhoto = Task { await scanner.handleImageScan(context: .main, decode: loadSlowPhoto) } + await fulfillment(of: [started], timeout: 2) + + // A second photo finishes first; the first one is still loading. + await scanner.handleImageScan(context: .main, decode: loadPhotoWithoutQrCode) + let nearbyURI = "bitcoin:bcrt1q59y53uy2h02dlqn76n824ns3maupd3mx4lfm0y" + let wasTaken = await scanner.handleNearbyRequest(nearbyURI, context: .main) + XCTAssertFalse(wasTaken, "Bluetooth must wait while any picked photo still loads") + + try XCTUnwrap(continuation).resume(returning: QRCodePayload(string: paymentURI, data: nil)) + await slowPhoto.value + XCTAssertEqual(app.scannedOnchainInvoice?.address, "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + } + + func testPhotoWithoutAQrCodeReleasesNearbyRequests() async { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + func loadPhoto() async throws -> QRCodePayload { + throw QRCodeImageDecoderError.noQRCode + } + await scanner.handleImageScan(context: .main, decode: loadPhoto) + + let wasTaken = await scanner.handleNearbyRequest(paymentURI, context: .main) + XCTAssertTrue(wasTaken) + } + + func testNodeSetupScannerDoesNotReadNearbyRequests() { + XCTAssertTrue(ScannerScreen.readsNearby(context: .main, path: [.scanner])) + XCTAssertFalse(ScannerScreen.readsNearby(context: .main, path: [.fundManual(nodeUri: nil), .scanner])) + XCTAssertFalse(ScannerScreen.readsNearby(context: .electrum, path: [.electrumSettings, .scanner])) + } + + func testMainScannerQrTakesOverFromADecodingNearbyRequest() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let started = expectation(description: "Nearby request decoding suspended") + var continuation: CheckedContinuation? + var decodedInputs: [String] = [] + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { input in + decodedInputs.append(input) + guard input.contains("nearbyrequest") else { return decoded } + return try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + let task = Task { + await scanner.handleNearbyRequest("bitcoin:bcrt1qnearbyrequest", context: .main) + } + await fulfillment(of: [started], timeout: 2) + + await scanner.handleScan(paymentURI, context: .main) + try XCTUnwrap(continuation).resume(returning: decoded) + let wasTaken = await task.value + + XCTAssertFalse(wasTaken) + XCTAssertEqual(decodedInputs.count, 2, "The QR code must be decoded while the nearby request is pending") + XCTAssertNotNil(app.scannedOnchainInvoice) + } + + func testBluetoothRequestCannotRouteWhileAnNfcReadIsOpen() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let reader = HeldNfcReader() + let scanner = ScannerManager(nfcReader: reader) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { _ in decoded }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var nfcRoutes: [SendRoute?] = [] + let nfcTask = Task { await scanner.handleSendNfcRead { nfcRoutes.append($0) } } + await fulfillment(of: [reader.started], timeout: 2) + + var nearbyRoutes: [SendRoute?] = [] + let wasTaken = await scanner.handleSendNearbyRequest("bitcoin:bcrt1qnearbyrequest") { nearbyRoutes.append($0) } + reader.finish(.success(paymentURI)) + await nfcTask.value + + XCTAssertFalse(wasTaken, "The Bluetooth request must wait for the open NFC read") + XCTAssertTrue(nearbyRoutes.allSatisfy { $0 == nil }) + XCTAssertEqual(nfcRoutes, [.amount]) + } + + func testFailedNfcReadReleasesTheScanLock() async { + let sheets = SheetViewModel() + sheets.showSheet(.send, data: SendConfig(view: .options)) + let scanner = ScannerManager(nfcReader: FakeNfcReader(.failure(.cancelled))) {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + var nfcRoutes: [SendRoute?] = [] + await scanner.handleSendNfcRead { nfcRoutes.append($0) } + + let wasTaken = await scanner.handleSendNearbyRequest(paymentURI) { _ in } + + XCTAssertEqual(nfcRoutes, [nil]) + XCTAssertTrue(wasTaken) + } + + func testNfcErrorMessages() { + XCTAssertEqual(NfcReadError.noPaymentRequest.message, t("other__nfc_error_text")) + XCTAssertEqual(NfcReadError.multiplePaymentRequests.message, t("other__nfc_error_multiple")) + XCTAssertEqual(NfcReadError.unavailable.message, t("other__nfc_error_unavailable")) + XCTAssertEqual(NfcReadError.failed("Tag connection lost").message, t("other__nfc_error_read_failed")) + } + + func testCancelledAndTimedOutNfcReadsAreSilent() { + XCTAssertTrue(NfcReadError.cancelled.isSilent) + XCTAssertTrue(NfcReadError.timedOut.isSilent) + XCTAssertFalse(NfcReadError.noPaymentRequest.isSilent) + XCTAssertFalse(NfcReadError.failed("x").isSilent) + } +} + +@MainActor +private final class FakeNfcReader: NfcPaymentReading { + var isAvailable = true + private let result: Result + private(set) var alertMessages: [String] = [] + + init(_ result: Result) { + self.result = result + } + + func readPaymentRequest(alertMessage: String) async throws -> String { + alertMessages.append(alertMessage) + return try result.get() + } +} + +/// Holds the NFC read open until the test finishes it, like the system NFC sheet waiting for a tag. +@MainActor +private final class HeldNfcReader: NfcPaymentReading { + var isAvailable = true + let started = XCTestExpectation(description: "NFC read open") + private var continuation: CheckedContinuation? + + func readPaymentRequest(alertMessage _: String) async throws -> String { + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + } + + func finish(_ result: Result) { + continuation?.resume(with: result) + continuation = nil + } +} diff --git a/Docs/nearby-payments.md b/Docs/nearby-payments.md new file mode 100644 index 0000000000..f91d6f7f77 --- /dev/null +++ b/Docs/nearby-payments.md @@ -0,0 +1,53 @@ +# Nearby payments (NFC and Bluetooth) + +Bitkit offers the payment request shown on the Receive screen to nearby phones, and its payment +scanners read requests from nearby phones and payment terminals. Both platforms implement the same +formats so Android and iOS interoperate. + +## NFC + +| Role | Android | iOS | +| --- | --- | --- | +| Read a tag (pay) | Reader mode while a payment scanner is open; `NDEF_DISCOVERED` when the app is closed | Core NFC NDEF session, started from the scanner | +| Be read (receive) | Host card emulation of an NFC Forum Type 4 tag while Receive is in the foreground | Not possible: Apple limits card emulation to licensed payment providers | + +- Tag content: one NDEF message with a single well-known URI record (`U`, identifier code `0x00`). + The URI is the Receive request with a scheme: `bitcoin:…` (BIP21, including `lightning=`), + `lightning:`, or the USDT `ethereum:` (EIP-681) request. +- Readers accept URI, Text (`T`) and absolute-URI records, and use the single distinct value found. +- Type 4 tag: NDEF application AID `D2760000850101`, capability container `E103`, NDEF file `E104`, + read-only. The emulated tag answers only while the Receive screen is in the foreground. +- Compatible tags and terminals: static `lightning:`/`bitcoin:`/LNURL tags, Numo and ZEUS tap-to-pay, + and (inferred, unverified) Square Register 2nd generation. Bolt Card terminals, which read an + `lnurlw` card, are not supported. + +## Bluetooth LE (v1) + +| Role | Android | iOS | +| --- | --- | --- | +| Read a request (pay) | GATT client while a payment scanner is open | CoreBluetooth central while a payment scanner is open | +| Serve a request (receive) | GATT server and advertiser while Receive is in the foreground | CoreBluetooth peripheral while Receive is in the foreground | + +Android and iOS interoperate in both directions; the iOS simulator has no Bluetooth, so iOS needs a device. + +The receiving phone is a GATT server; the paying phone is a central that connects to the closest +advertiser and reads the request. + +- Service UUID: `CB0E128B-1CA5-4959-94DF-A4FE588E3E98`, advertised alone, without a device name. +- Characteristics, all read-only: + - `69A713E5-B0A7-42F1-8B7F-FA0BDA119C00` (meta): 3 bytes, protocol version `0x01` then the + request length in bytes, unsigned 16-bit big-endian. + - `69A713E5-B0A7-42F1-8B7F-FA0BDA119C01` to `…9C08` (data 0 to 7): the UTF-8 request split into + chunks of 512 bytes; chunk `i` is bytes `[512 * i, 512 * (i + 1))`. Unused chunks are empty. + Reads honour the ATT read offset, so long reads return the whole chunk. +- Maximum request size: 4096 bytes. +- The request is the same URI as the NFC tag. +- Advertising runs only while the Receive screen is in the foreground and the nearby setting is on. +- Central: scans for the service UUID while a payment scanner is open, connects to the strongest + advertiser at or above -60 dBm, reads meta and the needed chunks, then disconnects. +- A request received over Bluetooth always opens the normal send review; QuickPay does not apply, + because Bluetooth range lets a device that is not the merchant's answer. +- Only `bitcoin:`, `lightning:` BOLT11 and USDT `ethereum:` requests are taken over Bluetooth. LNURL and + Lightning addresses (also as a unified URI's `lightning` part) are refused, since decoding them contacts + their server before the user picked the request. BOLT12 offers are refused because the decoder does not + read them. diff --git a/changelog.d/next/1178.added.md b/changelog.d/next/1178.added.md new file mode 100644 index 0000000000..95c74a3df3 --- /dev/null +++ b/changelog.d/next/1178.added.md @@ -0,0 +1 @@ +Bitkit can now pay and get paid by nearby phones: tap the NFC pill in the scanner to read a payment terminal or phone over NFC, and phones nearby can read your Receive request over Bluetooth (turn this off under Security > Nearby payments).