diff --git a/Bitkit/Managers/ScannerManager.swift b/Bitkit/Managers/ScannerManager.swift index ac6df7af6..798043416 100644 --- a/Bitkit/Managers/ScannerManager.swift +++ b/Bitkit/Managers/ScannerManager.swift @@ -21,7 +21,21 @@ class ScannerManager: ObservableObject { private var wallet: WalletViewModel? private weak var hwWalletManager: HwWalletManager? private let nfcReader: NfcPaymentReading - private var isHandlingScan = false + /// The scan holding the scan lock. A main or Send scan holds it only while its scanner visit lasts, so a scan still + /// waiting on a lookup (e.g. an LNURL fetch) after the user left the scanner does not block a scan on the next + /// visit. An Electrum or Add Contact scan holds it until it finishes. + private var scanOwner: ScanOwner? + + private struct ScanOwner { + let id: UUID + /// True while the scanner visit the scan started in is still shown. + let isOnVisit: () -> Bool + } + + private var isHandlingScan: Bool { + scanOwner?.isOnVisit() == true + } + /// 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] = [:] @@ -39,6 +53,10 @@ class ScannerManager: ObservableObject { /// 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? + typealias ElectrumScanResult = (success: Bool, host: String, port: String, errorMessage: String?) + /// Connects to the Electrum server a scan names. Replaceable in tests. + var electrumScan: (SettingsViewModel, String) async -> ElectrumScanResult? = { await $0.onElectrumScan($1) } + init( nfcReader: NfcPaymentReading? = nil, playScanSuccess: @escaping () -> Void = { Haptics.play(.scanSuccess) } @@ -74,13 +92,18 @@ class ScannerManager: ObservableObject { self.hwWalletManager = hwWalletManager } - func handleScan(_ uri: String, context: ScannerContext, isCurrent: () -> Bool = { true }) async { - guard isCurrent(), beginUserScan() else { return } - defer { isHandlingScan = false } + func handleScan(_ uri: String, context: ScannerContext, isCurrent: @escaping () -> Bool = { true }) async { + // A lookup can outlast the scanner visit or a PIN lock; its result must not route, or choose QuickPay, after + // the user left the scanner or unlocked. The origin check covers both. + let isCurrentOrigin = originCheck() + let isOnVisit = { isCurrent() && isCurrentOrigin() } + // Electrum and contact scans act on the screen under the scanner (they update settings and pop the scanner) + // whatever visit is shown when they finish, so they keep the lock until they finish. + let holdsUntilDone = context != .main && context != .send + guard isOnVisit(), let scanID = beginUserScan(isOnVisit: holdsUntilDone ? { true } : isOnVisit) else { return } + defer { endUserScan(scanID) } - // 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() }) + await processScan(uri, context: context, isCurrent: { [weak self] in isOnVisit() && self?.owns(scanID) == true }) } private func processScan( @@ -107,7 +130,7 @@ class ScannerManager: ObservableObject { } } - func handleScan(_ payload: QRCodePayload, context: ScannerContext, isCurrent: () -> Bool = { true }) async { + func handleScan(_ payload: QRCodePayload, context: ScannerContext, isCurrent: @escaping () -> Bool = { true }) async { guard let uri = payload.string else { showUnsupportedQRCodeError() return @@ -216,14 +239,20 @@ class ScannerManager: ObservableObject { func handleSendScan( _ uri: String, scope: ScanHandlingScope = .unrestricted, - isCurrent: () -> Bool = { true }, + isCurrent: @escaping () -> Bool = { true }, completion: @escaping (SendRoute?) -> Void ) async { - guard isCurrent(), beginUserScan() else { return } - defer { isHandlingScan = false } + let isCurrentOrigin = originCheck() + let isOnVisit = { isCurrent() && isCurrentOrigin() } + guard isOnVisit(), let scanID = beginUserScan(isOnVisit: isOnVisit) else { return } + defer { endUserScan(scanID) } - let isBeforeLock = lockCheck() - await processSendScan(uri, scope: scope, isCurrent: { isCurrent() && isBeforeLock() }, completion: completion) + await processSendScan( + uri, + scope: scope, + isCurrent: { [weak self] in isOnVisit() && self?.owns(scanID) == true }, + completion: completion + ) } private func processSendScan( @@ -301,7 +330,7 @@ class ScannerManager: ObservableObject { func handleSendScan( _ payload: QRCodePayload, scope: ScanHandlingScope = .unrestricted, - isCurrent: () -> Bool = { true }, + isCurrent: @escaping () -> Bool = { true }, completion: @escaping (SendRoute?) -> Void ) async { guard let uri = payload.string else { @@ -314,13 +343,14 @@ class ScannerManager: ObservableObject { /// 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 { + func handleNfcRead(context: ScannerContext, isCurrent: @escaping () -> Bool = { true }) async { let isCurrentOrigin = originCheck() + let isOnVisit = { isCurrent() && isCurrentOrigin() } + guard isOnVisit(), let scanID = beginUserScan(isOnVisit: isOnVisit) else { return } + defer { endUserScan(scanID) } func isStillCurrent() -> Bool { - isCurrent() && isCurrentOrigin() + isOnVisit() && owns(scanID) } - 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) } @@ -328,18 +358,19 @@ class ScannerManager: ObservableObject { /// 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 }, + isCurrent: @escaping () -> Bool = { true }, completion: @escaping (SendRoute?) -> Void ) async { let isCurrentOrigin = originCheck() - func isStillCurrent() -> Bool { - isCurrent() && isCurrentOrigin() - } - guard isStillCurrent(), beginUserScan() else { + let isOnVisit = { isCurrent() && isCurrentOrigin() } + guard isOnVisit(), let scanID = beginUserScan(isOnVisit: isOnVisit) else { completion(nil) return } - defer { isHandlingScan = false } + defer { endUserScan(scanID) } + func isStillCurrent() -> Bool { + isOnVisit() && owns(scanID) + } guard let uri = await readNfcPaymentRequest(isCurrent: isStillCurrent), isStillCurrent() else { completion(nil) return @@ -375,7 +406,7 @@ class ScannerManager: ObservableObject { /// - 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 { + func handleNearbyRequest(_ request: String, context: ScannerContext, isCurrent: @escaping () -> Bool = { true }) async -> Bool { guard app != nil, context == .main || context == .send else { return false } let uri = ScannedPaymentRequest.normalized(request) guard Self.isNearbyPaymentRequest(uri) else { @@ -387,7 +418,8 @@ class ScannerManager: ObservableObject { // 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 } + let isOnVisit = { isCurrent() && isCurrentOrigin() } + guard isOnVisit(), let scanID = beginNearbyScan(isOnVisit: isOnVisit) else { return false } defer { endNearbyScan(scanID) } func isStillCurrent() -> Bool { nearbyScanID == scanID && isCurrent() && isCurrentOrigin() @@ -406,7 +438,7 @@ class ScannerManager: ObservableObject { func handleSendNearbyRequest( _ request: String, scope: ScanHandlingScope = .unrestricted, - isCurrent: () -> Bool = { true }, + isCurrent: @escaping () -> Bool = { true }, completion: @escaping (SendRoute?) -> Void ) async -> Bool { let uri = ScannedPaymentRequest.normalized(request) @@ -418,7 +450,8 @@ class ScannerManager: ObservableObject { return false } let isCurrentOrigin = originCheck() - guard isCurrent(), isCurrentOrigin(), let scanID = beginNearbyScan() else { return false } + let isOnVisit = { isCurrent() && isCurrentOrigin() } + guard isOnVisit(), let scanID = beginNearbyScan(isOnVisit: isOnVisit) else { return false } defer { endNearbyScan(scanID) } func isStillCurrent() -> Bool { nearbyScanID == scanID && isCurrent() && isCurrentOrigin() @@ -435,21 +468,41 @@ class ScannerManager: ObservableObject { 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 } + /// Takes the scan lock for a QR code or NFC read the user started, held while `isOnVisit` holds: the scanner visit + /// for main and Send scans, always (until the scan ends) for Electrum and Add Contact scans. A Bluetooth request + /// still decoding gives the lock up, and so does a scan whose `isOnVisit` no longer holds. + /// - Returns: the id that owns the lock, or nil while another user scan whose `isOnVisit` still holds has it. + private func beginUserScan(isOnVisit: @escaping () -> Bool) -> UUID? { + if let owner = scanOwner, owner.id != nearbyScanID, owner.isOnVisit() { + return nil + } + if let nearbyScanID { app?.releaseQuickPaySuppression(nearbyScanID) self.nearbyScanID = nil } - isHandlingScan = true - return true + let scanID = UUID() + scanOwner = ScanOwner(id: scanID, isOnVisit: isOnVisit) + return scanID } - private func beginNearbyScan() -> UUID? { + /// Releases the lock if this scan still owns it. A scan that lost it to a newer one leaves the newer one's lock. + private func endUserScan(_ scanID: UUID) { + guard owns(scanID) else { return } + scanOwner = nil + } + + private func owns(_ scanID: UUID) -> Bool { + scanOwner?.id == scanID + } + + private func beginNearbyScan(isOnVisit: @escaping () -> Bool) -> UUID? { guard !isHandlingScan, !isImageScanPending else { return nil } + // A request from an ended visit may still be decoding; its suppression must not outlive the lock it lost. + if let nearbyScanID { + app?.releaseQuickPaySuppression(nearbyScanID) + } let scanID = UUID() - isHandlingScan = true + scanOwner = ScanOwner(id: scanID, isOnVisit: isOnVisit) nearbyScanID = scanID // A Bluetooth request always opens the normal review. The suppression ends with the request or when a user // scan takes over. @@ -459,10 +512,11 @@ class ScannerManager: ObservableObject { 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 + // A scan that took the lock releases it itself. + if nearbyScanID == scanID { + nearbyScanID = nil + } + endUserScan(scanID) } /// Reads a payment request over NFC. A failure shows its error only while [isCurrent] holds: a read that ends after @@ -502,7 +556,7 @@ class ScannerManager: ObservableObject { guard let settings else { return } let generation = settings.serverConnectionGeneration guard settings.isCurrentServerConnection(generation) else { return } - let result = await settings.onElectrumScan(uri) + let result = await electrumScan(settings, uri) guard settings.isCurrentServerConnection(generation) else { return } if let result { @@ -621,7 +675,7 @@ class ScannerManager: ObservableObject { if let nearbyScanID { app?.releaseQuickPaySuppression(nearbyScanID) self.nearbyScanID = nil - isHandlingScan = false + endUserScan(nearbyScanID) } let id = UUID() pendingImageScans[id] = isCurrent @@ -629,14 +683,6 @@ class ScannerManager: ObservableObject { 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 diff --git a/Bitkit/Views/Wallets/Send/SendOptionsView.swift b/Bitkit/Views/Wallets/Send/SendOptionsView.swift index 589920831..940fb6977 100644 --- a/Bitkit/Views/Wallets/Send/SendOptionsView.swift +++ b/Bitkit/Views/Wallets/Send/SendOptionsView.swift @@ -39,7 +39,8 @@ struct SendOptionsView: View { VStack(spacing: 8) { Scanner( onScan: { uri in - await scanner.handleSendScan(uri, scope: scanScope) { route in + // Moving on (e.g. to Enter Manually) keeps the sheet open, so check its own path too. + await scanner.handleSendScan(uri, scope: scanScope, isCurrent: isOnThisScannerVisit()) { route in if let route { handleRoute(route) } @@ -162,8 +163,9 @@ struct SendOptionsView: View { let value = uri.trimmingCharacters(in: .whitespacesAndNewlines) _ = ClipboardPromptHistory().recordInspection(changeCount: UIPasteboard.general.changeCount, supportedValue: value) + let isOnVisit = isOnThisScannerVisit() Task { - await scanner.handleSendScan(uri, scope: scanScope) { route in + await scanner.handleSendScan(uri, scope: scanScope, isCurrent: isOnVisit) { route in if let route { handleRoute(route) } diff --git a/BitkitTests/ScannerManagerTests.swift b/BitkitTests/ScannerManagerTests.swift index 6c5c5c56c..0e52921fd 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -983,6 +983,47 @@ extension ScannerManagerTests { XCTAssertEqual(nextRoutes, [.amount]) } + func testUserScanGetsQuickPayAfterNearbyRequestsFromTwoVisits() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let held = HeldDecoder() + let scanner = ScannerManager(nfcReader: FakeNfcReader(.success(paymentURI))) {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { try await held.decode($0, else: decoded) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var scannerVisit = 0 + func visitCheck() -> () -> Bool { + let visit = scannerVisit + return { scannerVisit == visit } + } + let oldNearby = Task { + await scanner.handleSendNearbyRequest("bitcoin:bcrt1qheldnearbyone", isCurrent: visitCheck()) { _ in } + } + await fulfillment(of: [held.started("bitcoin:bcrt1qheldnearbyone")], timeout: 2) + + // The payer leaves the scanner and comes back while the first request decodes, and a second one arrives. + scannerVisit += 1 + let newNearby = Task { + await scanner.handleSendNearbyRequest("bitcoin:bcrt1qheldnearbytwo", isCurrent: visitCheck()) { _ in } + } + await fulfillment(of: [held.started("bitcoin:bcrt1qheldnearbytwo")], timeout: 2) + + var suppressedAtUserRoute: [Bool] = [] + await scanner.handleSendNfcRead(isCurrent: visitCheck()) { _ in + suppressedAtUserRoute.append(app.isQuickPaySuppressed) + } + + XCTAssertEqual(suppressedAtUserRoute, [false], "The earlier visit's request must not suppress QuickPay for the user's read") + + held.resume("bitcoin:bcrt1qheldnearbyone", with: decoded) + held.resume("bitcoin:bcrt1qheldnearbytwo", with: decoded) + _ = await (oldNearby.value, newNearby.value) + XCTAssertFalse(app.isQuickPaySuppressed) + } + func testNearbyRequestWaitsForASelectedPhoto() async throws { let sheets = SheetViewModel() sheets.showSheet(.scanner) @@ -1287,6 +1328,197 @@ extension ScannerManagerTests { XCTAssertTrue(wasTaken) } + // MARK: Scan ownership per scanner visit + + func testSendCameraScanCannotRouteAfterEnterManually() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let held = HeldDecoder() + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { try await held.decode($0, else: decoded) }) + 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.handleSendScan("bitcoin:bcrt1qheldscan", isCurrent: { navigationPath.isEmpty }) { routes.append($0) } + } + await fulfillment(of: [held.started("bitcoin:bcrt1qheldscan")], timeout: 2) + + // The payer taps Enter Manually while the scan decodes. + navigationPath.append(.manual) + held.resume("bitcoin:bcrt1qheldscan", with: decoded) + await task.value + + XCTAssertTrue(routes.isEmpty, "A scan from before Enter Manually must not route") + XCTAssertNil(app.scannedOnchainInvoice) + XCTAssertEqual(navigationPath, [.manual]) + } + + func testMainCameraScanCannotRouteAfterLeavingAndReturningToTheScanner() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let navigation = NavigationViewModel() + let held = HeldDecoder() + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { try await held.decode($0, else: decoded) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, navigation: navigation, sheets: sheets + ) + let task = Task { await scanner.handleScan("bitcoin:bcrt1qheldscan", context: .main) } + await fulfillment(of: [held.started("bitcoin:bcrt1qheldscan")], timeout: 2) + + navigation.path.append(.savingsWallet) + navigation.path.removeLast() + held.resume("bitcoin:bcrt1qheldscan", with: decoded) + await task.value + + XCTAssertNil(app.scannedOnchainInvoice, "A camera scan from an earlier visit must not route") + } + + func testScanAfterReopeningTheScannerIsHandledWhileTheOldLookupRuns() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let held = HeldDecoder() + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { try await held.decode($0, else: decoded) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.scanner) + let oldScan = Task { await scanner.handleScan("bitcoin:bcrt1qheldscan", context: .main) } + await fulfillment(of: [held.started("bitcoin:bcrt1qheldscan")], timeout: 2) + + // The user closes the scanner and opens it again while the first lookup runs, then scans again. + sheets.hideSheet(reason: "Close the scanner") + sheets.showSheet(.scanner) + await scanner.handleScan(paymentURI, context: .main) + + XCTAssertEqual(held.decodedInputs, ["bitcoin:bcrt1qheldscan", paymentURI], "The new scan must not wait for the old lookup") + XCTAssertNotNil(app.scannedOnchainInvoice) + + held.resume("bitcoin:bcrt1qheldscan", with: decoded) + await oldScan.value + } + + func testSendScanAfterReturningFromEnterManuallyIsHandledWhileTheOldLookupRuns() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let held = HeldDecoder() + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { try await held.decode($0, else: decoded) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.send, data: SendConfig(view: .options)) + var navigationPath: [SendRoute] = [] + var scannerVisit = 0 + func visitCheck() -> () -> Bool { + let visit = scannerVisit + return { navigationPath.isEmpty && scannerVisit == visit } + } + var oldRoutes: [SendRoute?] = [] + let oldScan = Task { + await scanner.handleSendScan("bitcoin:bcrt1qheldscan", isCurrent: visitCheck()) { oldRoutes.append($0) } + } + await fulfillment(of: [held.started("bitcoin:bcrt1qheldscan")], timeout: 2) + + // Enter Manually, then Back. + navigationPath.append(.manual) + scannerVisit += 1 + navigationPath.removeLast() + var routes: [SendRoute?] = [] + await scanner.handleSendScan(paymentURI, isCurrent: visitCheck()) { routes.append($0) } + + XCTAssertEqual(routes, [.amount], "The new scan must not wait for the old lookup") + + held.resume("bitcoin:bcrt1qheldscan", with: decoded) + await oldScan.value + XCTAssertTrue(oldRoutes.isEmpty, "The old scan must not route") + } + + func testElectrumScanKeepsTheLockUntilItFinishes() async throws { + let started = expectation(description: "Electrum connection suspended") + var continuation: CheckedContinuation? + var connections: [String] = [] + let scanner = ScannerManager {} + scanner.electrumScan = { _, uri in + connections.append(uri) + guard connections.count == 1 else { return nil } + return await withCheckedContinuation { + continuation = $0 + started.fulfill() + } + } + let navigation = NavigationViewModel() + let app = configure(scanner) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, navigation: navigation + ) + navigation.path = [.electrumSettings, .scanner] + let firstScan = Task { await scanner.handleScan("first.example:50001", context: .electrum) } + await fulfillment(of: [started], timeout: 2) + + // Back to Electrum Settings and into the scanner again while the first server connects. + navigation.path.removeLast() + navigation.path.append(.scanner) + await scanner.handleScan("second.example:50001", context: .electrum) + XCTAssertEqual(connections, ["first.example:50001"], "A second server must wait for the first connection") + + try XCTUnwrap(continuation).resume(returning: nil) + await firstScan.value + navigation.path = [.electrumSettings, .scanner] + await scanner.handleScan("second.example:50001", context: .electrum) + XCTAssertEqual(connections, ["first.example:50001", "second.example:50001"]) + } + + func testStaleScanCompletionNeitherBlocksNorReleasesANewerScan() async throws { + let decoded = try await decode(invoice: paymentURI) + let firstURI = "bitcoin:bcrt1qheldfirst" + let secondURI = "bitcoin:bcrt1qheldsecond" + let sheets = SheetViewModel() + let held = HeldDecoder() + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets, decodeInvoice: { try await held.decode($0, else: decoded) }) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + sheets.showSheet(.scanner) + let firstScan = Task { await scanner.handleScan(firstURI, context: .main) } + await fulfillment(of: [held.started(firstURI)], timeout: 2) + + sheets.hideSheet(reason: "Close the scanner") + sheets.showSheet(.scanner) + let secondScan = Task { await scanner.handleScan(secondURI, context: .main) } + await fulfillment(of: [held.started(secondURI)], timeout: 2) + + // The first scan finishes while the second still decodes: the second keeps the lock. + held.resume(firstURI, with: decoded) + await firstScan.value + await scanner.handleScan(paymentURI, context: .main) + let nearbyWasTaken = await scanner.handleNearbyRequest(paymentURI, context: .main) + XCTAssertEqual(held.decodedInputs, [firstURI, secondURI], "A scan on the same visit must wait for the second scan") + XCTAssertFalse(nearbyWasTaken) + + held.resume(secondURI, with: decoded) + await secondScan.value + XCTAssertNotNil(app.scannedOnchainInvoice, "The second scan routes") + + // Once the second scan ends, the lock is free. + sheets.hideSheet(reason: "Close the payment sheet") + sheets.showSheet(.scanner) + await scanner.handleScan(paymentURI, context: .main) + XCTAssertEqual(held.decodedInputs, [firstURI, secondURI, paymentURI]) + } + func testNfcErrorMessages() { XCTAssertEqual(NfcReadError.noPaymentRequest.message, t("other__nfc_error_text")) XCTAssertEqual(NfcReadError.multiplePaymentRequests.message, t("other__nfc_error_multiple")) @@ -1318,6 +1550,37 @@ private final class FakeNfcReader: NfcPaymentReading { } } +/// Holds the decode of each input containing "held" until the test resumes it, like a slow LNURL lookup. Other inputs +/// decode at once. +@MainActor +private final class HeldDecoder { + private(set) var decodedInputs: [String] = [] + private var expectations: [String: XCTestExpectation] = [:] + private var continuations: [String: CheckedContinuation] = [:] + + func started(_ input: String) -> XCTestExpectation { + if let expectation = expectations[input] { + return expectation + } + let expectation = XCTestExpectation(description: "Decoding \(input) suspended") + expectations[input] = expectation + return expectation + } + + func decode(_ input: String, else decoded: BitkitCore.Scanner) async throws -> BitkitCore.Scanner { + decodedInputs.append(input) + guard input.contains("held") else { return decoded } + return try await withCheckedThrowingContinuation { + continuations[input] = $0 + started(input).fulfill() + } + } + + func resume(_ input: String, with decoded: BitkitCore.Scanner) { + continuations.removeValue(forKey: input)?.resume(returning: decoded) + } +} + /// 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 { diff --git a/changelog.d/next/1432.fixed.md b/changelog.d/next/1432.fixed.md new file mode 100644 index 000000000..5ebb51326 --- /dev/null +++ b/changelog.d/next/1432.fixed.md @@ -0,0 +1 @@ +After you leave the scanner while a slow payment link is still loading, the next scan is handled right away, and the old link no longer opens over Enter Manually or a reopened scanner.