diff --git a/docs/wear.md b/docs/wear.md index cbda663fc8..aba532b127 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -26,8 +26,8 @@ settings by reading the phone's backup (see Settings sync). 2 100 000 000. - **NFC required.** The manifest requires `android.hardware.nfc` (`android:required="true"`), so Play offers the app only to watches with NFC. It is a store filter only: `pm install` ignores it, so `just wear-install` still - installs on the NFC-less emulators. Host card emulation (`android.hardware.nfc.hce`) is not required yet; PR 4 - decides that with the tap-to-pay work. + installs on the NFC-less emulators. Host card emulation (`android.hardware.nfc.hce`) is declared but not required + (`android:required="false"`), as on the phone: see NFC › Manifest. - **SDK levels.** `minSdk` 34 (Wear OS 5), `targetSdk` 36, `compileSdk` 37. Wear OS 6+ keeps apps targeting 36 always-on, so the home screen hides the balance and stops its animations in ambient mode. - **ABIs.** Debug builds split `arm64-v8a`, `armeabi-v7a` and `x86_64` (emulator); release builds ship the two ARM @@ -47,18 +47,21 @@ settings by reading the phone's backup (see Settings sync). - **Play services components.** The Breez SDK's dependencies bring Play services' sign-in and credential components into the manifest: three activities and two services, one of them exported (`RevocationBoundService`). The watch app uses none of them, so its manifest removes them - (`tools:node="remove"`), and the merged manifest lists only `MainActivity`, the balance tile's service and the - androidx startup and profile components. The libraries themselves stay on the classpath, since Breez's classes load them. + (`tools:node="remove"`), and the merged manifest lists only `MainActivity`, the balance tile's service, the NFC + tag service and the androidx startup and profile components. The libraries themselves stay on the classpath, since Breez's classes load them. - **Main thread.** Nothing reads the disk, the network or a system service on the main thread at launch or while a screen composes. `NetworkMonitor`, `DeviceLock` and `NfcMonitor` are created empty and register with the system on the IO dispatcher; the HTTP client, the settings file and the seed directory are opened on first use there. Debug builds turn on `StrictMode` (disk reads, disk writes and network on the main thread, logged to logcat under - `StrictMode`), so a regression shows while the journeys run. + `StrictMode`), so a regression shows while the journeys run. The receive tag's route (`CardEmulationTagRoute`: + registering the application id and the preferred service) does run on the main thread, each time the receive QR + resumes or its invoice changes: these are short calls to the NFC service that need the resumed activity, as on + the phone, and no disk or network read. - **Backups.** `allowBackup` is off and both backup rule files exclude every domain, so neither the seed nor the Spark state leaves the watch. - **Copied code.** The currency formatting, the colour tokens and text styles, the balance swap animations and - `clickableAlpha` are copies of the phone's, each naming its source file. Keep them in sync until a shared module - replaces them. + `clickableAlpha` are copies of the phone's, each naming its source file. So is the NFC code in the `nfc` package + (see NFC). Keep them in sync until a shared module replaces them. ### Packages @@ -77,16 +80,19 @@ settings by reading the phone's backup (see Settings sync). `WipeMarker` for the note itself), `OwnInvoiceStore` (the invoices this wallet created, in the settings file), `QuickPaySpendStore` (the day's QuickPay spend, in the settings file), the rates client, `NetworkMonitor` (`ConnectivityManager`'s default network, online once the system validated it), - `NfcMonitor` (the NFC adapter's state), `ForegroundMonitor` (the process lifecycle: whether the app is on - screen), `AmbientMonitor` (whether the activity is in ambient mode) and `ElapsedClock` (the time since boot, + `NfcMonitor` (the NFC adapter's state and whether the watch has host card emulation), `ForegroundMonitor` (the process lifecycle: whether the app is on + screen), `SendMonitor` (whether a send is under way anywhere in the process), `AmbientMonitor` (whether the activity is in ambient mode) and `ElapsedClock` (the time since boot, sleep included, for ages). +- `nfc`: the NDEF codec, the Type 4 tag emulator with its service (`NdefTagService`), `NfcTagOffer` (the tag's + offer, from start to stop), the rewrite of a request read from a tag, `NfcTapFilter` and `NfcRepeatGuard` (one + tap, one request; `ui/LaunchGate` asks the filter and `SendMonitor` for the whole process). See NFC below. - `tile`: `BalanceTileService` (the balance tile), `TileState` (what it shows) and `TileUpdates` (asks the system to draw it again). See Tile below. - `models`: among others `PhoneSettingsParser`, the reader of the phone's settings backup. - `ui`: one `MainActivity` with `testTagsAsResourceId`, a `SwipeDismissableNavHost` with the routes Onboarding, the Restore graph, Wallet removed, Home, About, Receive QR, Send, Activity detail and Not supported, and the M3 Expressive theme (black background, Brand orange, Inter Tight). `LaunchRequest` reads what an intent asks for - beyond opening the app: a payment link or the tile's Receive. The splash screen stays while the first screen is picked, for at most about a second; + beyond opening the app: a payment link, a tapped NFC tag or the tile's Receive. The splash screen stays while the first screen is picked, for at most about a second; after that the loading ring shows until it is. When the wallet storage cannot be recovered at launch, the start error (`WatchStartError` with `WatchStartRetry`) shows instead of a first screen. @@ -100,7 +106,7 @@ On-screen copy stays short: a title or one line of at most about six words per s - **Home pager.** Home is a horizontal pager (`HorizontalPagerScaffold` with a page indicator) that opens on the Balance page; Receive, Activity and Settings follow, in that order. `HOME_PAGES` in `HomePage.kt` lists the pages in swipe order, so a page is added in one line. The pager leaves the left edge of the first page to swipe-to-dismiss, which leaves the app. - There is no Send page or button: a send starts from outside the app (phone handoff, NFC or a payment link). + There is no Send page or button: a send starts from outside the app (a tapped NFC tag or a payment link). The pager composes only the page on screen, so Home itself, above the pager, leaves for onboarding or the Wallet removed notice when the wallet's state says the wallet is gone. A removal therefore reaches the wearer on any page, also when the Settings page that asked for it was swiped away meanwhile. @@ -128,7 +134,7 @@ On-screen copy stays short: a title or one line of at most about six words per s the hint appears, and the icon is still until then. - NFC off: the same icon, still, dimmed to white-32 and slashed like the phone's `ic_eye_slash` (`ic_broadcast_off`), as `NfcHintDisabled` ("NFC off"). A tap opens the NFC settings, or the settings home on - a watch without an NFC settings screen. + a watch without an NFC settings screen; a screen reader names that action "Open NFC settings". - No NFC adapter: hidden. Only the emulators get here; a store install always has NFC (see NFC required). The emulators have no NFC, so the two visible states are checked on a physical watch, or in the `NfcHint` and @@ -178,7 +184,8 @@ On-screen copy stays short: a title or one line of at most about six words per s the confirm pattern that ends a send; a tap on the check shows a new invoice. In ambient mode the QR is replaced by a dimmed QR icon (`WatchReceiveHidden`), and an invoice paid meanwhile shows the check dimmed and without the amount, with the same haptic, so the always-on screen shows no amount; the amount shows once the watch wakes. Debug builds log each invoice shown (`Showing invoice`), which is how the - journeys read it. + journeys read it. While the QR shows, the watch also offers the invoice as an NFC tag, with the NFC hint below the + QR (`WatchReceiveNfc`, or `WatchReceiveNfcOff` with NFC off): see NFC › Receive by tap. - **Tile.** The Bitkit tile (`BalanceTileService`) uses the tiles and ProtoLayout Material 3 libraries: a primary layout with the balance in the main slot and an edge button below. With a wallet it shows the balance in bitcoin, in the unit (Modern or Classic) imported from the phone, white, as on the Balance page, and a round Brand orange @@ -200,13 +207,16 @@ On-screen copy stays short: a title or one line of at most about six words per s - The tile picker shows `tile_preview` (a drawing of the balance and the Receive button, no real amount). `tile_logo` and `tile_logo_dim` are the mark's letters and dot without its black outline, the dim one at 40% opacity baked into its colours, since a tile image cannot be drawn half transparent or tinted per path. -- **Send.** There is no Send page or button. A `bitcoin:`, `BITCOIN:`, `lightning:`, `LIGHTNING:`, `lnurl:`, +- **Send.** There is no Send page or button. A tapped NFC tag with a payment link opens the same flow as the link + itself (see NFC › Pay by tap). A `bitcoin:`, `BITCOIN:`, `lightning:`, `LIGHTNING:`, `lnurl:`, `lnurlp:` or `spark:` link opens the app, as on the phone (Android matches schemes case-sensitively, and QR codes often use the uppercase ones). `lnurlw:` and `lnurlc:` (LNURL withdraw and channel) are not taken: the watch only pays. `PaymentsRepo.parse` drops `lightning:`, `lnurl:` and `lnurlp:` before decoding, as the phone's scanner does, reads a LUD-17 `lnurlp://host/path` as `https://host/path` (`http` for an onion host) and lowercases an - all-uppercase payload. A link opens the send flow above Home (`MainActivity` is `singleTop`, so a link reaches the - open app); without a wallet, during the restore, or while a send is under way, the link is dropped. The flow waits + all-uppercase payload. A link opens the send flow above Home (`MainActivity` is `singleTask`, as on the phone, so a + link reaches the one running activity in Bitkit's own task through `onNewIntent`, also when its sender starts it + without `FLAG_ACTIVITY_NEW_TASK`); without a wallet, during the restore, or while a send is under way anywhere in + the process (`LaunchGate`, `SendMonitor`), the link is dropped. The flow waits for the wallet to be ready (the loading ring), reads the input and prices the send (see Payments), all before the hold. An input without an amount, an amountless invoice, a Spark address or an LNURL with a range, gets a minimal amount entry @@ -337,7 +347,7 @@ in any other state. invoice expired. - **Known gap: the phone's attempts.** The phone picks an invoice's attempt number from its own record of sends plus Spark's list; the watch has Spark's list alone and cannot read the phone's record until the two are paired - (PR 4). The two agree whenever the watch's synced list shows the phone's sends, which is why a send needs a sync + (a later PR). The two agree whenever the watch's synced list shows the phone's sends, which is why a send needs a sync that reached Spark. Should Spark's operators not report an attempt of the phone, the watch can derive another attempt number than the phone: when the phone's attempt failed before it reached the operators and its next attempt is in flight, unseen by the watch's sync, the watch's send under the first key is a second payment of @@ -389,6 +399,9 @@ The two differences from the phone: the link opens the app. The wait never runs across `WalletStatus.Offline`: an offline wallet ends the flow on the offline refusal (see Send), the request is dropped, and QuickPay is not asked for it, then or when the network returns. + - The flow's screen is still shown (`SendViewModel.onShownChange`, from the screen's `LifecycleStartEffect`). A + flow that a new link, tap or tile request took off the back stack is stopped at once, while its view model + lives until the transition ends, and it must not pay unseen in that moment. - It is the link's first send flow. Android keeps the Send route and its link in the saved back stack, and builds the flow again when it restores the app, as after the process was killed in the background. The first flow leaves a mark in that saved state (`SendViewModel.KEY_STARTED`), and a flow that finds it never asks @@ -396,7 +409,8 @@ The two differences from the phone: - A link that Android sends again from Recents is no request at all. A task that a link created keeps that link as its intent, and opening the task from Recents starts the app with it again (`FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY`), minutes or hours after the wearer saw it. `MainActivity` takes such a - launch as a plain one (`isReplayedLaunch`): the app opens on Home and nothing is priced or paid. + launch as a plain one (`isReplayedLaunch`): the app opens on Home and nothing is priced or paid. The check is + made where a task is started, `onCreate`, and again in `onNewIntent`, where a link reaches the running app. - **QuickPay is off until the phone's settings were imported.** The phone has its settings at hand; the watch has none of its own. So QuickPay is off before the first import, and it is turned off by an import that finds no backup, a backup that cannot be decrypted or read, one with a newer layout, or QuickPay values outside what the @@ -419,12 +433,13 @@ or a count that cannot be read. backup, as without a network, and a phone that could not upload it, leave the old settings in force. The Phone settings row shows when they were last imported. - **Known gap: two counts.** The phone keeps its own count of the day's QuickPay payments and the watch cannot read - it, so the phone and the watch each allow the daily limit: together up to twice the limit a day. Pairing (PR 4) + it, so the phone and the watch each allow the daily limit: together up to twice the limit a day. Pairing (a later PR) is where the two can share one count. - **Known limit: a link sent from the phone.** Being there is measured as the watch unlocked, the app on screen and out of ambient mode. It is not measured as a look or a touch: the watch has no sensor it could ask. An app on the paired phone can open a `lightning:` link on the watch (`RemoteActivityHelper`) while the wearer looks at the - phone. With the watch on the wrist and unlocked, and the screen lit by the launch, that send counts as attended + phone. A tapped NFC tag is measured the same way: the tap itself is the wearer's act, and Android reads a tag + only with the screen on and the watch unlocked. With the watch on the wrist and unlocked, and the screen lit by the launch, that send counts as attended and goes out under QuickPay with no touch on the watch, as a link from another app on the watch does. It is bounded by the phone's QuickPay amount per payment and by the daily limit, and by the two counts above. Whether a remote launch lights the screen was not tried on a device. Nothing in V1 tells such a launch from a tap on @@ -432,6 +447,184 @@ or a count that cannot be read. - **Known gap: the phone's payment PIN.** The phone can ask for its PIN before a QuickPay limit is raised; the watch has no PIN and adopts whatever the phone saved. +## NFC + +The watch pays by a tap on a payment tag and is paid by a tap on its receive QR. Both follow the phone's NFC code +([nearby-payments.md](nearby-payments.md)), copied into `to.bitkit.wear.nfc` with a note naming each source file +rather than shared through a module. Bluetooth ("nearby") is not on the watch. + +| Watch (`wear/src/main/java/to/bitkit/wear/…`) | Phone (`app/src/main/java/to/bitkit/…`) | | +| --- | --- | --- | +| `nfc/NdefCodec.kt` | `nfc/NdefCodec.kt` | copy | +| `nfc/Type4TagEmulator.kt` | `nfc/Type4TagEmulator.kt` | copy | +| `nfc/NfcTagEmitter.kt` | `nfc/NfcTagEmitter.kt` | copy, with `revoke` added (see Receive by tap › Stopping) | +| `nfc/NfcPaymentUri.kt` | `nfc/NfcPaymentUri.kt` | copy | +| `nfc/NdefTagService.kt` | `androidServices/NdefTagService.kt` | the same service | +| `nfc/NfcRepeatGuard.kt` | `nfc/NfcRepeatGuard.kt` | copy, without the hand-over to a scanner screen | +| `nfc/NfcTagOffer.kt`, `nfc/CardEmulationTagRoute.kt`, `ui/components/NfcTagEffect.kt` | `NfcEmitterEffect` in `ui/shared/effects/NfcEffects.kt` | the same steps, split so the offer is tested without a screen | +| `nfc/NfcTapFilter.kt` | the repeat window of `nfc/NfcReadDispatcher.kt` | adapted, see One tap, one request | +| `res/xml/ndef_tag_service.xml` | `res/xml/ndef_tag_service.xml` | the same | + +The copied unit tests (`NdefCodecTest`, `Type4TagEmulatorTest`, `NfcTagEmitterTest`, `NfcPaymentUriTest`, with +`PosNfcFixtures`) run in the watch module too. + +### Receive by tap + +While the receive QR shows an invoice, the watch is an NFC Forum Type 4 tag that carries it, exactly as the phone's +Receive is, so the phone's Send by NFC and any wallet or terminal that reads Bitkit's tag pays it. + +- **The tag.** The NDEF tag application `D2760000850101`, served by `NdefTagService` (a `HostApduService` that only + the NFC stack may bind, `BIND_NFC_SERVICE`) through `Type4TagEmulator`: capability container `E103`, NDEF file + `E104`, read-only. The message is one well-known URI record (`U`) without an abbreviation prefix, holding + `lightning:` and the invoice in lowercase (`nfcPaymentUri`), the same bytes the phone writes for the same + invoice. `ndef_tag_service.xml` declares no application id and asks for an unlocked device + (`requireDeviceUnlock`), as on the phone: the id is registered at runtime while the tag is offered, and the + service is made the preferred one meanwhile, so no other app with the same id answers in its place. Closing the + route unsets the preference and removes the id, each by itself, so a failure of the first does not skip the + second. Android keeps a runtime registration when the app is killed while it offers the tag: the id then stays + routed to `NdefTagService` until the app runs again, and `NfcMonitor` removes it at its start, before it reports + host card emulation and so before any screen can offer a tag. Meanwhile the service holds no request and reports + the tag application as not found, so no invoice is served, but the watch may still take the id from another + tag app. +- **When it is offered.** Only while all of these hold, and it stops at the first that ends: + - the receive QR screen is the screen in front and the app is resumed (`NfcTagEffect` follows the screen's + lifecycle, so leaving the screen, the app or the activity stops it); + - the QR itself shows: not in ambient mode, not while it rests after 2 min, not once paid (`receiveTagUri`); + - the wallet is connected and synced (`WalletStatus.Ready`); + - the invoice is the one on screen and has not expired by the watch's clock (`ReceiveViewModel` keeps + `ReceiveUiState.nfcUri` only meanwhile). A replaced invoice's tag ends before the new QR shows. An invoice that + the QR still shows past its expiry, as when its replacement keeps failing or the watch's clock runs ahead, is + not offered. A paid invoice is taken off the tag before the check shows; + - Spark's list shows no payment of the invoice after the wallet was away: when the wallet is ready again, the + request returns only once `PaymentsRepo.findPaid` read the list. A payment it finds turns the QR into the + check; a list that cannot be read keeps the tag away until the wallet is ready anew; + - NFC is on and the watch has host card emulation; + - the repeat guard does not hold reader mode (`NfcRepeatGuard.isHeld`). After any tapped tag it holds reader + mode until the tag left, at least 3 s without one, which pauses card emulation, so the tag is taken back and + the hint hidden meanwhile and both return when the hold ends. +- **The wall clock.** The view model's timers count the time the watch is awake and stand still while it sleeps, + so the expiry is also read from the wall clock, `nowSecs() < expiresAtSecs`: whenever `nfcUri` is published, + each time `NfcTagEffect` starts the offer (`isTagCurrent`, also on every resume), and when the screen shows + again after a resume, ambient mode or a tap on the resting QR (`onShow`). An invoice the watch slept past loses + its request at once and is replaced: it leaves the screen for the loading ring when it has expired, and stays + until its replacement exists when it is only within a minute of its expiry. One that is not due yet has its + replacement and its tag's end set again to what the wall clock leaves of them (`awaitWallClock`), so a watch + that woke and stays awake replaces it on time. +- **Stopping.** `NfcTagOffer.stop` first clears the request in `NfcTagEmitter`, then takes the application id + away. With no request the emulator reports the tag application as not found, also to a reader in the middle of a + tap, so nothing is served from the moment the offer stops, whatever the NFC stack still routes. A process that + died holds no request at all. At the moment of a payment the view model takes whatever request `NfcTagEmitter` + holds out of it itself (`revoke`), a frame before the screen stops the offer, so a paid invoice is not readable + in between. Nor does a resume in that frame start it again: `isTagCurrent` also asks that the invoice on screen + still has a request. +- **Failing closed.** A tag that cannot be registered, or made the preferred service, is not offered and the hint + stays hidden. An invoice Spark could not remember as the wallet's own is never shown, so never offered either. +- **The hint.** Below the QR, centred in the strip between the QR's square, quiet zone included, and the bottom of + the screen, so it never covers the quiet zone: the Balance page's `NfcHint` at 20dp. While the tag is offered it + is the animated broadcast icon (`WatchReceiveNfc`, "Tap to receive" to accessibility services). With NFC off it + is the dimmed, slashed, still icon (`WatchReceiveNfcOff`, "NFC off"), and a tap opens the NFC settings ("Open NFC + settings" to accessibility services). Its touch area is 48dp wide and ends at the screen's edge below the icon; + above it reaches 14dp past the icon, into the QR's square by about its quiet zone on a 192dp screen, where a + touch does nothing else. It is hidden without NFC hardware or host card emulation, in ambient mode, while the QR + rests, while the repeat guard holds reader mode, and whenever the tag is not offered. No text shows. +- **Paid.** The payer's wallet pays the invoice over Lightning; the watch learns it as for a scanned QR, and the QR + turns into the check. + +### Pay by tap + +A tap on a tag whose first record is a payment link opens the send flow, also while Bitkit is not in front. + +- **Dispatch: the manifest, as on the phone.** `MainActivity` has an `NDEF_DISCOVERED` intent filter for the + schemes the watch pays: `bitcoin`, `lightning`, `lnurl`, `lnurlp` and `spark`. The filter also lists `BITCOIN` + and `LIGHTNING`, which no tag reaches: Android lowercases a record's scheme before it matches, so they only + match an intent another app or `adb` sends. Android's tag dispatch starts the activity for such a tag whatever + app is in front, with the screen on and the watch unlocked. It does so from an activity of its own and without + `FLAG_ACTIVITY_NEW_TASK` (AOSP's `NfcRootActivity`), so a `singleTop` activity would be created anew for every + tap, next to or in place of the running one. `MainActivity` is therefore `singleTask`, as on the phone: the tap + reaches the one running activity in `onNewIntent`. This is read from AOSP and from the phone's manifest and was + not tried on a watch; what must hold either way does not depend on it (see One tap, one request). Foreground + dispatch and reader mode were considered and left out. The phone turns reader mode on only on its scanner + screens, and the watch has none. Reader mode switches the watch's own card emulation off while it is on, so the + receive QR does not offer its tag while the repeat guard holds it. And neither works while the app is in the + background, which is the case asked for. + The cost: while Bitkit is in front, another app that registered the same scheme leads to Android's chooser, as it + does in the background. +- **Reading.** `LaunchRequest` reads the tag as the phone's reader does. When the intent carries the tag's message + (`EXTRA_NDEF_MESSAGES`), `NdefCodec` decodes its URI, Text and absolute-URI records and takes the one request they + hold; a tag with several different requests asks for nothing. Without the message, as for an intent sent with + `adb`, the intent's data is the request. Then the phone's `nfcPaymentRequest`: `bitcoin:?lightning=` + becomes `lightning:`, and a `bitcoin:` request with a required (`req-`) parameter is refused. A tag + the watch refuses, as that one, a tag with several different requests or one whose records it cannot read, ends + on one line, "Not supported" (`WatchTagRefused`), with the reject haptic and OK (`WatchSendClose`), as the send + flow's refusals: Android already brought Bitkit to the front for it. Without a wallet or during the restore it + opens nothing. `lnurlw:` and `lnurlc:` tags are not taken: the filter does not match them, so Android does not + start Bitkit for one. +- **The send flow.** The request opens the same flow as a link: it waits for the wallet, runs the self-send guard, + prices the send and ends on Review with the hold to pay. The offline refusal, the QuickPay rules and "the wearer + has to be there" apply unchanged; the tap is the arrival from which QuickPay's 30 s count, so a tap on an + unlocked watch whose wallet is ready in time is paid under QuickPay without the hold, within the phone's amount + and daily limit. A tap during a send is dropped; one during the restore or without a wallet opens nothing. +- **A send under way.** `PaymentsRepo.send` runs in the repository's own scope and tells `SendMonitor` from its + start to its end, also when the screen that started it is gone. `LaunchGate` drops every link, tap and tile + request meanwhile, before it reaches a screen, so the send's outcome is not replaced and the same tag is not + priced a second time while the first payment is out. +- **Own tag.** A tag that carries the watch's own receive invoice ends on "Can't pay own invoice": the invoice's + payment hash is in `OwnInvoiceStore`. The phone's invoices are not, until pairing shares them (see Self-send + guard). +- **One tap, one request.** Android dispatches every activation of a tag again, and a phone emulating a tag + activates again whenever the field drops. Two things keep one tap from opening the flow twice. `NfcRepeatGuard`, + the phone's, holds reader mode from the next resume until the tag left the field. `NfcTapFilter` drops a request + equal to the last one until 3 s passed without it, so it also holds where reader mode does not. The filter and + the send state are one each for the process (`LaunchGate`), not fields of the activity, so they hold whichever + activity instance Android hands a tap to. A refused tag is filtered by its first record, so its refusal shows + once. Should a repeat get through, the flow opens again and Spark's idempotency key pays the invoice once (see + Paying once). +- **A launch from Recents** is no tap: `isReplayedLaunch` takes it as a plain launch, as for a link, in `onCreate` + and in `onNewIntent`. + +### Manifest + +- `android.permission.NFC`, for reader mode in the repeat guard and for registering the tag. +- `android.hardware.nfc` stays required (see Module overview). +- `android.hardware.nfc.hce` is `required="false"`, as on the phone. Requiring it would have Play hide the app from + a watch with NFC and without host card emulation, which could still pay by tap, the app's purpose; the receive + tag is an extra there, and the app checks the feature at runtime (`NfcMonitor.hasCardEmulation`) and hides the + hint without it. + +### Checked where + +The emulators have no NFC adapter, so no tag is read or offered there and the hint is hidden. + +- **Emulator.** `nfc-pay-background.xml`: an `NDEF_DISCOVERED` intent sent with `adb`, carrying the request as its + data and no tag, reaches the manifest filter with the app in the background and opens Review. It checks the + filter, `onNewIntent`, the repeat filter and the send flow. It does not check what a real tap differs in: `adb` + always adds `FLAG_ACTIVITY_NEW_TASK` and names the package, so it shows neither the NFC stack's start without + that flag nor the chooser; and a real intent always carries the tag's message, which production reads and only + `LaunchRequestTest` covers, while the journey takes the data fallback. +- **Unit tests.** The tag's bytes and the read sequence (`Type4TagEmulatorTest`, `NdefCodecTest`, + `NfcTagOfferTest`), the offer's lifecycle (`NfcTagEffectTest`, `ReceiveTagTest`, `ReceiveViewModelTest`), the + hint's place and the disabled hint's touch area on the 227dp and 192dp screens (`ReceiveQrContentTest`), the + reading of a tag and the repeat filter (`LaunchRequestTest`, `NfcTapFilterTest`), what a tap or a link may open, + also during a send (`LaunchGateTest`, `SendMonitorTest`), the wall clock, the revoke and the check of Spark's + list (`ReceiveViewModelTest`, `NfcTagEmitterTest`), the tap's send flow with QuickPay and the own tag + (`SendViewModelTest`, `PaymentsRepoTest`). +- **Previews.** `ReceiveQrScreen`'s `PreviewNfc` and `PreviewNfcOff`, `SendScreen`'s `PreviewTagRefused` + (`TagRefusedTest` checks its line and its close). +- **Physical watch.** The manual tests in [journeys/wear/README.md](../journeys/wear/README.md#nfc). Not run yet: + no physical watch was at hand. + +### Open questions + +- **Where does a tap arrive?** `singleTask` should deliver it to the running activity (`onNewIntent`), as on the + phone; manual tests 1e to 1h check it on a watch. +- **Does the watch read tags at all?** Wear OS watches ship NFC for card emulation; whether a given watch polls for + tags and dispatches `NDEF_DISCOVERED` with the screen on is the vendor's choice and was not tried. On a watch that + does not, Pay by tap needs reader mode on a screen of the app, which reads only while Bitkit is in front. +- **`requireDeviceUnlock` on a watch.** A watch counts as unlocked while it stays on the wrist. Whether the NFC + stack of a watch without a screen lock, or one just put on, serves the tag was not tried. +- **Observe mode and the wallet app.** Whether a watch's default wallet app answers a reader before the preferred + service of the app in front was not tried; the phone relies on the same preference. + ## Settings sync The watch holds the same seed as the phone, so it can read what the phone backed up. It imports the phone's settings @@ -518,7 +711,7 @@ from VSS and never writes there. settings backup of its restored wallet 1.8 s after the wallet synced (2026-11-28). - **Known gap: a stale backup.** The watch sees a change only once the phone uploaded it. A phone that is offline, or whose backup fails, leaves the old settings on VSS, and the watch keeps following them. -- **Later.** Pairing (PR 4) adds a live push from the phone over the Data Layer and the watch-specific limits. +- **Later.** Pairing (a later PR) adds a live push from the phone over the Data Layer and the watch-specific limits. ### Self-send guard @@ -544,7 +737,7 @@ own invoice without complaint. **Known gap.** A device does not know the invoices the other one created: the watch pays an invoice the phone made, and the phone one the watch made, until the two share their hashes. Both stores take hashes from outside -(`OwnInvoiceStore.add`, `CacheStore.addSparkOwnInvoice`), which the pairing work (PR 4) uses to merge them. An +(`OwnInvoiceStore.add`, `CacheStore.addSparkOwnInvoice`), which the pairing work (a later PR) uses to merge them. An unpaired watch has no way to learn the phone's invoices. The watch runs the guard when an input is read, if the wallet is ready then, and always before a send is priced, also on the invoice an LNURL service returns; a guard that cannot tell refuses the send. @@ -756,5 +949,7 @@ Measured on the emulator (Wear OS 7, API 37, 454×454 round, x86_64) unless note - bitkit-core costs the watch 47.5 MB per ABI for BIP39 alone; `Bip39` keeps a later swap to one file. - Whether the watch's count of the day's QuickPay payments should be shared with the phone's before pairing exists. +- Whether Wear OS watches read NFC tags and dispatch them with the screen on, which Pay by tap counts on: see NFC › + Open questions. - Whether bitkit-ios writes all three QuickPay keys into its settings backup: the watch needs all three and leaves QuickPay off when one is missing. diff --git a/journeys/wear/README.md b/journeys/wear/README.md index 0c0e287425..a7c4e6c4e2 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -112,6 +112,7 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `offline-keeps-last-balance.xml` | hosted | yes | | `background-disconnects-spark.xml` | hosted | yes | | `nfc-hint-states.xml` | hosted, physical watch only | yes | +| `nfc-pay-background.xml` | local | yes, 2 000 sats | | `screenshot-blocked.xml` | none | no | | `receive-qr.xml` | local | no | | `receive-qr-rests.xml` | local | no | @@ -599,3 +600,108 @@ build tools installed: ```bash AAPT2="$(ls -d "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}}"/build-tools/*/ | sort -V | tail -n 1)aapt2" ``` + +### Tags and taps + +The emulators read no tag and offer none, so two things stand in for a tap there: + +- **A tapped tag.** `nfc-pay-background.xml` sends the intent Android's tag dispatch would send, with the request as + its data. The real intent always carries the tag (`EXTRA_TAG`) and its message (`EXTRA_NDEF_MESSAGES`), which `adb` + cannot build; the app reads the message when it is there and the data otherwise, so the journey takes a path no + real tap takes, and only unit tests cover the message (`LaunchRequestTest`). `adb` also adds + `FLAG_ACTIVITY_NEW_TASK` and names the package; the NFC stack starts the activity without that flag and by the + filter alone, so the journey shows neither where a real tap arrives (`MainActivity` is `singleTask` for that, + manual tests 1e to 1h) nor Android's chooser. The filter's uppercase `BITCOIN` and `LIGHTNING` entries match + only such an `adb` or app intent: Android lowercases a tag record's scheme. The journey passed on the API 37 + emulator while `MainActivity` was `singleTop`. The activity is `singleTask` now, which changes how every wear + journey that starts it arrives (`onNewIntent`), so the journeys must be re-run under `singleTask`. + Re-run under `singleTask` at `7ac718aad` on the local stack: passed, along with send-deeplink-bolt11, send-own-invoice-guard, send-offline-error, receive-qr, receive-paid, tile-balance, nfc-required and restore-background-drops-words. + + ```bash + adb shell am start -a android.nfc.action.NDEF_DISCOVERED -d "lightning:" to.bitkit.dev + ``` + +- **The receive tag and its hint.** Without an NFC adapter the receive QR never offers its tag and shows no hint + (`WatchReceiveNfc` and `WatchReceiveNfcOff` are not listed). The offer's lifecycle and the hint are covered by unit + tests and by the `PreviewNfc` and `PreviewNfcOff` previews of `ReceiveQrScreen`; see docs/wear.md › NFC › Checked + where. + +### Manual tests on a physical watch + +These need a capability the journey environment lacks: an NFC radio on the watch, and a second NFC device to tap. +Run them on a physical watch with NFC on, unlocked and on the wrist, with a dev build +([On a physical watch](#on-a-physical-watch)) and a funded wallet on hosted regtest, and a phone with a dev build of +the phone app on **another** wallet: the two apps do not know each other's invoices before pairing, and with the +same wallet the phone's invoice would be the watch's own. Debug builds log the tag's offer under `BitkitWear` +(`Started the NFC tag`, `Stopped the NFC tag`). + +1. **Tap pays from the background.** On the phone open Receive with an amount of 1 000 sats, so that it offers its + NFC tag. On the watch leave Bitkit (press the crown) and keep the screen on. Hold the watch to the back of the + phone. + - Expected: Bitkit opens on the watch on the review with "1 000" and the hold to pay; nothing is paid before the + hold. Holding pays, and the phone shows the payment as received. + - 1a. Keep the watch on the phone for 10 s after the review shows: the review stays, and no second review or + chooser opens. + - 1b. With Bitkit open on the Balance page instead of in the background: the same review opens. + - 1c. With the watch's screen off, hold it to the phone for 5 s: nothing opens, as Android reads no tag with + the screen off. Wake the screen with the watch still on the phone: the review opens once, without lifting the + watch and tapping again. + - 1d. A printed or written NFC tag with one URI record `lightning:` gives the same result as 1. + - 1e. One activity, one task: after 1 and again after 1b, run + `adb shell dumpsys activity activities | grep -c 'Hist.*to.bitkit.wear.ui.MainActivity'`. Expected: it prints + 1, and the watch's Recents show Bitkit once: the tap reached the running activity and made no second one. + - 1f. Tap again during Sending: start a payment as in 1 with a second tag at hand (another invoice). Lift the + watch off the phone when the review shows and wait 3 s, so the watch reads tags again, then hold to pay and + tap the second tag while the bolt and ring show. Expected: the sending screen stays and ends on "Sent", and + no second review opens; the log lists "Dropped launch request 'Send' during a send", unless the tap came + while the watch still held off repeats of the first tag, when Android sends nothing and nothing is logged. + If "Sent" shows before the second tap, run it again. Lifting and tapping the second tag after the flow + closed opens its review. + - 1g. Tap with Bitkit open from the launcher: open Bitkit from the launcher, open a payment link from the + phone or `adb` so a review shows, then tap a tag with another invoice. Expected: the tag's review replaces + the first in the same activity; Recents shows Bitkit once, and nothing of the first link is paid. + - 1h. A link from another app's task, where the watch has an app that opens a `lightning:` link without a new + task, as a notes or browser app that shows links; skip it otherwise, since `adb` always adds a new task. + With Bitkit running, open the link from that app. Expected: the review opens in Bitkit's own task, and + Recents shows Bitkit once. + - 1i. A tag the watch refuses: write `bitcoin:
?req-foo=1` as one URI record to a tag and tap it. + Expected: "Not supported" with OK (`WatchTagRefused`), once, however long the watch stays on the tag; OK + returns to Home. +2. **QuickPay on a tap.** With QuickPay on in the phone settings the watch imported and an amount within its limit + (the private settings wallet, see [Phone settings on VSS](#phone-settings-on-vss)), repeat 1 with a tag of + another wallet. + - Expected: the send goes out without the review and ends on "Sent"; the log lists "Skipped the hold to pay + under QuickPay". +3. **Offline tap.** Turn the watch's Wi-Fi and Bluetooth off, wait for the offline icon on the Balance page, then + tap as in 1. + - Expected: "Can't pay offline" with OK; nothing is paid when the network returns. +4. **The phone pays the watch's receive QR.** On the watch open Receive and the QR. On the phone open Send and its + NFC scanner, and hold the phone to the watch. + - Expected: below the QR the NFC hint animates (`WatchReceiveNfc`); the phone reads the watch's invoice and + opens its amount entry (the invoice is amountless); after the phone pays, the watch shows the check with the + amount. + - 4a. The hint is clear of the QR's white square, and the phone's camera still scans the QR. + - 4b. `adb shell svc nfc disable`: the hint turns dimmed and slashed (`WatchReceiveNfcOff`), the phone reads + nothing, and a tap on the hint opens the NFC settings. Run `adb shell svc nfc enable` and swipe back from the + NFC settings to the QR: the hint animates again and the phone reads the invoice. + - 4c. Leave the QR showing until the watch's screen is off, and wait until the invoice expired (1 h; the log's + "Showing invoice" line dates it). Wake the watch, and open Bitkit if the watch face shows: it returns on the + receive screen. Expected: the loading ring, then a new QR, or the QR-hidden icon that shows the new QR on a + tap (a screen that went off without ambient mode keeps the QR resting); the log lists a second "Showing + invoice" with another invoice; the phone's scanner never reads the old one. +5. **The tag stops with the QR.** With the QR showing, check with the phone's scanner that each of these ends the + tag (the phone reads nothing, and the log lists "Stopped the NFC tag"): swiping back to the Receive page; + pressing the crown; covering the watch until it goes ambient; waiting 2 min until the QR rests; after a payment, + while the check shows. + - Expected: nothing is read in any of them, and tapping the resting screen, waking the watch or tapping the + check for a new invoice brings the tag back with the QR. + - 5a. A tag tapped on the QR: with the QR showing, tap the watch on a payment tag as in 1. Expected: the review + opens above Home in place of the QR, and the log lists "Stopped the NFC tag"; the phone's scanner reads + nothing from the watch while the review shows. + - 5b. Recreation: with the QR showing, change the watch's font size or language in its settings and return. + Expected: the same QR shows, the log lists "Stopped the NFC tag" and then "Started the NFC tag" once each, + and the phone reads the invoice again. +6. **The watch's own tag.** Read the invoice of the watch's receive QR from the log + ([Reading the receive invoice](#reading-the-receive-invoice)), write `lightning:` as one URI record to a + blank NFC tag with any tag-writing app on the phone, and tap the watch on that tag. + - Expected: "Can't pay own invoice" with OK, and no hold to pay. diff --git a/journeys/wear/nfc-pay-background.xml b/journeys/wear/nfc-pay-background.xml new file mode 100644 index 0000000000..535f2d4003 --- /dev/null +++ b/journeys/wear/nfc-pay-background.xml @@ -0,0 +1,32 @@ + + + A tapped NFC payment tag opens the send flow while Bitkit is in the background: Android's tag dispatch starts the + app with an `NDEF_DISCOVERED` intent, the review shows the tag's amount, a repeat of the same tap changes nothing, + and holding the pay button pays. The emulators have no NFC, so no tag can be tapped there; `adb` sends the intent + the dispatch would send, with the request as its data and without the tag and its message. That checks the + manifest filter, `onNewIntent`, the repeat filter and the send flow. The reading of a tag's message is + unit-tested only (`LaunchRequestTest`): a real tap always carries it, and `adb` cannot. `adb` also adds + `FLAG_ACTIVITY_NEW_TASK` and names the package, which the NFC stack does not, so this does not check where a + real tap arrives or that a watch reads a tag at all; the manual tests in journeys/wear/README.md › NFC cover + those on a physical watch. Emulator and physical watch. + + Precondition: Restored wallet on the local ./spark stack with at least 2 000 sats (run receive-paid.xml first), + see journeys/wear/README.md › Local ./spark stack, with the app open on the Balance page and the loading ring + stopped, and QuickPay off or never imported (a watch with QuickPay on pays 1 000 sats without the review, as + designed). README › Holding to pay has the hold gesture. + + + Run `../bitkit-docker/spark invoice 1000` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell input keyevent KEYCODE_HOME` and wait 2 s + Run `adb shell dumpsys activity activities | grep -m1 topResumedActivity` and verify it does not name `to.bitkit.dev`: the app is in the background + Run `adb logcat -c` + Run `adb shell 'am start -a android.nfc.action.NDEF_DISCOVERED -d "lightning:<invoice>" to.bitkit.dev; sleep 1; am start -a android.nfc.action.NDEF_DISCOVERED -d "lightning:<invoice>" to.bitkit.dev'`: one command, so the repeat follows the tap by 1 s however slow the runner is, as when the watch stays on the tag + Wait up to 20 s until "WatchSendHold" is listed: the wallet may connect again first + Verify "WatchSendAmount" reads "1 000" + Run `adb logcat -d -s BitkitWear | grep -c "Dropped a repeat of an NFC tap"` and verify it prints 1: the repeat opened no second flow + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + Verify "WatchSendResultAmount" reads "1 000" + Wait up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself on the Balance page + + diff --git a/journeys/wear/nfc-required.xml b/journeys/wear/nfc-required.xml index b6b712f6c3..c01aefe96f 100644 --- a/journeys/wear/nfc-required.xml +++ b/journeys/wear/nfc-required.xml @@ -1,6 +1,7 @@ - The watch app requires NFC hardware (`android.hardware.nfc`, required), so Play offers it only to watches with NFC. + The watch app requires NFC hardware (`android.hardware.nfc`, required), so Play offers it only to watches with NFC, + and does not require host card emulation (`android.hardware.nfc.hce`), so a watch without it is not filtered out. `uses-feature` is a store filter, not an install check, so the app still installs on the NFC-less emulators. `dumpsys package` does not list required features, so the check reads the installed APK with `aapt2` from the newest SDK build tools installed (journeys/wear/README.md › NFC sets `AAPT2`). Emulator and physical watch. @@ -12,6 +13,6 @@ Run `adb pull "$(adb shell pm path to.bitkit.dev | grep base.apk | sed 's/package://')" base.apk` Run `"$AAPT2" dump badging base.apk | grep uses-feature` and verify it lists `android.hardware.nfc` Verify the same output lists `android.hardware.type.watch` - Run `"$AAPT2" dump badging base.apk | grep -c nfc.hce` and verify it prints 0: host card emulation is not required yet + Run `"$AAPT2" dump badging base.apk | grep nfc.hce` and verify its one line starts with `uses-feature-not-required`: host card emulation, which the receive tag uses, is declared but not required diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 7af945f1ac..e094432335 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -8,7 +8,13 @@ android:name="android.hardware.nfc" android:required="true" tools:ignore="UnnecessaryRequiredFeature" /> + + + + @@ -53,10 +59,15 @@ tools:ignore="MissingClass" tools:node="remove" /> + @@ -84,8 +95,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + /** + * Whether the watch can act as an NFC tag (host card emulation); false until it was read and a tag route that an + * earlier process left behind was taken away. + */ + val hasCardEmulation: StateFlow } /** @@ -51,11 +61,19 @@ class AdapterNfcMonitor @Inject constructor( override val state: StateFlow = _state.asStateFlow() + private val _hasCardEmulation = MutableStateFlow(false) + override val hasCardEmulation: StateFlow = _hasCardEmulation.asStateFlow() + init { scope.launch { runCatching { refresh() if (adapter == null) return@runCatching + val hasCardEmulation = + context.packageManager.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION) + // Before the flag lets any screen offer a tag, so this never takes away a route just opened. + if (hasCardEmulation) removeStaleTagRoute() + _hasCardEmulation.update { hasCardEmulation } val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { scope.launch { refresh() } @@ -74,6 +92,18 @@ class AdapterNfcMonitor @Inject constructor( } } + /** + * Takes the tag application id away from [NdefTagService] when an earlier process left it registered: Android + * keeps a runtime registration when the app is killed while it offers a tag. + */ + private fun removeStaleTagRoute() { + val adapter = adapter ?: return + runCatching { + CardEmulation.getInstance(adapter) + .removeAidsForService(ComponentName(context, NdefTagService::class.java), CardEmulation.CATEGORY_OTHER) + }.onFailure { Logger.warn("Failed to remove a stale NFC tag application id", it, context = TAG) } + } + private fun refresh() = _state.update { read() } private fun read(): NfcState { diff --git a/wear/src/main/java/to/bitkit/wear/data/SendMonitor.kt b/wear/src/main/java/to/bitkit/wear/data/SendMonitor.kt new file mode 100644 index 0000000000..ee21fbab29 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/SendMonitor.kt @@ -0,0 +1,31 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Whether a send is under way anywhere in the process. A send outlives the screen that started it, so what must not + * interrupt one, such as a payment link or a tapped tag, asks here and not the screen. + */ +@Singleton +class SendMonitor @Inject constructor() { + private var sends = 0 + private val _isSending = MutableStateFlow(false) + val isSending: StateFlow = _isSending.asStateFlow() + + /** Counts a send that starts now; [end] takes it out again. */ + @Synchronized + fun begin() { + sends++ + _isSending.value = true + } + + @Synchronized + fun end() { + sends = (sends - 1).coerceAtLeast(0) + _isSending.value = sends > 0 + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/CardEmulationTagRoute.kt b/wear/src/main/java/to/bitkit/wear/nfc/CardEmulationTagRoute.kt new file mode 100644 index 0000000000..95c2bc32d8 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/CardEmulationTagRoute.kt @@ -0,0 +1,49 @@ +package to.bitkit.wear.nfc + +import android.app.Activity +import android.content.ComponentName +import android.nfc.NfcAdapter +import android.nfc.cardemulation.CardEmulation +import to.bitkit.wear.utils.Logger + +/** + * Routes the NDEF tag application to [NdefTagService] while [activity] is resumed, as the phone's `NfcEmitterEffect` + * does: the application id is registered for the service only meanwhile, and the service is made the preferred + * one, so Bitkit answers no reader elsewhere and another app with the same application id does not answer instead. + */ +internal class CardEmulationTagRoute(private val activity: Activity) : TagRoute { + companion object { + private const val TAG = "CardEmulationTagRoute" + private val NDEF_AIDS = listOf(Type4TagEmulator.NDEF_AID_HEX) + } + + private val service = ComponentName(activity, NdefTagService::class.java) + private val cardEmulation: CardEmulation? by lazy { + runCatching { NfcAdapter.getDefaultAdapter(activity)?.let(CardEmulation::getInstance) } + .onFailure { Logger.warn("Failed to reach card emulation", it, context = TAG) } + .getOrNull() + } + + /** Whether both the route and the preference were set: without the preference the route is taken back. */ + override fun open(): Boolean { + val cardEmulation = cardEmulation ?: return false + return runCatching { + val isRegistered = cardEmulation.registerAidsForService(service, CardEmulation.CATEGORY_OTHER, NDEF_AIDS) + if (!isRegistered) return@runCatching false + if (cardEmulation.setPreferredService(activity, service)) return@runCatching true + cardEmulation.removeAidsForService(service, CardEmulation.CATEGORY_OTHER) + false + }.onFailure { Logger.warn("Failed to register NFC tag service", it, context = TAG) } + .onSuccess { if (!it) Logger.warn("NFC tag service registration was refused", context = TAG) } + .getOrDefault(false) + } + + /** Each step by itself: the preference can only be unset while resumed, and the id must go either way. */ + override fun close() { + val cardEmulation = cardEmulation ?: return + runCatching { cardEmulation.unsetPreferredService(activity) } + .onFailure { Logger.warn("Failed to unset the preferred NFC tag service", it, context = TAG) } + runCatching { cardEmulation.removeAidsForService(service, CardEmulation.CATEGORY_OTHER) } + .onFailure { Logger.warn("Failed to remove the NFC tag application id", it, context = TAG) } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NdefCodec.kt b/wear/src/main/java/to/bitkit/wear/nfc/NdefCodec.kt new file mode 100644 index 0000000000..4da05ba0ce --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NdefCodec.kt @@ -0,0 +1,117 @@ +// Copied from app/src/main/java/to/bitkit/nfc/NdefCodec.kt; keep both in sync. +package to.bitkit.wear.nfc + +import java.nio.ByteBuffer + +/** + * Encodes and decodes the NDEF records used for NFC payments. + * + * Bitkit writes one NFC Forum well-known URI record ("U") holding the payment request. + * When reading, it accepts URI records, Text records ("T", used by Numo and some POS apps) + * and absolute-URI records, so a tag from any payment terminal or wallet lands in the same + * scan flow as a QR code. + */ +object NdefCodec { + private const val FLAG_MB = 0x80 + private const val FLAG_ME = 0x40 + private const val FLAG_CF = 0x20 + private const val FLAG_SR = 0x10 + private const val FLAG_IL = 0x08 + private const val TNF_MASK = 0x07 + private const val TNF_WELL_KNOWN = 0x01 + private const val TNF_ABSOLUTE_URI = 0x03 + private const val TEXT_UTF16 = 0x80 + private const val TEXT_LANG_LENGTH_MASK = 0x3F + private const val SHORT_RECORD_MAX = 255 + private val TYPE_URI = byteArrayOf('U'.code.toByte()) + private val TYPE_TEXT = byteArrayOf('T'.code.toByte()) + + /** URI identifier codes, NFC Forum URI Record Type Definition, table 3. */ + private val URI_PREFIXES = listOf( + "", "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:", + ) + + /** One NDEF message with a single URI record, written without an abbreviation prefix. */ + fun encodeUriMessage(uri: String): ByteArray { + val payload = byteArrayOf(0x00) + uri.toByteArray(Charsets.UTF_8) + val isShort = payload.size <= SHORT_RECORD_MAX + val header = FLAG_MB or FLAG_ME or TNF_WELL_KNOWN or (if (isShort) FLAG_SR else 0) + val lengthBytes = if (isShort) { + byteArrayOf(payload.size.toByte()) + } else { + ByteBuffer.allocate(Int.SIZE_BYTES).putInt(payload.size).array() + } + return byteArrayOf(header.toByte(), TYPE_URI.size.toByte()) + lengthBytes + TYPE_URI + payload + } + + /** + * Returns the text of every URI, Text or absolute-URI record in [message]. + * Other record types are skipped. A malformed or chunked message yields an empty list. + */ + fun decodeTexts(message: ByteArray): List = runCatching { parse(message) }.getOrDefault(emptyList()) + + /** + * Picks the payment request from the decoded record texts: the single distinct non-blank + * value, or null when the tag holds nothing or several different requests. + */ + fun payableText(texts: List): String? { + val distinct = texts.map { it.trim() }.filter { it.isNotEmpty() }.distinct() + return distinct.singleOrNull() + } + + private fun parse(message: ByteArray): List { + val texts = mutableListOf() + var offset = 0 + while (offset < message.size) { + val header = message[offset].toInt() and 0xFF + require(header and FLAG_CF == 0) { "Chunked records are not supported" } + val typeLength = message[offset + 1].toInt() and 0xFF + offset += 2 + val payloadLength: Int + if (header and FLAG_SR != 0) { + payloadLength = message[offset].toInt() and 0xFF + offset += 1 + } else { + payloadLength = ByteBuffer.wrap(message, offset, Int.SIZE_BYTES).int + offset += Int.SIZE_BYTES + } + require(payloadLength >= 0) { "Invalid payload length" } + val idLength = if (header and FLAG_IL != 0) (message[offset++].toInt() and 0xFF) else 0 + val type = message.copyOfRange(offset, offset + typeLength) + offset += typeLength + idLength + require(offset + payloadLength <= message.size) { "Truncated record" } + val payload = message.copyOfRange(offset, offset + payloadLength) + offset += payloadLength + + recordText(header and TNF_MASK, type, payload)?.let(texts::add) + if (header and FLAG_ME != 0) break + } + return texts + } + + private fun recordText(tnf: Int, type: ByteArray, payload: ByteArray): String? = when { + tnf == TNF_WELL_KNOWN && type.contentEquals(TYPE_URI) -> decodeUri(payload) + tnf == TNF_WELL_KNOWN && type.contentEquals(TYPE_TEXT) -> decodeText(payload) + tnf == TNF_ABSOLUTE_URI -> type.toString(Charsets.UTF_8) + else -> null + } + + private fun decodeUri(payload: ByteArray): String? { + if (payload.isEmpty()) return null + val prefix = URI_PREFIXES.getOrNull(payload[0].toInt() and 0xFF) ?: return null + return prefix + payload.copyOfRange(1, payload.size).toString(Charsets.UTF_8) + } + + private fun decodeText(payload: ByteArray): String? { + if (payload.isEmpty()) return null + val status = payload[0].toInt() and 0xFF + val textStart = 1 + (status and TEXT_LANG_LENGTH_MASK) + if (textStart > payload.size) return null + val charset = if (status and TEXT_UTF16 != 0) Charsets.UTF_16 else Charsets.UTF_8 + return payload.copyOfRange(textStart, payload.size).toString(charset) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NdefTagService.kt b/wear/src/main/java/to/bitkit/wear/nfc/NdefTagService.kt new file mode 100644 index 0000000000..9bfef3c2a7 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NdefTagService.kt @@ -0,0 +1,23 @@ +package to.bitkit.wear.nfc + +import android.nfc.cardemulation.HostApduService +import android.os.Bundle + +/** + * Presents the receive QR's invoice as an NFC Forum Type 4 tag, so a phone or a point of sale reads it like any NDEF + * tag. It answers only while [NfcTagEmitter] holds a request, which the receive QR screen publishes while it shows + * the invoice (see [NfcTagOffer]). The watch's counterpart of the phone's `to.bitkit.androidServices.NdefTagService`, + * with the same tag application and record; keep the two in sync. + */ +class NdefTagService : HostApduService() { + private val emulator = Type4TagEmulator(NfcTagEmitter::currentMessage) + + override fun processCommandApdu(commandApdu: ByteArray?, extras: Bundle?): ByteArray { + val apdu = commandApdu ?: return Type4TagEmulator.SW_WRONG_LENGTH + return emulator.process(apdu) + } + + override fun onDeactivated(reason: Int) { + emulator.reset() + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcPaymentUri.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcPaymentUri.kt new file mode 100644 index 0000000000..d49043cd44 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcPaymentUri.kt @@ -0,0 +1,128 @@ +// Copied from app/src/main/java/to/bitkit/nfc/NfcPaymentUri.kt; keep both in sync. +package to.bitkit.wear.nfc + +import java.math.BigDecimal + +private val URI_SCHEMES = listOf("bitcoin:", "lightning:", "ethereum:", "lnurlp:", "lnurlw:", "lnurlc:") +private val LIGHTNING_PREFIXES = listOf("lnbc", "lntb", "lntbs", "lnbcrt", "lnsb", "lno1", "lnurl") + +/** + * Turns a receive request into the URI written to an NFC tag. + * + * A tag needs a scheme for other wallets (and Android's tag dispatch) 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. + */ +fun nfcPaymentUri(request: String?): String? { + val trimmed = request?.trim().orEmpty() + if (trimmed.isEmpty()) return null + val lowercase = trimmed.lowercase() + return when { + URI_SCHEMES.any { lowercase.startsWith(it) } -> trimmed + LIGHTNING_PREFIXES.any { lowercase.startsWith(it) } -> "lightning:$trimmed" + else -> "bitcoin:$trimmed" + } +} + +private const val BITCOIN_WITHOUT_ADDRESS = "bitcoin:?" +private const val REQUIRED_PARAM_PREFIX = "req-" +private const val BITCOIN_SCHEME = "bitcoin:" +private const val DEEPLINK_SCHEME = "bitkit://" +private val DECODER_WRAPPERS = listOf("lightning:", "lnurl:", "lnurlw:", "lnurlc:", "lnurlp:") + +/** + * Keys BIP 321 ("Query Keys", "Invalid URIs") forbids repeating; `pop` and `req-pop` count as the same key. + * Unknown optional keys and payment instructions may repeat. + */ +private val SINGLETON_KEYS = setOf("amount", "label", "message", "pop") + +/** + * Turns a payment request read from a tag or a nearby device into one the scanner decodes. + * + * 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 one of [SINGLETON_KEYS], which BIP 321 + * makes invalid; one with more than one `lightning` value, which Bitkit does not support, since the rewrite would + * have to pick one; and one whose `amount` the invoice does not carry: the invoice alone could not ask for it. + * Anything else is returned trimmed and unchanged. + */ +fun scannedPaymentRequest(text: String): String { + val trimmed = text.trim() + if (!trimmed.startsWith(BITCOIN_WITHOUT_ADDRESS, ignoreCase = true)) return trimmed + val pairs = trimmed.substring(BITCOIN_WITHOUT_ADDRESS.length).split('&') + // Checked on every key, since BIP 321 allows a required key with an empty or no value. + if (pairs.any { it.substringBefore('=').lowercase().startsWith(REQUIRED_PARAM_PREFIX) }) return trimmed + val keys = pairs.map { it.substringBefore('=').lowercase().removePrefix(REQUIRED_PARAM_PREFIX) } + val singletons = keys.filter { it in SINGLETON_KEYS } + if (singletons.size != singletons.toSet().size) return trimmed + if (keys.count { it == "lightning" } > 1) return trimmed + // An `amount` key with no value is a malformed amount, not a missing one. + val hasEmptyAmount = pairs.any { + it.substringBefore('=').equals("amount", ignoreCase = true) && it.substringAfter('=', "").isEmpty() + } + if (hasEmptyAmount) return trimmed + val params = pairs.mapNotNull { + val key = it.substringBefore('=', missingDelimiterValue = "") + val value = it.substringAfter('=', missingDelimiterValue = "") + if (key.isEmpty() || value.isEmpty()) null else key.lowercase() to value + }.toMap() + // A BOLT12 offer (`lno`) is left as is: the scanner cannot pay one yet. + val request = params["lightning"] ?: return trimmed + val amount = params["amount"] + if (amount != null && !isBolt11Amount(request, amount)) return trimmed + return "lightning:$request" +} + +/** + * Whether [uri] is a `bitcoin:` URI with a required (`req-`) BIP 321 parameter. No Bitkit flow fulfils one, and the + * shipped scanner ignores it on a URI with an address, so a request read from a nearby device or a tag with one is + * refused. Other schemes, such as an LNURL-pay URL, keep their own query untouched. + */ +fun hasRequiredParam(uri: String): Boolean { + // 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. Follow the same + // steps and check the `bitcoin:` request the decoder would receive. + var decoded = uri.coreTrim() + while (true) { + val wrapper = DECODER_WRAPPERS.firstOrNull { decoded.startsWith(it, ignoreCase = true) } + decoded = when { + wrapper != null -> decoded.substring(wrapper.length).coreTrim() + decoded.startsWith(DEEPLINK_SCHEME) -> decoded.replace(DEEPLINK_SCHEME, "").coreTrim() + else -> break + } + } + if (!decoded.startsWith(BITCOIN_SCHEME, ignoreCase = true)) return false + return decoded.substringAfter('?', missingDelimiterValue = "") + .split('&') + .any { it.substringBefore('=').lowercase().startsWith(REQUIRED_PARAM_PREFIX) } +} + +/** Trims like the decoder's Rust `trim()`, which also removes U+0085 (NEL) that Kotlin's `trim()` keeps. */ +private fun String.coreTrim() = trim { it.isWhitespace() || it == '\u0085' } + +/** The request to hand to the scanner for [text] read from an NFC tag, or null when it is refused. */ +fun nfcPaymentRequest(text: String): String? = scannedPaymentRequest(text).takeUnless(::hasRequiredParam) + +/** BIP 321 amount syntax: decimal BTC, with no sign, exponent or unit. */ +private val BIP321_AMOUNT = Regex("^(\\d+(\\.\\d*)?|\\.\\d+)$") +private val BOLT11_HRP = Regex("^ln[a-z]+?(\\d+)([munp]?)$") +private val BTC_PER_UNIT = mapOf( + "" to BigDecimal.ONE, + "m" to BigDecimal("0.001"), + "u" to BigDecimal("0.000001"), + "n" to BigDecimal("0.000000001"), + "p" to BigDecimal("0.000000000001"), +) + +/** Whether [invoice] is a BOLT11 invoice for exactly [amountBtc], read from its human-readable part. */ +private fun isBolt11Amount(invoice: String, amountBtc: String): Boolean { + val hrp = invoice.lowercase().substringBeforeLast('1', missingDelimiterValue = "") + val match = BOLT11_HRP.matchEntire(hrp) ?: return false + val (digits, unit) = match.destructured + val invoiceBtc = BigDecimal(digits).multiply(BTC_PER_UNIT.getValue(unit)) + if (!BIP321_AMOUNT.matches(amountBtc)) return false + val requested = amountBtc.toBigDecimal() + return invoiceBtc.compareTo(requested) == 0 +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcRepeatGuard.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcRepeatGuard.kt new file mode 100644 index 0000000000..8aed5fa9cb --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcRepeatGuard.kt @@ -0,0 +1,105 @@ +package to.bitkit.wear.nfc + +import android.app.Activity +import android.nfc.NfcAdapter +import android.nfc.Tag +import android.os.Handler +import android.os.Looper +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import to.bitkit.wear.utils.Logger +import java.lang.ref.WeakReference +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds + +private const val READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A or + NfcAdapter.FLAG_READER_NFC_B or + NfcAdapter.FLAG_READER_NFC_F or + NfcAdapter.FLAG_READER_NFC_V + +/** + * Stops Android from delivering a payment tag again while the watch stays on it after a tap. + * + * Android dispatches every activation of a tag as a new NDEF_DISCOVERED intent, and a phone emulating a tag activates + * again whenever the field drops. The guard holds reader mode with a callback that reads nothing until the tag has + * left the field, then switches reader mode off. Reader mode pauses the watch's own card emulation meanwhile. + * + * A copy of the phone's `to.bitkit.nfc.NfcRepeatGuard` without its hand-over to a scanning screen, which the watch + * does not have, and with [isHeld], which the receive QR reads so it never shows a tag no reader reaches; keep the + * two in sync. + */ +internal object NfcRepeatGuard { + private const val TAG = "NfcRepeatGuard" + + /** How long the guard holds when no tag answers, e.g. after a launch from a tag already removed. */ + private val HOLD_WITHOUT_TAG: Duration = 3.seconds + + /** How long a tag must stay out of range before Android may deliver it again. */ + private val REMOVAL_DEBOUNCE: Duration = 1.seconds + + /** Covers the gap while an emulating phone re-activates its tag after a removal is reported. */ + private val RELEASE_AFTER_REMOVAL: Duration = 500.milliseconds + + private val handler by lazy { Handler(Looper.getMainLooper()) } + private val release = Runnable { release() } + private var activity = WeakReference(null) + + private val _isHeld = MutableStateFlow(false) + + /** Whether reader mode is held right now, which pauses the watch's own card emulation: no reader reaches it. */ + val isHeld: StateFlow = _isHeld.asStateFlow() + + /** Holds reader mode on [activity], which must be resumed. Pass the [tag] just read so its removal ends it. */ + fun engage(activity: Activity, tag: Tag? = null) { + if (Looper.myLooper() != Looper.getMainLooper()) { + handler.post { engage(activity, tag) } + return + } + val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return + val enabled = runCatching { + adapter.enableReaderMode(activity, { onTag(adapter, it) }, READER_FLAGS, null) + }.onFailure { Logger.warn("Failed to hold NFC reader mode", it, context = TAG) }.isSuccess + if (!enabled) return + this.activity = WeakReference(activity) + _isHeld.value = true + schedule(HOLD_WITHOUT_TAG) + tag?.let { onTag(adapter, it) } + } + + private fun onTag(adapter: NfcAdapter, tag: Tag) { + handler.post { handler.removeCallbacks(release) } + val ignored = runCatching { + adapter.ignore( + tag, + REMOVAL_DEBOUNCE.inWholeMilliseconds.toInt(), + { schedule(RELEASE_AFTER_REMOVAL) }, + handler, + ) + }.getOrDefault(false) + if (!ignored) schedule(HOLD_WITHOUT_TAG) + } + + private fun schedule(delay: Duration) { + handler.post { + handler.removeCallbacks(release) + handler.postDelayed(release, delay.inWholeMilliseconds) + } + } + + /** Ends the hold of [activity] as it goes away, so a hold never outlives the activity that reader mode ran on. */ + fun disengage(activity: Activity) { + if (this.activity.get() !== activity) return + handler.removeCallbacks(release) + release() + } + + private fun release() { + _isHeld.value = false + val activity = activity.get() ?: return + this.activity = WeakReference(null) + runCatching { NfcAdapter.getDefaultAdapter(activity)?.disableReaderMode(activity) } + .onFailure { Logger.warn("Failed to release NFC reader mode", it, context = TAG) } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcTagEmitter.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagEmitter.kt new file mode 100644 index 0000000000..ede0dad302 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagEmitter.kt @@ -0,0 +1,40 @@ +// Copied from app/src/main/java/to/bitkit/nfc/NfcTagEmitter.kt, with [NfcTagEmitter.revoke] added; keep both in sync. +package to.bitkit.wear.nfc + +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference + +/** + * The payment request this device currently offers over NFC. + * + * The Receive screen publishes its request while it is in the foreground and clears it when it + * leaves, so [NdefTagService] answers a reader only while that request is on screen. + * The service and the UI run in the same process, so a process-wide holder is enough. + */ +object NfcTagEmitter { + private class Published(val token: Long, val message: ByteArray) + + private val tokens = AtomicLong(0) + private val published = AtomicReference(null) + + /** Publishes [uri] and returns the token that [clear] needs, so a later publisher is not cleared. */ + fun publish(uri: String): Long { + val token = tokens.incrementAndGet() + published.set(Published(token, NdefCodec.encodeUriMessage(uri))) + return token + } + + /** Clears the request published with [token]; returns false when another one replaced it. */ + fun clear(token: Long): Boolean { + val current = published.get() ?: return false + return current.token == token && published.compareAndSet(current, null) + } + + /** + * Takes the published request back at once, whoever published it: the moment an invoice of the Receive screen is + * paid, without waiting for the screen to stop the offer. A reader is served nothing more of it. + */ + fun revoke() = published.set(null) + + fun currentMessage(): ByteArray? = published.get()?.message +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcTagOffer.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagOffer.kt new file mode 100644 index 0000000000..f498aac102 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcTagOffer.kt @@ -0,0 +1,46 @@ +package to.bitkit.wear.nfc + +/** Routes the NDEF tag application to [NdefTagService] and takes the route away again. */ +internal interface TagRoute { + /** Whether readers now reach the service, and no other app's service under the same application id. */ + fun open(): Boolean + + fun close() +} + +/** + * Offers one payment request to NFC readers through [NdefTagService], from [start] until [stop]. The logic of the + * phone's `NfcEmitterEffect` (`to.bitkit.ui.shared.effects.NfcEffects`), apart from the screen so it can be tested: + * the request is published first, and taken back when the route to the service cannot be opened, so the screen + * never says it can be tapped when no reader would reach it. + */ +internal class NfcTagOffer( + private val route: TagRoute, + private val emitter: NfcTagEmitter = NfcTagEmitter, +) { + private var token: Long? = null + + val isOffered: Boolean get() = token != null + + /** Offers [uri], instead of what was offered before. Returns whether a reader can now read it. */ + fun start(uri: String): Boolean { + stop() + val published = emitter.publish(uri) + if (route.open()) { + token = published + return true + } + emitter.clear(published) + return false + } + + /** Stops offering. The request is cleared before the route closes, so a reader mid-tap is served nothing more. */ + fun stop() { + val published = token ?: return + token = null + // Another offer may have published since; it then owns the route too. A request that was revoked left + // nothing published, and its route still closes here. + if (!emitter.clear(published) && emitter.currentMessage() != null) return + route.close() + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/NfcTapFilter.kt b/wear/src/main/java/to/bitkit/wear/nfc/NfcTapFilter.kt new file mode 100644 index 0000000000..36d2344efb --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/NfcTapFilter.kt @@ -0,0 +1,39 @@ +package to.bitkit.wear.nfc + +import android.os.SystemClock +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +/** + * Drops the repeats of one tap. Android dispatches every activation of a tag as a new intent, and a phone emulating + * a tag activates again whenever the field drops, so a watch held on it gets the same request again and again. + * [NfcRepeatGuard] stops that where the watch supports reader mode; this filter holds either way: a request equal to + * the last one is dropped until [REPEAT_WINDOW] passed without it. Modelled on the phone's + * `to.bitkit.nfc.NfcReadDispatcher`, whose window counts from the first read; here every repeat extends it, since no + * reader mode callback tells the watch that the tag left. + * + * One filter serves the whole process, so it holds whichever activity instance Android hands a repeat to. + */ +@Singleton +class NfcTapFilter internal constructor(private val nowMs: () -> Long) { + @Inject + constructor() : this(SystemClock::elapsedRealtime) + + private var last: Pair? = null + + /** Whether [request], just read from a tag, is a new tap and not a repeat of the last one. */ + @Synchronized + fun isNew(request: String): Boolean { + val time = nowMs() + val previous = last + last = request to time + if (previous == null || previous.first != request) return true + return time - previous.second >= REPEAT_WINDOW.inWholeMilliseconds + } + + companion object { + val REPEAT_WINDOW: Duration = 3.seconds + } +} diff --git a/wear/src/main/java/to/bitkit/wear/nfc/Type4TagEmulator.kt b/wear/src/main/java/to/bitkit/wear/nfc/Type4TagEmulator.kt new file mode 100644 index 0000000000..9510b75af2 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/nfc/Type4TagEmulator.kt @@ -0,0 +1,129 @@ +// Copied from app/src/main/java/to/bitkit/nfc/Type4TagEmulator.kt; keep both in sync. +package to.bitkit.wear.nfc + +/** + * Read-only NFC Forum Type 4 tag, served over host card emulation. + * + * A reader selects the NDEF tag application, reads the capability container (file E103) + * and then the NDEF file (E104), which holds a 2-byte length followed by the message. + * [ndefMessage] is read when the NDEF file is selected, so one tap always sees one + * consistent request. While it returns null the application itself is reported as not found, + * so a reader sees no tag. + */ +class Type4TagEmulator( + private val ndefMessage: () -> ByteArray?, +) { + private var isApplicationSelected = false + private var selectedFile: ByteArray? = null + + fun process(apdu: ByteArray): ByteArray { + if (apdu.size < HEADER_SIZE) return SW_WRONG_LENGTH + if (apdu[0] != CLA) return SW_CLA_NOT_SUPPORTED + return when (apdu[1]) { + INS_SELECT -> select(apdu) + INS_READ_BINARY -> readBinary(apdu) + INS_UPDATE_BINARY -> SW_SECURITY_NOT_SATISFIED + else -> SW_INS_NOT_SUPPORTED + } + } + + fun reset() { + isApplicationSelected = false + selectedFile = null + } + + private fun select(apdu: ByteArray): ByteArray { + val p1 = apdu[2] + val data = commandData(apdu) ?: return SW_WRONG_LENGTH + return when (p1) { + // With nothing published Bitkit does not present a tag at all, so readers cannot detect it. + P1_SELECT_BY_NAME -> if (data.contentEquals(NDEF_AID) && ndefMessage() != null) { + isApplicationSelected = true + selectedFile = null + SW_OK + } else { + reset() + SW_FILE_NOT_FOUND + } + + P1_SELECT_BY_ID -> selectFile(data) + else -> SW_FILE_NOT_FOUND + } + } + + private fun selectFile(fileId: ByteArray): ByteArray { + if (!isApplicationSelected) return SW_FILE_NOT_FOUND + selectedFile = when { + fileId.contentEquals(CC_FILE_ID) -> CAPABILITY_CONTAINER + fileId.contentEquals(NDEF_FILE_ID) -> ndefFile() + else -> null + } + return if (selectedFile != null) SW_OK else SW_FILE_NOT_FOUND + } + + private fun ndefFile(): ByteArray? { + val message = ndefMessage() ?: return null + if (message.size > MAX_NDEF_SIZE) return null + val length = byteArrayOf((message.size shr 8).toByte(), message.size.toByte()) + return length + message + } + + private fun readBinary(apdu: ByteArray): ByteArray { + val file = selectedFile ?: return SW_FILE_NOT_FOUND + // The selected copy keeps one tap consistent, but once Receive stops offering, nothing more is served. + if (ndefMessage() == null) { + reset() + return SW_FILE_NOT_FOUND + } + val offset = ((apdu[2].toInt() and 0xFF) shl 8) or (apdu[3].toInt() and 0xFF) + if (offset > file.size) return SW_WRONG_OFFSET + val requested = if (apdu.size > HEADER_SIZE) apdu[HEADER_SIZE].toInt() and 0xFF else 0 + val length = if (requested == 0) SHORT_LE_MAX else requested + val end = minOf(file.size, offset + length) + return file.copyOfRange(offset, end) + SW_OK + } + + private fun commandData(apdu: ByteArray): ByteArray? { + if (apdu.size <= HEADER_SIZE) return null + val lc = apdu[HEADER_SIZE].toInt() and 0xFF + val start = HEADER_SIZE + 1 + if (apdu.size < start + lc) return null + return apdu.copyOfRange(start, start + lc) + } + + companion object { + /** NDEF Tag Application, NFC Forum Type 4 Tag specification. */ + val NDEF_AID = byteArrayOf(0xD2.toByte(), 0x76, 0x00, 0x00, 0x85.toByte(), 0x01, 0x01) + const val NDEF_AID_HEX = "D2760000850101" + const val MAX_NDEF_SIZE = 0x0FFE + + private const val HEADER_SIZE = 4 + private const val SHORT_LE_MAX = 256 + private const val CLA: Byte = 0x00 + private const val INS_SELECT: Byte = 0xA4.toByte() + private const val INS_READ_BINARY: Byte = 0xB0.toByte() + private const val INS_UPDATE_BINARY: Byte = 0xD6.toByte() + private const val P1_SELECT_BY_NAME: Byte = 0x04 + private const val P1_SELECT_BY_ID: Byte = 0x00 + + private val CC_FILE_ID = byteArrayOf(0xE1.toByte(), 0x03) + private val NDEF_FILE_ID = byteArrayOf(0xE1.toByte(), 0x04) + + /** + * Mapping version 2.0, MLe 0x003B, MLc 0x0034, then the NDEF file control TLV: + * file E104, maximum size [MAX_NDEF_SIZE] + 2, read access granted, write access denied. + */ + private val CAPABILITY_CONTAINER = byteArrayOf( + 0x00, 0x0F, 0x20, 0x00, 0x3B, 0x00, 0x34, + 0x04, 0x06, 0xE1.toByte(), 0x04, 0x10, 0x00, 0x00, 0xFF.toByte(), + ) + + val SW_OK = byteArrayOf(0x90.toByte(), 0x00) + val SW_FILE_NOT_FOUND = byteArrayOf(0x6A, 0x82.toByte()) + val SW_WRONG_LENGTH = byteArrayOf(0x67, 0x00) + val SW_WRONG_OFFSET = byteArrayOf(0x6B, 0x00) + val SW_SECURITY_NOT_SATISFIED = byteArrayOf(0x69, 0x82.toByte()) + val SW_INS_NOT_SUPPORTED = byteArrayOf(0x6D, 0x00) + val SW_CLA_NOT_SUPPORTED = byteArrayOf(0x6E, 0x00) + } +} diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt index adde658df7..f8d4dbcb9f 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -34,6 +34,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.data.OwnInvoiceStore +import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.UncertainSend import to.bitkit.wear.data.UncertainSendStore import to.bitkit.wear.di.IoDispatcher @@ -71,6 +72,7 @@ class PaymentsRepo @Inject constructor( private val ownInvoiceStore: OwnInvoiceStore, private val uncertainSendStore: UncertainSendStore, private val quickPayRepo: QuickPayRepo, + private val sendMonitor: SendMonitor, ) { companion object { private const val TAG = "PaymentsRepo" @@ -229,6 +231,16 @@ class PaymentsRepo @Inject constructor( }.first().toWatchPayment() } + /** + * The payment of [invoice] as Spark lists it now, or null when it lists none. Fails when the list cannot be + * read, so a caller never takes an unread list for an unpaid invoice. + */ + suspend fun findPaid(invoice: ReceiveInvoice): Result = withContext(ioDispatcher) { + runSuspendCatching { + sparkService.listPayments().firstOrNull { it.isReceiptOf(invoice) }?.toWatchPayment() + } + } + private suspend fun findReceipt(invoice: ReceiveInvoice): Payment? = runSuspendCatching { sparkService.listPayments().firstOrNull { it.isReceiptOf(invoice) } }.getOrNull() @@ -451,8 +463,18 @@ class PaymentsRepo @Inject constructor( * * A send that [skipConfirmation] counted against the QuickPay limit is taken out of the count again when it * fails with a [SendError] other than [SendError.Unknown]. + * + * While it runs, [SendMonitor.isSending] says so to the whole process. */ - suspend fun send(prepared: PreparedSend): Result = sendScope.async { + suspend fun send(prepared: PreparedSend): Result { + // Counted before the send leaves the caller, and until it ends, also when the caller went away meanwhile. + sendMonitor.begin() + val send = sendScope.async { sendCounted(prepared) } + send.invokeOnCompletion { sendMonitor.end() } + return send.await() + } + + private suspend fun sendCounted(prepared: PreparedSend): Result = runSuspendCatching { // Another send holds the wallet: nothing of this request is sent, so it is not reported as under way. if (!sendMutex.tryLock()) throw SendError.Busy() @@ -485,7 +507,6 @@ class PaymentsRepo @Inject constructor( quickPayRepo.release(reservation) } } - }.await() /** * Syncs with Spark, so its list shows what the phone sent from the same wallet as far as Spark's operators tell. diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchGate.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchGate.kt new file mode 100644 index 0000000000..053de54e73 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchGate.kt @@ -0,0 +1,51 @@ +package to.bitkit.wear.ui + +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.nfc.NfcTapFilter +import to.bitkit.wear.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Decides what an intent's request may open, for the whole process: the repeat of a tap and anything that arrives + * while a send is under way open nothing. It is asked before a request reaches a screen and holds no activity's + * state, so it decides the same whichever activity instance Android handed the intent to. + */ +@Singleton +class LaunchGate @Inject constructor( + private val tapFilter: NfcTapFilter, + private val sendMonitor: SendMonitor, +) { + companion object { + private const val TAG = "LaunchGate" + } + + /** Whether a send is under way anywhere in the process. */ + val isSending: Boolean get() = sendMonitor.isSending.value + + /** + * What to show for [request], read from an intent, or null for nothing. For a tapped tag, [isTap], a request + * that is no [LaunchRequest.Send] becomes the tag's refusal, and a repeat of the last tap, told by the request + * or else by [tapData], the tag's first record, is dropped. + */ + fun admit(request: LaunchRequest?, isTap: Boolean = false, tapData: String? = null): LaunchRequest? { + val asked = if (isTap) request as? LaunchRequest.Send ?: LaunchRequest.TagRefused else request + if (isTap) { + val tapped = (asked as? LaunchRequest.Send)?.input ?: tapData.orEmpty() + // The filter hears of every tap, also one dropped below, so its repeats stay dropped afterwards. + if (!tapFilter.isNew(tapped)) { + Logger.debug("Dropped a repeat of an NFC tap", context = TAG) + return null + } + if (asked is LaunchRequest.TagRefused) { + Logger.info("Refused an NFC tag without a payment request the watch takes", context = TAG) + } + } + if (asked == null) return null + if (isSending) { + Logger.info("Dropped launch request '${asked::class.simpleName}' during a send", context = TAG) + return null + } + return asked + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt index 2f8ea0425a..d7b73a2b26 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -1,15 +1,26 @@ package to.bitkit.wear.ui import android.content.Intent +import android.nfc.NdefMessage +import android.nfc.NfcAdapter +import androidx.core.content.IntentCompat +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentRequest /** What an intent that opened the app asks for, beyond showing it. */ sealed interface LaunchRequest { - /** Pay the payment input of a `bitcoin:`, `lightning:`, `lnurl:`, `lnurlp:` or `spark:` link, in any case. */ + /** + * Pay the payment input of a `bitcoin:`, `lightning:`, `lnurl:`, `lnurlp:` or `spark:` link, in any case, or + * the one read from an NFC tag. + */ data class Send(val input: String) : LaunchRequest /** Show the receive QR, as from the tile. */ data object Receive : LaunchRequest + /** Say that the tapped NFC tag holds no payment request the watch takes; never made from a link. */ + data object TagRefused : LaunchRequest + companion object { /** The extra that asks for [Receive], set by the tile. */ const val EXTRA_OPEN = "to.bitkit.wear.OPEN" @@ -18,16 +29,46 @@ sealed interface LaunchRequest { /** The manifest's link schemes, lowercased. `lnurlw` and `lnurlc` are left out: the watch only pays. */ private val SEND_SCHEMES = setOf("bitcoin", "lightning", "lnurl", "lnurlp", "spark") - /** The request of an intent with [action], [data] and the [open] extra, or null for a plain launch. */ - fun from(action: String?, data: String?, open: String?): LaunchRequest? { + /** + * The request of an intent with [action], [data] and the [open] extra, or null for a plain launch. For a + * tapped NFC tag, [tagTexts] holds the texts of the tag's records when the intent carries the tag's + * message: see [tagInput]. + */ + fun from(action: String?, data: String?, open: String?, tagTexts: List? = null): LaunchRequest? { if (open == OPEN_RECEIVE) return Receive - if (action != Intent.ACTION_VIEW || data.isNullOrBlank()) return null - val scheme = data.substringBefore(':', missingDelimiterValue = "").lowercase() - return if (scheme in SEND_SCHEMES) Send(data) else null + val input = when (action) { + Intent.ACTION_VIEW -> data + NfcAdapter.ACTION_NDEF_DISCOVERED -> tagInput(data, tagTexts) + else -> null + } + if (input.isNullOrBlank()) return null + val scheme = input.substringBefore(':', missingDelimiterValue = "").lowercase() + return if (scheme in SEND_SCHEMES) Send(input) else null + } + + /** + * The payment request of a tapped tag, read as the phone reads one: the one request its records hold, + * [NdefCodec.payableText], or [data], the first record as Android hands it over, when the intent came + * without the tag's message; then the phone's rewrite and refusal, [nfcPaymentRequest]. Null, so nothing + * opens, for a tag with several different requests or with a required parameter no flow fulfils. + */ + internal fun tagInput(data: String?, tagTexts: List?): String? { + val text = if (tagTexts != null) NdefCodec.payableText(tagTexts) else data + return text?.takeIf { it.isNotBlank() }?.let(::nfcPaymentRequest) } fun from(intent: Intent?): LaunchRequest? = - intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN)) } + intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN), it.tagTexts()) } + + /** The texts of the records of the tag that sent this intent, or null when it carries no tag message. */ + private fun Intent.tagTexts(): List? { + if (action != NfcAdapter.ACTION_NDEF_DISCOVERED) return null + val messages = runCatching { + IntentCompat.getParcelableArrayExtra(this, NfcAdapter.EXTRA_NDEF_MESSAGES, NdefMessage::class.java) + }.getOrNull() + if (messages.isNullOrEmpty()) return null + return messages.filterIsInstance().flatMap { NdefCodec.decodeTexts(it.toByteArray()) } + } } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt index 0d4811e771..d80e9a9ec2 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt @@ -1,6 +1,8 @@ package to.bitkit.wear.ui import android.content.Intent +import android.nfc.NfcAdapter +import android.nfc.Tag import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent @@ -13,6 +15,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.core.content.IntentCompat import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.foundation.LocalAmbientModeManager @@ -20,6 +23,7 @@ import androidx.wear.compose.foundation.rememberAmbientModeManager import androidx.wear.compose.material3.AppScaffold import dagger.hilt.android.AndroidEntryPoint import to.bitkit.wear.data.AmbientMonitor +import to.bitkit.wear.nfc.NfcRepeatGuard import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.screens.start.StartErrorScreen @@ -38,16 +42,24 @@ class MainActivity : ComponentActivity() { @Inject lateinit var ambientMonitor: AmbientMonitor + /** Decides what a link or a tap may open; one for the process, so it never depends on this instance. */ + @Inject + lateinit var launchGate: LaunchGate + private val startViewModel: StartViewModel by viewModels() /** What the intent that opened the app asks for, until the navigation shows it. */ private var launchRequest by mutableStateOf(null) + /** Whether a tag opened or reached the app, so the next resume holds the reader against its repeats. */ + private var guardNfcOnResume = false + private var nfcTagToGuard: Tag? = null + override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) // A recreated activity has shown its intent's request already, and so has one opened again from Recents. - if (savedInstanceState == null && !isReplayedLaunch(intent.flags)) launchRequest = LaunchRequest.from(intent) + if (savedInstanceState == null && !isReplayedLaunch(intent.flags)) handleLaunch(intent) val splashStart = TimeSource.Monotonic.markNow() splashScreen.setKeepOnScreenCondition { startViewModel.uiState.value.isStarting && splashStart.elapsedNow() < SPLASH_LIMIT @@ -68,6 +80,7 @@ class MainActivity : ComponentActivity() { startRoute = it, launchRequest = launchRequest, onLaunchRequestHandle = { launchRequest = null }, + isSendUnderWay = { launchGate.isSending }, ) } if (uiState.isStarting) BezelLoading() @@ -83,9 +96,38 @@ class MainActivity : ComponentActivity() { } } + /** Where a link or a tap reaches the running app: `singleTask` keeps one activity in one task. */ override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) - LaunchRequest.from(intent)?.let { launchRequest = it } + if (isReplayedLaunch(intent.flags)) return + handleLaunch(intent) + } + + override fun onDestroy() { + NfcRepeatGuard.disengage(this) + super.onDestroy() + } + + override fun onResume() { + super.onResume() + if (!guardNfcOnResume) return + guardNfcOnResume = false + NfcRepeatGuard.engage(this, nfcTagToGuard) + nfcTagToGuard = null + } + + /** + * Takes what [intent] asks for, as far as [LaunchGate] lets it through. A tapped tag's intent also arms the + * repeat guard for the next resume, as on the phone. + */ + private fun handleLaunch(intent: Intent) { + val isTap = intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED + if (isTap) { + guardNfcOnResume = true + nfcTagToGuard = IntentCompat.getParcelableExtra(intent, NfcAdapter.EXTRA_TAG, Tag::class.java) + } + launchGate.admit(LaunchRequest.from(intent), isTap = isTap, tapData = intent.dataString) + ?.let { launchRequest = it } } override fun onWindowFocusChanged(hasFocus: Boolean) { diff --git a/wear/src/main/java/to/bitkit/wear/ui/Routes.kt b/wear/src/main/java/to/bitkit/wear/ui/Routes.kt index 4e459737a2..b94f317772 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/Routes.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/Routes.kt @@ -25,6 +25,9 @@ object Routes { const val SEND_INPUT = "input" const val SEND = "send?$SEND_INPUT={$SEND_INPUT}" + /** The one-line refusal of a tapped NFC tag without a payment request the watch takes. */ + const val TAG_REFUSED = "tag_refused" + /** One payment of the activity list, by its id in [ACTIVITY_PAYMENT_ID]. */ const val ACTIVITY_PAYMENT_ID = "id" const val ACTIVITY_DETAIL = "activity/{$ACTIVITY_PAYMENT_ID}" diff --git a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt index a68932bb17..97a5983857 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt @@ -32,6 +32,7 @@ import to.bitkit.wear.ui.screens.restore.RestoreStartScreen import to.bitkit.wear.ui.screens.restore.RestoreViewModel import to.bitkit.wear.ui.screens.restore.RestoreWordScreen import to.bitkit.wear.ui.screens.send.SendScreen +import to.bitkit.wear.ui.screens.send.TagRefusedScreen import to.bitkit.wear.ui.screens.settings.AboutScreen import to.bitkit.wear.ui.screens.unsupported.UnsupportedScreen import to.bitkit.wear.utils.Logger @@ -42,16 +43,19 @@ fun WearNavHost( launchRequest: LaunchRequest?, onLaunchRequestHandle: () -> Unit, modifier: Modifier = Modifier, + isSendUnderWay: () -> Boolean = { false }, ) { val navController = rememberSwipeDismissableNavController() var isRestoreSaving by remember { mutableStateOf(false) } var isSending by remember { mutableStateOf(false) } val currentOnLaunchRequestHandle by rememberUpdatedState(onLaunchRequestHandle) + val currentIsSendUnderWay by rememberUpdatedState(isSendUnderWay) LaunchedEffect(launchRequest) { val request = launchRequest ?: return@LaunchedEffect currentOnLaunchRequestHandle() // A send under way keeps its screen: leaving it would hide the outcome of a payment that may have gone out. - if (isSending) { + // The process is asked too, as the screen's own state follows a send that just started by a frame. + if (isSending || currentIsSendUnderWay()) { Logger.info("Dropped launch request '${request::class.simpleName}' during a send", context = TAG) return@LaunchedEffect } @@ -97,6 +101,9 @@ fun WearNavHost( onBusyChange = { isSending = it }, ) } + composable(Routes.TAG_REFUSED) { + TagRefusedScreen(onClose = { navController.popBackStack(Routes.TAG_REFUSED, inclusive = true) }) + } composable( route = Routes.ACTIVITY_DETAIL, arguments = listOf(navArgument(Routes.ACTIVITY_PAYMENT_ID) { type = NavType.StringType }), @@ -174,7 +181,8 @@ private fun NavController.showRestoreWord(index: Int) { } /** - * Opens what [request] asks for above Home: the send flow of a deeplink, or the tile's receive QR. Without a wallet, + * Opens what [request] asks for above Home: the send flow of a deeplink or a tapped tag, the tile's receive QR, or + * the refusal of a tag the watch does not take. Without a wallet, * or outside Home's back stack, such as during the restore, the request is dropped; the caller drops it while a send * is under way. */ @@ -188,6 +196,7 @@ private fun NavController.showLaunchRequest(request: LaunchRequest) { when (request) { is LaunchRequest.Send -> navigateTo(Routes.send(request.input)) LaunchRequest.Receive -> navigateTo(Routes.RECEIVE_QR) + LaunchRequest.TagRefused -> navigateTo(Routes.TAG_REFUSED) } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt b/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt index fc7811f125..da7141eb77 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/components/NfcHint.kt @@ -26,6 +26,9 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.coerceAtLeast +import androidx.compose.ui.unit.coerceIn import androidx.compose.ui.unit.dp import androidx.wear.compose.material3.Icon import kotlinx.coroutines.Dispatchers @@ -39,8 +42,8 @@ import to.bitkit.wear.ui.theme.Colors /** The hint's icon size. */ private val HINT_SIZE = 24.dp -/** The extra touch area around the disabled hint, which makes it a 48dp target without moving the icon. */ -private val DISABLED_TOUCH_PADDING = 12.dp +/** The touch target of the disabled hint; the area around the icon is added without moving the icon. */ +private val DISABLED_TOUCH_SIZE = 48.dp /** The side of the viewport of `ic_broadcast`, whose path data [BroadcastPaths] holds. */ private const val VIEWPORT = 16f @@ -91,46 +94,76 @@ fun nfcHintState(nfc: NfcState, isWalletReady: Boolean, isAmbient: Boolean): Nfc * loop; only their alpha animates. When animations are off it is the still icon; that setting is read off the main * thread each time the hint appears, and the icon is still until then. With NFC off it is the still icon, * dimmed and slashed, and a tap on it opens the NFC settings through [onDisabledClick]. + * + * The Balance page shows it for paying by tap; the receive QR shows it at another [size], with its own + * [activeDescription] and test tags, while the watch offers the invoice as a tag. The disabled icon sits where the + * active one does when both are aligned by their bottom edge: its touch area reaches below it, by + * [disabledTouchBelow] when given, for a hint so near the screen's edge that the full area would leave the screen. */ @Composable fun NfcHint( state: NfcHintState, onDisabledClick: () -> Unit, modifier: Modifier = Modifier, + size: Dp = HINT_SIZE, + activeDescription: String = stringResource(R.string.home__nfc_hint), + activeTag: String = "NfcHint", + disabledTag: String = "NfcHintDisabled", + disabledTouchBelow: Dp? = null, ) { when (state) { NfcHintState.Hidden -> Unit - NfcHintState.Active -> ActiveHint(modifier = modifier) - NfcHintState.Disabled -> DisabledHint(onClick = onDisabledClick, modifier = modifier) + NfcHintState.Active -> ActiveHint( + description = activeDescription, + hintSize = size, + tag = activeTag, + modifier = modifier + ) + NfcHintState.Disabled -> DisabledHint( + size = size, + tag = disabledTag, + touchBelow = disabledTouchBelow, + onClick = onDisabledClick, + modifier = modifier + ) } } @Composable private fun DisabledHint( + size: Dp, + tag: String, + touchBelow: Dp?, onClick: () -> Unit, modifier: Modifier = Modifier, ) { - val description = stringResource(R.string.home__nfc_off) + val touchPadding = ((DISABLED_TOUCH_SIZE - size) / 2).coerceAtLeast(0.dp) + val paddingBelow = touchBelow?.coerceIn(0.dp, touchPadding) ?: touchPadding Icon( painter = painterResource(R.drawable.ic_broadcast_off), - contentDescription = description, + contentDescription = stringResource(R.string.home__nfc_off), tint = Colors.White32, modifier = modifier - .offset(y = DISABLED_TOUCH_PADDING) - .clickableAlpha(onClickLabel = description, onClick = onClick) - .padding(DISABLED_TOUCH_PADDING) - .size(HINT_SIZE) - .testTag("NfcHintDisabled") + .offset(y = paddingBelow) + // The label says what the tap does: the description alone would read as turning NFC off. + .clickableAlpha(onClickLabel = stringResource(R.string.nfc__open_settings), onClick = onClick) + .padding(start = touchPadding, top = touchPadding, end = touchPadding, bottom = paddingBelow) + .size(size) + .testTag(tag) ) } @Composable -private fun ActiveHint(modifier: Modifier = Modifier) { - val description = stringResource(R.string.home__nfc_hint) +private fun ActiveHint( + description: String, + hintSize: Dp, + tag: String, + modifier: Modifier = Modifier, +) { val hintModifier = modifier - .size(HINT_SIZE) + .size(hintSize) .semantics { contentDescription = description } - .testTag("NfcHint") + .testTag(tag) val context = LocalContext.current val isStill by produceState(initialValue = true) { value = withContext(Dispatchers.IO) { context.areAnimationsDisabled } diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/NfcTagEffect.kt b/wear/src/main/java/to/bitkit/wear/ui/components/NfcTagEffect.kt new file mode 100644 index 0000000000..ea27b1ec71 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/ui/components/NfcTagEffect.kt @@ -0,0 +1,85 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.compose.LocalActivity +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import to.bitkit.wear.nfc.CardEmulationTagRoute +import to.bitkit.wear.nfc.NfcTagOffer +import to.bitkit.wear.nfc.TagRoute +import to.bitkit.wear.utils.Logger + +private const val TAG = "NfcTagEffect" + +/** + * Offers [uri] to NFC readers as a tag while the calling screen is resumed, so only while it is the screen in front + * of an app in the foreground, and stops when it pauses, leaves or [uri] changes or turns null. [onOfferChange] + * tells whether a reader can read the tag right now. [isCurrent] is asked each time the offer starts, also on a + * return to the screen, and a request that is no longer current, as an invoice that expired while the watch slept, + * is not offered. The watch's counterpart of the phone's `NfcEmitterEffect`. + */ +@Composable +fun NfcTagEffect( + uri: String?, + onOfferChange: (Boolean) -> Unit, + isCurrent: () -> Boolean = { true }, +) { + val activity = LocalActivity.current ?: return + val route = remember(activity) { CardEmulationTagRoute(activity) } + NfcTagEffect(uri = uri, route = route, onOfferChange = onOfferChange, isCurrent = isCurrent) +} + +@Composable +internal fun NfcTagEffect( + uri: String?, + route: TagRoute, + onOfferChange: (Boolean) -> Unit, + isCurrent: () -> Boolean = { true }, +) { + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnOfferChange by rememberUpdatedState(onOfferChange) + val currentIsCurrent by rememberUpdatedState(isCurrent) + + DisposableEffect(route, lifecycleOwner, uri) { + if (uri.isNullOrBlank()) return@DisposableEffect onDispose {} + val offer = NfcTagOffer(route) + + fun start() { + if (!currentIsCurrent()) { + Logger.debug("Kept back an NFC tag whose request is no longer current", context = TAG) + offer.stop() + currentOnOfferChange(false) + return + } + val isOffered = offer.start(uri) + Logger.debug("Started the NFC tag, offered '$isOffered'", context = TAG) + currentOnOfferChange(isOffered) + } + + fun stop() { + if (offer.isOffered) Logger.debug("Stopped the NFC tag", context = TAG) + offer.stop() + currentOnOfferChange(false) + } + + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> start() + Lifecycle.Event.ON_PAUSE -> stop() + else -> Unit + } + } + // A new observer is sent the events up to the current state, so a resumed screen starts here. + lifecycleOwner.lifecycle.addObserver(observer) + + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + stop() + } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt index aa4cea0fd6..2d9822a066 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -20,6 +21,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource @@ -29,6 +31,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.material3.FilledTonalIconButton import androidx.wear.compose.material3.Icon @@ -37,8 +40,13 @@ import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.Text import kotlinx.coroutines.delay import to.bitkit.wear.R +import to.bitkit.wear.data.NfcState +import to.bitkit.wear.ext.openNfcSettings import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.CenteredScreen +import to.bitkit.wear.ui.components.NfcHint +import to.bitkit.wear.ui.components.NfcHintState +import to.bitkit.wear.ui.components.NfcTagEffect import to.bitkit.wear.ui.components.QrCode import to.bitkit.wear.ui.components.ScreenAwake import to.bitkit.wear.ui.components.SmallAmountRow @@ -62,6 +70,50 @@ private const val HIDDEN_ALPHA = 0.4f /** How long the QR keeps the screen on at full brightness without a touch, before it rests. */ internal val QR_AWAKE_LIMIT = 2.minutes +/** The NFC hint's size below the QR: it fits the strip the QR leaves free on the smallest round screen. */ +private val NFC_HINT_SIZE = 20.dp + +/** + * The request the watch offers as an NFC tag, or null when it offers none: the invoice the QR shows right now, so + * not in ambient mode, not while the QR rests and not once paid, with NFC on and on a watch that can act as a tag. + * Nor while the repeat guard holds reader mode after a tap, [isReaderHeld], since no reader reaches the watch's tag + * meanwhile. [ReceiveUiState.nfcUri] is already null unless the wallet is ready and the invoice is current. + */ +internal fun receiveTagUri( + uiState: ReceiveUiState, + nfc: NfcState, + hasCardEmulation: Boolean, + isAmbient: Boolean, + isResting: Boolean, + isReaderHeld: Boolean = false, +): String? { + val isQrShown = uiState.qrContent != null && uiState.paidAmount == null && !isAmbient && !isResting + val canOffer = isQrShown && hasCardEmulation && nfc == NfcState.On && !isReaderHeld + return uiState.nfcUri?.takeIf { canOffer && it.isNotBlank() } +} + +/** + * The NFC hint below the QR: animated while the tag is offered, [isOffered]; dimmed and slashed when only NFC being + * off keeps the invoice on screen from being offered; hidden otherwise, as without NFC hardware, in ambient mode, + * while the QR rests, while the repeat guard holds reader mode, or when the tag could not be registered. + */ +internal fun receiveNfcHintState( + uiState: ReceiveUiState, + nfc: NfcState, + hasCardEmulation: Boolean, + isAmbient: Boolean, + isResting: Boolean, + isOffered: Boolean, + isReaderHeld: Boolean = false, +): NfcHintState { + fun tagUri(nfc: NfcState) = receiveTagUri(uiState, nfc, hasCardEmulation, isAmbient, isResting, isReaderHeld) + return when { + nfc == NfcState.Off && tagUri(NfcState.On) != null -> NfcHintState.Disabled + isOffered && tagUri(nfc) != null -> NfcHintState.Active + else -> NfcHintState.Hidden + } +} + /** * The receive QR, as large as the round screen allows, at full brightness and with the screen kept on while it * shows. After [QR_AWAKE_LIMIT] without a touch it rests: the QR hides behind a dimmed icon and the screen may turn @@ -69,6 +121,9 @@ internal val QR_AWAKE_LIMIT = 2.minutes * again, as does a tap anywhere on the resting screen. Ambient mode hides it. A paid invoice turns into a check with * the amount and its own haptic; a tap on the check makes a new invoice. In ambient mode the check shows without * the amount, as the always-on screen shows no amount. + * + * While the QR shows, the watch also offers the invoice as an NFC tag, as the phone's Receive does, with the NFC + * hint below the QR: see [receiveTagUri]. */ @Composable fun ReceiveQrScreen( @@ -93,12 +148,41 @@ fun ReceiveQrScreen( } // A watch that wakes from ambient mode shows the QR again, and so does the invoice after a paid one. LaunchedEffect(isAmbient, isPaid) { if (isAmbient || isPaid) isResting = false } + val nfc by viewModel.nfcState.collectAsStateWithLifecycle() + val hasCardEmulation by viewModel.hasCardEmulation.collectAsStateWithLifecycle() + val isReaderHeld by viewModel.isReaderHeld.collectAsStateWithLifecycle() + // The watch may have slept past the invoice's expiry: the view model reads the clock when the screen is back. + LifecycleResumeEffect(viewModel) { + viewModel.onShow() + onPauseOrDispose {} + } + LaunchedEffect(isAmbient) { if (!isAmbient) viewModel.onShow() } + var isTagOffered by remember { mutableStateOf(false) } + NfcTagEffect( + uri = receiveTagUri(uiState, nfc, hasCardEmulation, isAmbient, isResting, isReaderHeld), + isCurrent = viewModel::isTagCurrent, + onOfferChange = { isTagOffered = it }, + ) + val context = LocalContext.current ReceiveQrContent( uiState = uiState, isAmbient = isAmbient, isResting = isResting, + nfcHint = receiveNfcHintState( + uiState = uiState, + nfc = nfc, + hasCardEmulation = hasCardEmulation, + isAmbient = isAmbient, + isResting = isResting, + isOffered = isTagOffered, + isReaderHeld = isReaderHeld, + ), + onNfcSettingsClick = context::openNfcSettings, onQrTouch = { touches++ }, - onShowClick = { isResting = false }, + onShowClick = { + isResting = false + viewModel.onShow() + }, onRefreshClick = viewModel::onRefreshClick, modifier = modifier ) @@ -111,8 +195,10 @@ internal fun ReceiveQrContent( onRefreshClick: () -> Unit, modifier: Modifier = Modifier, isResting: Boolean = false, + nfcHint: NfcHintState = NfcHintState.Hidden, onQrTouch: () -> Unit = {}, onShowClick: () -> Unit = {}, + onNfcSettingsClick: () -> Unit = {}, ) { val qrContent = uiState.qrContent val paidAmount = uiState.paidAmount @@ -124,7 +210,13 @@ internal fun ReceiveQrContent( ) qrContent != null && isAmbient -> Hidden(modifier = modifier) qrContent != null && isResting -> Hidden(onClick = onShowClick, modifier = modifier) - qrContent != null -> Qr(content = qrContent, onTouch = onQrTouch, modifier = modifier) + qrContent != null -> Qr( + content = qrContent, + nfcHint = nfcHint, + onTouch = onQrTouch, + onNfcSettingsClick = onNfcSettingsClick, + modifier = modifier + ) uiState.isError -> Error(onRetryClick = onRefreshClick, modifier = modifier) else -> CenteredScreen( overlay = { BezelLoading() }, @@ -138,7 +230,9 @@ internal fun ReceiveQrContent( @Composable private fun Qr( content: String, + nfcHint: NfcHintState, onTouch: () -> Unit, + onNfcSettingsClick: () -> Unit, modifier: Modifier = Modifier, ) { val currentOnTouch by rememberUpdatedState(onTouch) @@ -155,13 +249,31 @@ private fun Qr( } } ) { + val screenSize = minOf(maxWidth, maxHeight) + val qrSize = screenSize * QR_SIZE_FRACTION QrCode( content = content, contentDescription = stringResource(R.string.receive__title), modifier = Modifier - .size(minOf(maxWidth, maxHeight) * QR_SIZE_FRACTION) + .size(qrSize) .testTag("WatchReceiveQr") ) + // Centred in the strip between the QR's square, quiet zone included, and the bottom of the screen. The + // disabled hint's touch area ends at the screen's edge below it; above it reaches into the QR's square, by + // about its quiet zone on the smallest screen, where a touch does nothing else. + val strip = (screenSize - qrSize) / 2 + NfcHint( + state = nfcHint, + onDisabledClick = onNfcSettingsClick, + size = NFC_HINT_SIZE, + disabledTouchBelow = (strip - NFC_HINT_SIZE) / 2, + activeDescription = stringResource(R.string.receive__nfc_hint), + activeTag = "WatchReceiveNfc", + disabledTag = "WatchReceiveNfcOff", + modifier = Modifier + .align(Alignment.BottomCenter) + .offset(y = -(strip - NFC_HINT_SIZE) / 2) + ) } } @@ -256,6 +368,32 @@ private fun Preview() { } } +@WearPreviewDevices +@Composable +private fun PreviewNfc() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + nfcHint = NfcHintState.Active, + ) + } +} + +@WearPreviewDevices +@Composable +private fun PreviewNfcOff() { + WearPreview { + ReceiveQrContent( + uiState = ReceiveUiState(qrContent = PREVIEW_INVOICE), + isAmbient = false, + onRefreshClick = {}, + nfcHint = NfcHintState.Disabled, + ) + } +} + @WearPreviewDevices @Composable private fun PreviewPaid() { diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt index 32e2adf60c..6fdf421d5e 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModel.kt @@ -9,20 +9,30 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.NfcMonitor +import to.bitkit.wear.data.NfcState import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.env.Env import to.bitkit.wear.ext.runSuspendCatching import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.ReceiveInvoice import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.nfc.NfcRepeatGuard +import to.bitkit.wear.nfc.NfcTagEmitter +import to.bitkit.wear.nfc.nfcPaymentUri import to.bitkit.wear.repositories.PaymentsRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletStatus @@ -31,19 +41,31 @@ import to.bitkit.wear.ui.screens.home.bitcoinAmount import to.bitkit.wear.utils.Logger import java.time.Instant import javax.inject.Inject +import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds /** * The receive QR: an amountless invoice made once the wallet is ready, shown until it is paid or nearly expired. * A nearly expired invoice is replaced by a new one and still watched until it expires; a paid one, shown or * replaced, turns into a check until the wearer asks for a new invoice. + * + * The invoice on screen is also what the watch may offer as an NFC tag, [ReceiveUiState.nfcUri]: only while the + * wallet is ready and only until the invoice expires by the watch's clock, so a tag never carries a stale or a paid + * invoice. The screen decides whether it is offered at all (see `receiveTagUri`). + * + * The timers here count the time the watch is awake, which stands still while it sleeps, so the expiry is also read + * from the wall clock, [nowSecs]: whenever the tag's request is published, when the screen starts to offer it + * ([isTagCurrent]), and when the screen shows again ([onShow]), which replaces an invoice that expired meanwhile + * and sets the timers of one that did not to what the wall clock leaves of them. */ @HiltViewModel class ReceiveViewModel internal constructor( private val paymentsRepo: PaymentsRepo, private val walletRepo: WalletRepo, private val settingsStore: SettingsStore, + nfcMonitor: NfcMonitor, private val nowSecs: () -> Long, + private val revokeTag: () -> Unit = NfcTagEmitter::revoke, ) : ViewModel() { companion object { private const val TAG = "ReceiveViewModel" @@ -66,13 +88,26 @@ class ReceiveViewModel internal constructor( paymentsRepo: PaymentsRepo, walletRepo: WalletRepo, settingsStore: SettingsStore, - ) : this(paymentsRepo, walletRepo, settingsStore, { Instant.now().epochSecond }) + nfcMonitor: NfcMonitor, + ) : this(paymentsRepo, walletRepo, settingsStore, nfcMonitor, { Instant.now().epochSecond }) private val _uiState = MutableStateFlow(ReceiveUiState()) val uiState: StateFlow = _uiState.asStateFlow() + /** Whether NFC is on, for the hint beside the QR. */ + val nfcState: StateFlow = nfcMonitor.state + + /** Whether the watch can act as an NFC tag at all. */ + val hasCardEmulation: StateFlow = nfcMonitor.hasCardEmulation + + /** Whether the repeat guard holds reader mode after a tap, which keeps every reader from the watch's tag. */ + val isReaderHeld: StateFlow = NfcRepeatGuard.isHeld + private var job: Job? = null + /** Asks the rotation and the tag to read the wall clock again: see [onShow]. */ + private val clockChecks = MutableSharedFlow(extraBufferCapacity = 1) + init { refresh() } @@ -80,6 +115,24 @@ class ReceiveViewModel internal constructor( /** Makes a new invoice: after an error, and after the last one was paid. */ fun onRefreshClick() = refresh() + /** + * The screen shows again, after the app returned, ambient mode ended or the wearer asked for the QR: the watch + * may have slept past the invoice's expiry, so its tag request goes at once and the rotation replaces the + * invoice now. An invoice that is not due yet has its timers set again from the wall clock. + */ + fun onShow() { + _uiState.update { if (it.nfcUri != null && !isCurrent(it.expiresAtSecs)) it.copy(nfcUri = null) else it } + clockChecks.tryEmit(Unit) + } + + /** + * Whether the invoice on screen still has a tag request and has not expired by the watch's clock; asked + * whenever its tag starts, so a request that was taken away a frame ago, as a paid one, is not started again. + */ + fun isTagCurrent(): Boolean = _uiState.value.let { it.nfcUri != null && isCurrent(it.expiresAtSecs) } + + private fun isCurrent(expiresAtSecs: Long?): Boolean = expiresAtSecs != null && nowSecs() < expiresAtSecs + private fun refresh() { job?.cancel() job = viewModelScope.launch { @@ -88,8 +141,13 @@ class ReceiveViewModel internal constructor( val watcherScope = this val rotation = launch { rotate(watcherScope, paid) } val payment = paid.await() - rotation.cancelAndJoin() + // Paid: the tag goes first, before anything here suspends, so a paid invoice is never offered. It is + // also taken from the NFC service here, a frame before the screen stops the offer: whatever it holds, + // since only this screen publishes, and it may still hold the request of an invoice just replaced. coroutineContext.cancelChildren() + revokeTag() + _uiState.update { it.copy(nfcUri = null) } + rotation.join() Logger.info("Received payment '${payment.id}'", context = TAG) val unit = runSuspendCatching { settingsStore.data.first().displayUnit } .getOrDefault(BitcoinDisplayUnit.MODERN) @@ -103,6 +161,7 @@ class ReceiveViewModel internal constructor( * still completes [paid]. */ private suspend fun rotate(watcherScope: CoroutineScope, paid: CompletableDeferred) { + var tag: Job? = null while (true) { // The invoice on screen stays until its replacement exists, or until it is about to expire. val isShowing = _uiState.value.qrContent != null @@ -115,16 +174,82 @@ class ReceiveViewModel internal constructor( return } if (Env.isDebug) Logger.debug("Showing invoice '${invoice.bolt11}'", context = TAG) - _uiState.update { ReceiveUiState(qrContent = invoice.bolt11.uppercase()) } - val expiresIn = (invoice.expiresAtSecs.toLong() - nowSecs()).seconds + // The replaced invoice's tag ends before the new invoice shows, so the tag is never behind the QR. + tag?.cancelAndJoin() + val expiresAtSecs = invoice.expiresAtSecs.toLong() + _uiState.update { ReceiveUiState(qrContent = invoice.bolt11.uppercase(), expiresAtSecs = expiresAtSecs) } + val expiresIn = (expiresAtSecs - nowSecs()).seconds + tag = watcherScope.launch { offerTag(invoice, expiresIn, paid) } val lifetime = (expiresIn - EXPIRY_MARGIN).coerceAtLeast(MIN_LIFETIME) watcherScope.launch { withTimeoutOrNull(expiresIn.coerceAtLeast(lifetime + EXPIRY_MARGIN)) { paymentsRepo.awaitPaid(invoice) } ?.let { paid.complete(it) } } - delay(lifetime) + awaitWallClock(untilSecs = nowSecs() + lifetime.inWholeSeconds, timeout = lifetime) Logger.debug("Replacing invoice '${invoice.paymentHash}' before it expires", context = TAG) - _uiState.update { it.copy(isLoading = true) } + // An invoice the watch slept past is not shown while its replacement is made. + val isExpired = nowSecs() >= expiresAtSecs && expiresIn > Duration.ZERO + _uiState.update { if (isExpired) ReceiveUiState(isLoading = true) else it.copy(isLoading = true) } + } + } + + /** + * Waits [timeout], which ends at [untilSecs] on the wall clock. The timeout stands still while the watch sleeps, + * so at every [clockChecks] it is set again to what the wall clock leaves of it, and a watch that woke before + * [untilSecs] and stays awake still returns on time. + */ + private suspend fun awaitWallClock(untilSecs: Long, timeout: Duration) { + var left = timeout + while (left > Duration.ZERO) { + withTimeoutOrNull(left) { clockChecks.first() } ?: return + left = (untilSecs - nowSecs()).seconds + } + } + + /** + * Keeps [ReceiveUiState.nfcUri] at [invoice]'s request while that invoice is the one on screen, the wallet is + * ready and the invoice has not expired, by [expiresIn] set again from the wall clock (see [awaitWallClock]) + * and by the wall clock at every publish, and takes it away at the first of them that ends. A wallet that was + * not ready may have been paid meanwhile, so the request returns only after Spark's list was read and shows no + * payment; one it shows completes [paid]. + */ + private suspend fun offerTag( + invoice: ReceiveInvoice, + expiresIn: Duration, + paid: CompletableDeferred, + ) { + val uri = nfcPaymentUri(invoice.bolt11) ?: return + val qrContent = invoice.bolt11.uppercase() + fun set(value: String?) = _uiState.update { if (it.qrContent == qrContent) it.copy(nfcUri = value) else it } + var wasAway = false + try { + coroutineScope { + val offer = launch { + walletRepo.walletState.map { it.status == WalletStatus.Ready } + .distinctUntilChanged() + .collectLatest { isReady -> + if (!isReady) { + wasAway = true + set(null) + return@collectLatest + } + if (wasAway) { + // A list that cannot be read keeps the tag away until the wallet is ready anew. + val receipt = paymentsRepo.findPaid(invoice).getOrElse { return@collectLatest } + if (receipt != null) { + paid.complete(receipt) + return@collectLatest + } + wasAway = false + } + set(uri.takeIf { isCurrent(invoice.expiresAtSecs.toLong()) }) + } + } + awaitWallClock(untilSecs = invoice.expiresAtSecs.toLong(), timeout = expiresIn) + offer.cancel() + } + } finally { + set(null) } } @@ -152,6 +277,13 @@ class ReceiveViewModel internal constructor( data class ReceiveUiState( /** The uppercased invoice the QR shows, or null while there is none to show. */ val qrContent: String? = null, + /** + * The request of the invoice in [qrContent] as the watch's NFC tag offers it, `lightning:` and the invoice, or + * null while it must not be offered: the wallet is not ready, or the invoice expired. + */ + val nfcUri: String? = null, + /** When the invoice in [qrContent] expires, in epoch seconds. */ + val expiresAtSecs: Long? = null, val isLoading: Boolean = false, val isError: Boolean = false, /** What the paid invoice brought in, shown with the check. */ diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt index 37acb772ac..ea41fce6dc 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendScreen.kt @@ -38,6 +38,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.material3.EdgeButton import androidx.wear.compose.material3.EdgeButtonSize @@ -91,6 +92,11 @@ fun SendScreen( } } } + // A flow that left the back stack, as for a new link or tap, is stopped at once and pays nothing under QuickPay. + LifecycleStartEffect(viewModel) { + viewModel.onShownChange(true) + onStopOrDispose { viewModel.onShownChange(false) } + } LaunchedEffect(uiState.isBusy) { currentOnBusyChange(uiState.isBusy) } // A screen that leaves while busy must not leave the swipe to dismiss off for every other screen. DisposableEffect(Unit) { onDispose { currentOnBusyChange(false) } } @@ -115,6 +121,26 @@ fun SendScreen( ) } +/** + * What a tapped NFC tag without a payment request the watch takes ends on: one line and its close, as the send + * flow's own refusals, since Android already brought the app to the front for the tag. + */ +@Composable +fun TagRefusedScreen( + onClose: () -> Unit, + modifier: Modifier = Modifier, +) { + val haptic = LocalHapticFeedback.current + LaunchedEffect(Unit) { haptic.performHapticFeedback(HapticFeedbackType.Reject) } + Refusal( + icon = R.drawable.ic_close, + text = stringResource(R.string.send__error_unsupported), + textTag = "WatchTagRefused", + onCloseClick = onClose, + modifier = modifier + ) +} + @Composable private fun Content( uiState: SendUiState, @@ -593,6 +619,14 @@ private fun PreviewFailed() { } } +@WearPreviewDevices +@Composable +private fun PreviewTagRefused() { + WearPreview { + TagRefusedScreen(onClose = {}) + } +} + private val PreviewBitcoin = DisplayAmount(symbol = "₿", text = "21 000") private val PreviewReviewStep = SendStep.Review( diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt index 9dd15129bf..f3d022b949 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -52,10 +52,11 @@ import kotlin.time.Duration.Companion.seconds * QuickPay is asked only for a send the wearer is there for: one priced within [QUICKPAY_WINDOW] of its link, with * the app on screen, out of ambient mode and the watch unlocked all the while. A link that waited longer for the * wallet, as while it connects, or across a lock, a pause or ambient mode, always ends on the review and the hold, - * so nothing is ever paid long after the wearer looked away. A wallet that turns offline during that wait ends the - * flow as above, with no QuickPay and no review. Only the first flow of a link asks: one that Android - * builds again for the same link, as after the process was killed and the back stack restored, finds its mark in the - * saved state and ends on the review. + * so nothing is ever paid long after the wearer looked away. Nor is a flow whose screen is no longer shown, as + * one that a new link, tap or tile request just took off the back stack: it never pays unseen. A wallet that turns + * offline during that wait ends the flow as above, with no QuickPay and no review. Only the first flow of a link + * asks: one that Android builds again for the same link, as after the process was killed and the back stack + * restored, finds its mark in the saved state and ends on the review. */ @HiltViewModel class SendViewModel @Inject constructor( @@ -121,6 +122,13 @@ class SendViewModel @Inject constructor( @Volatile private var wasAway = savedStateHandle.get(KEY_STARTED) == true + /** + * Whether this flow's screen is shown: its back stack entry is started. A view model is made as its screen + * shows, and lives a moment longer than an entry that was popped: see [onShownChange]. + */ + @Volatile + private var isShown = true + /** Whether the wallet was seen out of [WalletStatus.Paused], which it may be in only while the app returns. */ private var hasLeftPause = false @@ -147,6 +155,14 @@ class SendViewModel @Inject constructor( } } + /** + * The screen's back stack entry started or stopped. A stopped one asks no QuickPay, so a flow that another + * request replaced cannot pay in the moment before its view model is cleared. + */ + fun onShownChange(isShown: Boolean) { + this.isShown = isShown + } + fun onAmountChange(text: String) { val digits = text.filter { it.isDigit() }.take(MAX_AMOUNT_DIGITS) _uiState.update { state -> @@ -240,10 +256,10 @@ class SendViewModel @Inject constructor( canQuickPay() && clock.nowMs() - arrivedAtMs in 0..QUICKPAY_WINDOW.inWholeMilliseconds /** - * Whether the wearer is there and the wallet is not offline, by its status now and by a request already - * dropped for it, which nothing pays later. + * Whether this flow is shown, the wearer is there and the wallet is not offline, by its status now and by a + * request already dropped for it, which nothing pays later. */ - private fun canQuickPay(): Boolean = isAttended() && + private fun canQuickPay(): Boolean = isShown && isAttended() && walletRepo.walletState.value.status != WalletStatus.Offline && _uiState.value.step !is SendStep.Offline diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index 6a019b9691..55d16e0af2 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -17,10 +17,13 @@ NFC متوقف غير متصل تبديل الوحدة + فتح إعدادات NFC + طلب دفع Bitkit استعادة تعذّر إنشاء الفاتورة رمز QR مخفي فاتورة جديدة + انقر للاستلام مدفوع إظهار رمز QR استلام diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml index 6c6cf80683..8d89adce01 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -17,10 +17,13 @@ NFC desactivado Sin conexión Cambiar unidad + Abrir ajustes de NFC + Solicitud de pago de Bitkit Restaurar No se creó la factura QR oculto Nueva factura + Toca para recibir Pagado Mostrar QR Recibir diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index 752d58a710..465e8bfeed 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -17,10 +17,13 @@ NFC desactivat Sense connexió Canvia la unitat + Obre la configuració de l\'NFC + Sol·licitud de pagament de Bitkit Restaurar No s\'ha creat la factura QR amagat Nova factura + Toca per rebre Pagat Mostra el QR Rebre diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index db62d4b208..af5ec6007c 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -17,10 +17,13 @@ NFC vypnuto Offline Přepnout jednotku + Otevřít nastavení NFC + Žádost o platbu Bitkit Obnovit Fakturu nelze vytvořit QR skryt Nová faktura + Klepnutím přijměte Zaplaceno Zobrazit QR Přijmout diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index c127f5e8d1..c6132523a1 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -17,10 +17,13 @@ NFC aus Offline Einheit wechseln + NFC-Einstellungen öffnen + Bitkit-Zahlungsanforderung Wiederherstellen Rechnung nicht erstellt QR versteckt Neue Rechnung + Zum Empfangen tippen Bezahlt QR anzeigen Empfangen diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index 2ff5822172..68cd83eccd 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -17,10 +17,13 @@ NFC ανενεργό Εκτός σύνδεσης Αλλαγή μονάδας + Άνοιγμα ρυθμίσεων NFC + Αίτημα πληρωμής Bitkit Επαναφορά Αποτυχία τιμολογίου QR κρυφό Νέο τιμολόγιο + Πατήστε για λήψη Πληρώθηκε Εμφάνιση QR Λήψη diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index ab02c5e19b..3010418c68 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -17,10 +17,13 @@ NFC desactivado Sin conexión Cambiar unidad + Abrir ajustes de NFC + Solicitud de pago de Bitkit Restaurar No se creó la factura QR oculto Nueva factura + Toca para recibir Pagado Mostrar QR Recibir diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index ab02c5e19b..3010418c68 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -17,10 +17,13 @@ NFC desactivado Sin conexión Cambiar unidad + Abrir ajustes de NFC + Solicitud de pago de Bitkit Restaurar No se creó la factura QR oculto Nueva factura + Toca para recibir Pagado Mostrar QR Recibir diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index 3302738046..f90a8d275a 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -17,10 +17,13 @@ NFC désactivé Hors ligne Changer d\'unité + Ouvrir les réglages NFC + Demande de paiement Bitkit Restaurer Facture non créée QR masqué Nouvelle facture + Touchez pour recevoir Payé Afficher le QR Recevoir diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index daee4e3424..c144316fcd 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -17,10 +17,13 @@ NFC disattivato Offline Cambia unità + Apri impostazioni NFC + Richiesta di pagamento Bitkit Ripristina Fattura non creata QR nascosto Nuova fattura + Tocca per ricevere Pagato Mostra QR Ricevi diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index 79a1d475ed..11452dc127 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -17,10 +17,13 @@ NFC uit Offline Eenheid wisselen + NFC-instellingen openen + Bitkit-betaalverzoek Herstellen Factuur niet gemaakt QR verborgen Nieuwe factuur + Tik om te ontvangen Betaald QR tonen Ontvangen diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index 3ce8962352..1f07f8843c 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -17,10 +17,13 @@ NFC wyłączone Offline Zmień jednostkę + Otwórz ustawienia NFC + Żądanie płatności Bitkit Odzyskaj Nie utworzono faktury QR ukryty Nowa faktura + Dotknij, aby odebrać Opłacono Pokaż QR Odbierz diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index 9496751b26..5c0b8a9e58 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -17,10 +17,13 @@ NFC desligado Sem conexão Alternar unidade + Abrir configurações de NFC + Solicitação de pagamento Bitkit Restaurar Invoice não criado QR oculto Novo invoice + Toque para receber Pago Mostrar QR Receber diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index c2c80f951c..6a2f1709b9 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -17,10 +17,13 @@ NFC desligado Sem ligação Alternar unidade + Abrir definições de NFC + Pedido de pagamento Bitkit Restaurar Fatura não criada QR oculto Nova fatura + Toque para receber Pago Mostrar QR Receber diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index c916fe53d7..41130d8c16 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -17,10 +17,13 @@ NFC выключен Нет сети Сменить единицу + Открыть настройки NFC + Запрос на оплату Bitkit Восстановить Счёт не создан QR скрыт Новый счёт + Коснитесь для получения Оплачено Показать QR Получить diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 380d38685d..539830f6fc 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -17,10 +17,13 @@ NFC off Offline Switch unit + Open NFC settings + Bitkit payment request Restore Couldn\'t create invoice QR hidden New invoice + Tap to receive Paid Show QR Receive diff --git a/wear/src/main/res/xml/ndef_tag_service.xml b/wear/src/main/res/xml/ndef_tag_service.xml new file mode 100644 index 0000000000..7a0df56656 --- /dev/null +++ b/wear/src/main/res/xml/ndef_tag_service.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/wear/src/test/java/to/bitkit/wear/data/SendMonitorTest.kt b/wear/src/test/java/to/bitkit/wear/data/SendMonitorTest.kt new file mode 100644 index 0000000000..c0d001115e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/SendMonitorTest.kt @@ -0,0 +1,44 @@ +package to.bitkit.wear.data + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SendMonitorTest { + private val sut = SendMonitor() + + @Test + fun `nothing is under way at first`() { + assertFalse(sut.isSending.value) + } + + @Test + fun `a send is under way from its begin to its end`() { + sut.begin() + assertTrue(sut.isSending.value) + + sut.end() + assertFalse(sut.isSending.value) + } + + @Test + fun `two sends are under way until both ended`() { + sut.begin() + sut.begin() + + sut.end() + assertTrue(sut.isSending.value) + + sut.end() + assertFalse(sut.isSending.value) + } + + @Test + fun `an end without a begin leaves nothing under way, and the next send counts`() { + sut.end() + assertFalse(sut.isSending.value) + + sut.begin() + assertTrue(sut.isSending.value) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NdefCodecTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NdefCodecTest.kt new file mode 100644 index 0000000000..1c2f0fce89 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NdefCodecTest.kt @@ -0,0 +1,116 @@ +// Copied from app/src/test/java/to/bitkit/nfc/NdefCodecTest.kt; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NdefCodecTest { + @Test + fun `encodes a short URI record without a prefix code`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbc1") + + val payload = byteArrayOf(0x00) + "lightning:lnbc1".toByteArray() + val expected = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'U'.code.toByte()) + payload + assertArrayEquals(expected, message) + } + + @Test + fun `encodes a long URI record with a 4-byte length`() { + val uri = "bitcoin:bc1q?lightning=" + "x".repeat(400) + + val message = NdefCodec.encodeUriMessage(uri) + + assertEquals(0xC1.toByte(), message[0]) + assertEquals(listOf(uri), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes the long URI record a Square Register serves`() { + val message = PosNfcFixtures.squareMessage() + + assertEquals(465, message.size) + assertArrayEquals( + PosNfcFixtures.hex(PosNfcFixtures.SQUARE_MESSAGE_START_HEX), + message.copyOf(18), + ) + assertEquals(listOf(PosNfcFixtures.SQUARE_URI), NdefCodec.decodeTexts(message)) + assertEquals(PosNfcFixtures.SQUARE_URI, NdefCodec.payableText(NdefCodec.decodeTexts(message))) + } + + @Test + fun `encodes a Square-sized request exactly as Square does`() { + assertArrayEquals(PosNfcFixtures.squareMessage(), NdefCodec.encodeUriMessage(PosNfcFixtures.SQUARE_URI)) + } + + @Test + fun `decodes the BIP 321 request Numo serves`() { + val message = PosNfcFixtures.squareMessage(PosNfcFixtures.BIP321_URI) + + assertEquals(listOf(PosNfcFixtures.BIP321_URI), NdefCodec.decodeTexts(message)) + } + + @Test + fun `round trips a URI record`() { + val uri = "bitcoin:BC1QTEST?amount=0.001&lightning=LNBC10U1P" + + assertEquals(listOf(uri), NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri))) + } + + @Test + fun `expands URI prefix codes`() { + val payload = byteArrayOf(0x04) + "example.com/lnurlp/alice".toByteArray() + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'U'.code.toByte()) + payload + + assertEquals(listOf("https://example.com/lnurlp/alice"), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes a UTF-8 text record`() { + val text = "bitcoin:?lightning=lnbc1&creq=creqA1" + val payload = byteArrayOf(0x02, 'e'.code.toByte(), 'n'.code.toByte()) + text.toByteArray() + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'T'.code.toByte()) + payload + + assertEquals(listOf(text), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes a UTF-16 text record`() { + val text = "lnbc1" + val header = byteArrayOf(0x82.toByte(), 'e'.code.toByte(), 'n'.code.toByte()) + val payload = header + text.toByteArray(Charsets.UTF_16) + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'T'.code.toByte()) + payload + + assertEquals(listOf(text), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes every record and skips unknown types`() { + val uri = NdefCodec.encodeUriMessage("lightning:lnbc1") + val mime = byteArrayOf(0x52, 0x0A, 0x01) + "text/plain".toByteArray() + byteArrayOf(0x41) + val firstRecord = byteArrayOf((uri[0].toInt() and 0xBF).toByte()) + uri.copyOfRange(1, uri.size) + + assertEquals(listOf("lightning:lnbc1"), NdefCodec.decodeTexts(firstRecord + mime)) + } + + @Test + fun `returns nothing for a truncated message`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbc1") + + assertTrue(NdefCodec.decodeTexts(message.copyOf(message.size - 3)).isEmpty()) + } + + @Test + fun `payable text is the single distinct request`() { + assertEquals("lightning:lnbc1", NdefCodec.payableText(listOf(" lightning:lnbc1 ", "lightning:lnbc1", ""))) + } + + @Test + fun `payable text is null for no or conflicting requests`() { + assertNull(NdefCodec.payableText(emptyList())) + assertNull(NdefCodec.payableText(listOf(" "))) + assertNull(NdefCodec.payableText(listOf("lightning:lnbc1", "lightning:lnbc2"))) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcPaymentUriTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcPaymentUriTest.kt new file mode 100644 index 0000000000..34b4a592ec --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcPaymentUriTest.kt @@ -0,0 +1,167 @@ +// Copied from app/src/test/java/to/bitkit/nfc/NfcPaymentUriTest.kt; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class NfcPaymentUriTest { + @Test + fun `keeps requests that already have a payment scheme`() { + assertEquals("bitcoin:bc1q?lightning=lnbc1", nfcPaymentUri("bitcoin:bc1q?lightning=lnbc1")) + assertEquals("BITCOIN:BC1Q", nfcPaymentUri("BITCOIN:BC1Q")) + assertEquals("lightning:lnbc1", nfcPaymentUri("lightning:lnbc1")) + assertEquals("ethereum:0xabc@42161/transfer", nfcPaymentUri("ethereum:0xabc@42161/transfer")) + assertEquals("LIGHTNING:LNTBS1P", nfcPaymentUri("LIGHTNING:LNTBS1P")) + } + + @Test + fun `adds lightning to bare lightning requests`() { + assertEquals("lightning:lnbc10u1p", nfcPaymentUri("lnbc10u1p")) + assertEquals("lightning:lnbcrt1p", nfcPaymentUri(" lnbcrt1p ")) + assertEquals("lightning:LNURL1DP68", nfcPaymentUri("LNURL1DP68")) + } + + @Test + fun `adds bitcoin to bare addresses`() { + assertEquals("bitcoin:bc1qxyz", nfcPaymentUri("bc1qxyz")) + } + + @Test + fun `returns null for no request`() { + assertNull(nfcPaymentUri(null)) + assertNull(nfcPaymentUri(" ")) + } + + @Test + fun `keeps a Square request for the scanner`() { + assertEquals(PosNfcFixtures.SQUARE_URI, scannedPaymentRequest(PosNfcFixtures.SQUARE_URI)) + assertEquals("LIGHTNING:LNTBS1P", scannedPaymentRequest(" LIGHTNING:LNTBS1P\n")) + } + + @Test + fun `turns a BIP 321 request without an address into its Lightning request`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + + assertEquals("lightning:$invoice", scannedPaymentRequest(PosNfcFixtures.BIP321_URI)) + assertEquals("lightning:$invoice", scannedPaymentRequest("BITCOIN:?LIGHTNING=$invoice")) + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.0000799&lightning=$invoice&creq=x")) + } + + @Test + fun `keeps other bitcoin requests unchanged`() { + val unified = "bitcoin:bc1qtest?lightning=lnbc1" + + assertEquals(unified, scannedPaymentRequest(unified)) + assertEquals("bitcoin:?amount=0.001", scannedPaymentRequest("bitcoin:?amount=0.001")) + assertEquals("bitcoin:?lightning=", scannedPaymentRequest("bitcoin:?lightning=")) + assertEquals("bitcoin:?lno=lno1qgsq", scannedPaymentRequest("bitcoin:?lno=lno1qgsq")) + } + + @Test + fun `request repeating a parameter is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + for (repeated in listOf( + "bitcoin:?lightning=$invoice&amount=0.01&AMOUNT=0.02", + "bitcoin:?lightning=$invoice&lightning=lnbc1other", + "bitcoin:?lightning=$invoice&label=a&label=b", + "bitcoin:?lightning=$invoice&message=a&message=b", + "bitcoin:?lightning=$invoice&amount=0.0000799&amount=0.0000799", + "bitcoin:?lightning=$invoice&pop=a%3a&POP=b%3a", + )) { + assertEquals(repeated, scannedPaymentRequest(repeated)) + } + } + + @Test + fun `request repeating an optional extension is unwrapped`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals( + "lightning:$invoice", + scannedPaymentRequest("bitcoin:?lightning=$invoice&x-shop=a&X-SHOP=b&creq=c&creq=d&lno=lno1a&lno=lno1b"), + ) + } + + @Test + fun `request whose amount the invoice does not carry is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.0000799&lightning=$invoice")) + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.00007990&lightning=$invoice")) + for (kept in listOf( + "bitcoin:?amount=0.0001&lightning=$invoice", + "bitcoin:?amount=0.0001&lightning=lnbcrt1pamountless", + "bitcoin:?amount=abc&lightning=$invoice", + "bitcoin:?amount=0.0000799,50&lightning=$invoice", + "bitcoin:?amount=0.0000799BTC&lightning=$invoice", + "bitcoin:?amount=7.99E-5&lightning=$invoice", + "bitcoin:?amount=+0.0000799&lightning=$invoice", + )) { + assertEquals(kept, scannedPaymentRequest(kept)) + } + } + + @Test + fun `nfc read with a required parameter is refused`() { + assertNull(nfcPaymentRequest("bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a")) + assertNull(nfcPaymentRequest("BITCOIN:BCRT1QTEST?REQ-FOO=bar")) + // The scanner strips `lightning:` before decoding, so a wrapped Bitcoin request is checked as one. + assertNull(nfcPaymentRequest("lightning:bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a")) + val wrappedInvoice = "LIGHTNING:bitcoin:?lightning=${PosNfcFixtures.SQUARE_INVOICE}&req-pop=callback%3a" + assertNull(nfcPaymentRequest(wrappedInvoice)) + val required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=callback" + for (wrapper in listOf("bitkit://", "bitkit://lightning:", "lightning:lightning:", "lnurl:lightning:")) { + assertNull(nfcPaymentRequest("$wrapper$required")) + } + val wrappedPlain = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + assertEquals(wrappedPlain, nfcPaymentRequest(wrappedPlain)) + val lnurlPay = "https://pay.example.com/lnurlp?req-x=1&lightning=LNURL1DP68GURN8GHJ7" + assertEquals(lnurlPay, nfcPaymentRequest(lnurlPay)) + assertEquals("bitcoin:bcrt1qtest?amount=0.001", nfcPaymentRequest(" bitcoin:bcrt1qtest?amount=0.001 ")) + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals("lightning:$invoice", nfcPaymentRequest("bitcoin:?lightning=$invoice")) + } + + @Test + fun `nfc read with a required parameter behind an inner bitkit scheme is refused`() { + // The decoder deletes every `bitkit://` in a deep link, which can turn a key into `req-`. + val address = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + assertNull(nfcPaymentRequest("$address&bitkit://req-pop=callback")) + assertNull(nfcPaymentRequest("$address&rebitkit://q-pop=callback")) + // The decoder deletes only lowercase `bitkit://`, so a mixed-case one stays part of an optional key. + val mixedCase = "bitkit://bitkit://bitcoin:bcrt1qtest?REBITKIT://Q-POP=callback" + assertEquals(mixedCase, nfcPaymentRequest(mixedCase)) + val optional = "bitkit://bitcoin:bcrt1qtest?amount=0.001&reBitkit://q-x=1" + assertEquals(optional, nfcPaymentRequest(optional)) + // The decoder deletes them again while the text starts with `bitkit://`, so a nested one is removed too. + val required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=x" + assertNull(nfcPaymentRequest("bitkit://bitbitkit://kit://$required")) + assertNull(nfcPaymentRequest("bitkit://lightning:bitbitkit://kit://$required")) + // Once the text starts with `bitcoin:` the decoder deletes nothing more, so this key is not `req-`. + val payable = "bitcoin:bcrt1qtest?amount=0.001&bitbitkit://kit://req-pop=x" + assertEquals(payable, nfcPaymentRequest(payable)) + assertEquals("bitkit://$payable", nfcPaymentRequest("bitkit://$payable")) + // The decoder's trim also removes U+0085 (NEL), which Kotlin's `trim()` keeps. + assertNull(nfcPaymentRequest("\u0085$required")) + assertNull(nfcPaymentRequest("bitkit://\u0085$required")) + } + + @Test + fun `request with an empty amount is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + for (empty in listOf("bitcoin:?amount=&lightning=$invoice", "bitcoin:?lightning=$invoice&amount")) { + assertEquals(empty, scannedPaymentRequest(empty)) + } + } + + @Test + fun `request with a required parameter is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + val required = "bitcoin:?lightning=$invoice&req-pop=callback%3a" + assertEquals(required, scannedPaymentRequest(required)) + val uppercase = "BITCOIN:?REQ-FOO=bar&LIGHTNING=$invoice" + assertEquals(uppercase, scannedPaymentRequest(uppercase)) + for (empty in listOf("bitcoin:?lightning=$invoice&req-foo=", "bitcoin:?lightning=$invoice&req-foo")) { + assertEquals(empty, scannedPaymentRequest(empty)) + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcTagEmitterTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagEmitterTest.kt new file mode 100644 index 0000000000..62c346a3e6 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagEmitterTest.kt @@ -0,0 +1,54 @@ +// Copied from app/src/test/java/to/bitkit/nfc/NfcTagEmitterTest.kt, with the revoke cases added; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NfcTagEmitterTest { + private val tokens = mutableListOf() + + @After + fun tearDown() { + tokens.forEach { NfcTagEmitter.clear(it) } + } + + @Test + fun `serves the published request until its owner clears it`() { + val token = NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc1"), NfcTagEmitter.currentMessage()) + assertTrue(NfcTagEmitter.clear(token)) + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `an older publisher cannot clear a newer request`() { + val first = NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + NfcTagEmitter.publish("lightning:lnbc2").also(tokens::add) + + assertFalse(NfcTagEmitter.clear(first)) + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc2"), NfcTagEmitter.currentMessage()) + } + + @Test + fun `a revoked request is served no more, whoever published it`() { + NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + + NfcTagEmitter.revoke() + + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `revoking while nothing is published leaves the next request alone`() { + NfcTagEmitter.revoke() + + NfcTagEmitter.publish("lightning:lnbc2").also(tokens::add) + + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc2"), NfcTagEmitter.currentMessage()) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcTagOfferTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagOfferTest.kt new file mode 100644 index 0000000000..8239862be8 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcTagOfferTest.kt @@ -0,0 +1,153 @@ +package to.bitkit.wear.nfc + +import org.junit.After +import org.junit.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class NfcTagOfferTest { + private val route = FakeTagRoute() + private val sut = NfcTagOffer(route) + private val reader = Type4TagEmulator(NfcTagEmitter::currentMessage) + + @After + fun tearDown() { + sut.stop() + } + + @Test + fun `nothing is offered before start`() { + assertFalse(sut.isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertNull(read()) + } + + @Test + fun `a started offer serves its request to a reader, as one uri record`() { + assertTrue(sut.start(URI)) + + assertTrue(sut.isOffered) + assertEquals(1, route.opens) + assertContentEquals(NdefCodec.encodeUriMessage(URI), NfcTagEmitter.currentMessage()) + assertEquals(listOf(URI), read()) + } + + @Test + fun `a stopped offer serves nothing and closes the route`() { + sut.start(URI) + + sut.stop() + + assertFalse(sut.isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertNull(read()) + assertEquals(1, route.closes) + } + + @Test + fun `a reader that selected the tag is served nothing more once the offer stops`() { + sut.start(URI) + reader.process(SELECT_APP) + reader.process(SELECT_NDEF) + + sut.stop() + + assertContentEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, reader.process(READ_LENGTH)) + } + + @Test + fun `an offer whose route cannot be opened publishes nothing`() { + route.canOpen = false + + assertFalse(sut.start(URI)) + + assertFalse(sut.isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertEquals(0, route.closes) + } + + @Test + fun `starting again replaces the request`() { + sut.start(URI) + + assertTrue(sut.start(OTHER_URI)) + + assertEquals(listOf(OTHER_URI), read()) + sut.stop() + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `stopping twice closes the route once`() { + sut.start(URI) + + sut.stop() + sut.stop() + + assertEquals(1, route.closes) + } + + @Test + fun `an older offer that stops leaves a newer one, and its route, alone`() { + val newerRoute = FakeTagRoute() + val newer = NfcTagOffer(newerRoute) + sut.start(URI) + newer.start(OTHER_URI) + + sut.stop() + + assertEquals(0, route.closes) + assertEquals(listOf(OTHER_URI), read()) + newer.stop() + assertEquals(1, newerRoute.closes) + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `a revoked request is served no more, and its offer still closes the route when it stops`() { + sut.start(URI) + + NfcTagEmitter.revoke() + assertNull(read()) + + sut.stop() + assertEquals(1, route.closes) + } + + /** What a reader gets from the tag over the standard read sequence, or null when it finds no tag. */ + private fun read(): List? { + reader.reset() + if (!reader.process(SELECT_APP).contentEquals(Type4TagEmulator.SW_OK)) return null + if (!reader.process(SELECT_NDEF).contentEquals(Type4TagEmulator.SW_OK)) return null + val length = reader.process(READ_LENGTH) + val size = ((length[0].toInt() and 0xFF) shl 8) or (length[1].toInt() and 0xFF) + val message = reader.process(byteArrayOf(0x00, 0xB0.toByte(), 0x00, 0x02, size.toByte())).copyOf(size) + return NdefCodec.decodeTexts(message) + } + + private class FakeTagRoute : TagRoute { + var canOpen = true + var opens = 0 + var closes = 0 + + override fun open(): Boolean { + opens++ + return canOpen + } + + override fun close() { + closes++ + } + } + + private companion object { + const val URI = "lightning:lnbcrt1invoice" + const val OTHER_URI = "lightning:lnbcrt1other" + val SELECT_APP = byteArrayOf(0x00, 0xA4.toByte(), 0x04, 0x00, 0x07) + Type4TagEmulator.NDEF_AID + 0x00 + val SELECT_NDEF = byteArrayOf(0x00, 0xA4.toByte(), 0x00, 0x0C, 0x02, 0xE1.toByte(), 0x04) + val READ_LENGTH = byteArrayOf(0x00, 0xB0.toByte(), 0x00, 0x00, 0x02) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/NfcTapFilterTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/NfcTapFilterTest.kt new file mode 100644 index 0000000000..f34e0abda2 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/NfcTapFilterTest.kt @@ -0,0 +1,59 @@ +package to.bitkit.wear.nfc + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class NfcTapFilterTest { + private var time = 0L + private val sut = NfcTapFilter { time } + + @Test + fun `the filter is one for the process, so a repeat is dropped whichever activity it reaches`() { + assertTrue(NfcTapFilter::class.java.isAnnotationPresent(javax.inject.Singleton::class.java)) + } + + @Test + fun `the first tap is new`() { + assertTrue(sut.isNew(REQUEST)) + } + + @Test + fun `the same request again within the window is a repeat`() { + sut.isNew(REQUEST) + time += NfcTapFilter.REPEAT_WINDOW.inWholeMilliseconds - 1 + + assertFalse(sut.isNew(REQUEST)) + } + + @Test + fun `a watch held on the tag keeps getting repeats, however long`() { + sut.isNew(REQUEST) + repeat(20) { + time += 1_000 + assertFalse(sut.isNew(REQUEST)) + } + } + + @Test + fun `the same request is a new tap once the window passed without it`() { + sut.isNew(REQUEST) + time += 1_000 + sut.isNew(REQUEST) + time += NfcTapFilter.REPEAT_WINDOW.inWholeMilliseconds + + assertTrue(sut.isNew(REQUEST)) + } + + @Test + fun `another request is a new tap at once`() { + sut.isNew(REQUEST) + + assertTrue(sut.isNew("lightning:lnbcrt1other")) + assertTrue(sut.isNew(REQUEST)) + } + + private companion object { + const val REQUEST = "lightning:lnbcrt1invoice" + } +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/PosNfcFixtures.kt b/wear/src/test/java/to/bitkit/wear/nfc/PosNfcFixtures.kt new file mode 100644 index 0000000000..826c15eaf0 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/PosNfcFixtures.kt @@ -0,0 +1,37 @@ +// Copied from app/src/test/java/to/bitkit/nfc/PosNfcFixtures.kt; keep both in sync. +package to.bitkit.wear.nfc + +import java.nio.ByteBuffer + +/** + * 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. [SQUARE_INVOICE] is a real signet invoice of the size Square serves: + * its message is 465 bytes and starts like Square's. + */ +object PosNfcFixtures { + const val SQUARE_INVOICE = + "LNTBS79900N1P4TZWUQD962DCH2CTJV5S9YET8D9EHGETJYP8YVSEQWFJKWUN9WDEKJMMWYPNXJ7R5W4EX2GZNW96KZUN9YPFX2E" + + "MFWD6X2U3QFERYXGRJV4NHYETNWD5K7M3QVE5HSAR4WFJJQ5M3W4SHYEFQ2FJKW6TNW3JHYGZWGEPJQUN9VAEX2UMND9HKUGRXD9" + + "U8GATJV5PP5QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSSP5PYYSJZGFPYYSJZGFPYYSJZGFPYYSJZGFPY" + + "YSJZGFPYYSJZGFPYYS9QRSGQXQ97ZVUQCQZYSKUAHP9D6GKX2H8ERFH5E9NZZ52SY0UFR2F6VGK43QEJ0ZJU7FTYQYJTQE8705R2" + + "KM9QS5NYFM3ZPR330ML3S3HWJP5D0RERD49QGT5CPUXAWEL" + const val SQUARE_URI = "lightning:$SQUARE_INVOICE" + const val BIP321_URI = "bitcoin:?lightning=$SQUARE_INVOICE" + + /** The first bytes of Square's NDEF message: long URI record, 0x1CA-byte payload, code 0x00, `lightning:`. */ + const val SQUARE_MESSAGE_START_HEX = "C1010000 01CA 55 00 6C696768746E696E673A" + + /** Square's NDEF message, built by hand from the record layout rather than by [NdefCodec]. */ + fun squareMessage(uri: String = SQUARE_URI): ByteArray { + val payload = byteArrayOf(0x00) + uri.toByteArray(Charsets.US_ASCII) + val lengthBytes = ByteBuffer.allocate(Int.SIZE_BYTES).putInt(payload.size).array() + val header = byteArrayOf(0xC1.toByte(), 0x01) + lengthBytes + byteArrayOf(0x55) + return header + payload + } + + fun hex(value: String): ByteArray = + value.replace(" ", "").chunked(2).map { it.toInt(16).toByte() }.toByteArray() +} diff --git a/wear/src/test/java/to/bitkit/wear/nfc/Type4TagEmulatorTest.kt b/wear/src/test/java/to/bitkit/wear/nfc/Type4TagEmulatorTest.kt new file mode 100644 index 0000000000..8b78f873f3 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/nfc/Type4TagEmulatorTest.kt @@ -0,0 +1,139 @@ +// Copied from app/src/test/java/to/bitkit/nfc/Type4TagEmulatorTest.kt; keep both in sync. +package to.bitkit.wear.nfc + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test + +class Type4TagEmulatorTest { + private var message: ByteArray? = NdefCodec.encodeUriMessage("lightning:lnbc1") + private val sut = Type4TagEmulator { message } + + private val selectApp = hex("00A4040007D276000085010100") + private val selectCc = hex("00A4000C02E103") + private val selectNdef = hex("00A4000C02E104") + + @Test + fun `serves the NDEF message through the standard read sequence`() { + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectApp)) + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectCc)) + assertArrayEquals(hex("000F20003B00340406E104100000FF9000"), sut.process(hex("00B000000F"))) + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectNdef)) + + val expected = requireNotNull(message) + val lengthResponse = sut.process(hex("00B0000002")) + assertArrayEquals(byteArrayOf(0x00, expected.size.toByte()) + Type4TagEmulator.SW_OK, lengthResponse) + + val read = readNdef(offset = 2, total = expected.size) + assertArrayEquals(expected, read) + } + + @Test + fun `reads a long message in chunks`() { + message = NdefCodec.encodeUriMessage("bitcoin:bc1q?lightning=" + "x".repeat(700)) + sut.process(selectApp) + sut.process(selectNdef) + + val expected = requireNotNull(message) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size)) + } + + @Test + fun `serves a Square-sized request to a reader looping over offsets`() { + message = NdefCodec.encodeUriMessage(PosNfcFixtures.SQUARE_URI) + sut.process(selectApp) + sut.process(selectNdef) + + val expected = requireNotNull(message) + assertArrayEquals(hex("01D1") + Type4TagEmulator.SW_OK, sut.process(hex("00B0000002"))) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size)) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size, chunk = 0xFF)) + assertEquals(listOf(PosNfcFixtures.SQUARE_URI), NdefCodec.decodeTexts(expected)) + } + + @Test + fun `presents no tag when nothing is published`() { + message = null + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectApp)) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00B0000002"))) + } + + @Test + fun `refuses files before the application is selected`() { + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectCc)) + } + + @Test + fun `refuses other applications`() { + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00A4040007A000000003101000"))) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectCc)) + } + + @Test + fun `keeps serving the message selected for this tap`() { + sut.process(selectApp) + sut.process(selectNdef) + val first = requireNotNull(message) + message = NdefCodec.encodeUriMessage("lightning:lnbc2") + + assertArrayEquals(first, readNdef(offset = 2, total = first.size)) + } + + @Test + fun `stops serving once nothing is published`() { + sut.process(selectApp) + sut.process(selectNdef) + message = null + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00B0000002"))) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + } + + @Test + fun `is read-only`() { + sut.process(selectApp) + sut.process(selectNdef) + + assertArrayEquals(Type4TagEmulator.SW_SECURITY_NOT_SATISFIED, sut.process(hex("00D60000020000"))) + } + + @Test + fun `rejects malformed and unsupported commands`() { + assertArrayEquals(Type4TagEmulator.SW_WRONG_LENGTH, sut.process(hex("00A4"))) + assertArrayEquals(Type4TagEmulator.SW_CLA_NOT_SUPPORTED, sut.process(hex("80A4040000"))) + assertArrayEquals(Type4TagEmulator.SW_INS_NOT_SUPPORTED, sut.process(hex("00CA000000"))) + } + + @Test + fun `reset forgets the selection`() { + sut.process(selectApp) + sut.reset() + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + } + + private fun readNdef(offset: Int, total: Int, chunk: Int = MAX_READ): ByteArray { + var result = byteArrayOf() + var position = offset + while (result.size < total) { + val length = minOf(chunk, total - result.size) + val response = sut.process( + byteArrayOf(0x00, 0xB0.toByte(), (position shr 8).toByte(), position.toByte(), length.toByte()) + ) + assertArrayEquals(Type4TagEmulator.SW_OK, response.copyOfRange(response.size - 2, response.size)) + val chunk = response.copyOfRange(0, response.size - 2) + assertEquals(length, chunk.size) + result += chunk + position += chunk.size + } + return result + } + + private fun hex(value: String): ByteArray = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + + private companion object { + const val MAX_READ = 0x3B + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index a06071d199..a40548ebd3 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.wear.repositories +import android.nfc.NfcAdapter import breez_sdk_spark.FeePolicy import breez_sdk_spark.Payment import breez_sdk_spark.PaymentStatus @@ -35,6 +36,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.wear.data.FakeOwnInvoiceStore import to.bitkit.wear.data.FakeUncertainSendStore +import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.UncertainSend import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.PreparedSend @@ -42,6 +44,8 @@ import to.bitkit.wear.models.ReceiveError import to.bitkit.wear.models.ReceiveInvoice import to.bitkit.wear.models.SendError import to.bitkit.wear.models.SendRequest +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentUri import to.bitkit.wear.services.InputDecoder import to.bitkit.wear.services.SparkError import to.bitkit.wear.services.SparkFixtures @@ -58,6 +62,7 @@ import to.bitkit.wear.services.SparkSync import to.bitkit.wear.services.WalletSelfSendGuard import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.LaunchRequest import java.math.BigInteger import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -83,6 +88,7 @@ class PaymentsRepoTest : BaseUnitTest() { private val uncertainSends = FakeUncertainSendStore() private val decoder = FakeInputDecoder() private val quickPayRepo = mock() + private val sendMonitor = SendMonitor() private lateinit var sut: PaymentsRepo @@ -106,6 +112,7 @@ class PaymentsRepoTest : BaseUnitTest() { ownInvoices, uncertainSends, quickPayRepo, + sendMonitor, ) } @@ -120,6 +127,7 @@ class PaymentsRepoTest : BaseUnitTest() { ownInvoices, uncertainSends, quickPayRepo, + sendMonitor, ) } @@ -191,6 +199,24 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals("paid", sut.awaitPaid(invoice()).id) } + @Test + fun `an invoice's payment is found in spark's list, and none when it lists none`() = test { + assertNull(sut.findPaid(invoice()).getOrThrow()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(receipt("other", paymentHash = "ff".repeat(32)), receipt("paid"))) + + assertEquals("paid", sut.findPaid(invoice()).getOrThrow()?.id) + } + + @Test + fun `a list that cannot be read is no answer about an invoice's payment`() = test { + whenever(sparkService.listPayments(anyOrNull())) + .doSuspendableAnswer { throw SdkException.NetworkException("reset") } + + assertTrue(sut.findPaid(invoice()).isFailure) + } + @Test fun `waiting for an invoice reads spark's list again after a sync`() = test { val paid = async { sut.awaitPaid(invoice()) } @@ -352,6 +378,25 @@ class PaymentsRepoTest : BaseUnitTest() { verify(sparkService, never()).prepareSend(any(), anyOrNull()) } + @Test + fun `the watch's own receive invoice, read back from its nfc tag, is refused and never priced`() = test { + whenever(sparkService.receiveBolt11(null, "", PaymentsRepo.INVOICE_EXPIRY_SECS)).thenReturn(BOLT11) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + val invoice = sut.createInvoice().getOrThrow() + // The tag as the receive QR offers it, and as a tap on it reaches the send flow. + val uri = nfcPaymentUri(invoice.bolt11)!! + val tapped = LaunchRequest.from( + NfcAdapter.ACTION_NDEF_DISCOVERED, + data = uri, + open = null, + tagTexts = NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri)), + ) + val input = assertIs(tapped).input + + assertIs(sut.parse(input).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull()) + } + @Test fun `an invoice read before the wallet was ready is still refused before it is priced`() = test { decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) @@ -1112,6 +1157,31 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals(noted, uncertainSends.sends.keys) } + @Test + fun `a send is under way for the whole process until it ends, also after its caller is cancelled`() = test { + val release = CompletableDeferred() + whenever(sparkService.send(any(), any())).doSuspendableAnswer { release.await() } + assertFalse(sendMonitor.isSending.value) + val caller = launch { sut.send(preparedSend()) } + assertTrue(sendMonitor.isSending.value) + + caller.cancel() + assertTrue(sendMonitor.isSending.value) + + release.complete(payment("key-0", PaymentStatus.COMPLETED)) + assertFalse(sendMonitor.isSending.value) + } + + @Test + fun `a send that is refused is no longer under way`() = test { + val prepared = preparedSend() + walletState.update { it.copy(status = WalletStatus.Offline) } + + assertIs(sut.send(prepared).exceptionOrNull()) + + assertFalse(sendMonitor.isSending.value) + } + @Test fun `a send goes on and is settled after its caller is cancelled`() = test { val release = CompletableDeferred() diff --git a/wear/src/test/java/to/bitkit/wear/security/Fakes.kt b/wear/src/test/java/to/bitkit/wear/security/Fakes.kt index 2a9e957b88..d8c9b834de 100644 --- a/wear/src/test/java/to/bitkit/wear/security/Fakes.kt +++ b/wear/src/test/java/to/bitkit/wear/security/Fakes.kt @@ -38,8 +38,9 @@ class FakeNetworkMonitor(isOnline: Boolean = true) : NetworkMonitor { override val isOnline = MutableStateFlow(isOnline) } -class FakeNfcMonitor(state: NfcState = NfcState.On) : NfcMonitor { +class FakeNfcMonitor(state: NfcState = NfcState.On, hasCardEmulation: Boolean = true) : NfcMonitor { override val state = MutableStateFlow(state) + override val hasCardEmulation = MutableStateFlow(hasCardEmulation) } class FakeDeviceLock( diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt new file mode 100644 index 0000000000..bb701336e5 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt @@ -0,0 +1,96 @@ +package to.bitkit.wear.ui + +import org.junit.Test +import to.bitkit.wear.data.SendMonitor +import to.bitkit.wear.nfc.NfcTapFilter +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** What a link or a tapped tag may open, decided for the process and not for one activity. */ +class LaunchGateTest { + private var time = 0L + private val sendMonitor = SendMonitor() + private val sut = LaunchGate(NfcTapFilter { time }, sendMonitor) + + @Test + fun `a link and the tile's request pass`() { + assertEquals(SEND, sut.admit(SEND)) + assertEquals(LaunchRequest.Receive, sut.admit(LaunchRequest.Receive)) + assertNull(sut.admit(null)) + } + + @Test + fun `a link is never taken for the repeat of a tap`() { + assertEquals(SEND, sut.admit(SEND, isTap = true)) + + assertEquals(SEND, sut.admit(SEND)) + assertEquals(SEND, sut.admit(SEND)) + } + + @Test + fun `a tapped tag passes once, and its repeats are dropped whichever activity asks`() { + assertEquals(SEND, sut.admit(SEND, isTap = true)) + + // The gate holds no activity's state: a second activity instance asks the same gate. + repeat(5) { + time += 1_000 + assertNull(sut.admit(SEND, isTap = true)) + } + } + + @Test + fun `the same tag tapped again after the window passes`() { + sut.admit(SEND, isTap = true) + time += NfcTapFilter.REPEAT_WINDOW.inWholeMilliseconds + + assertEquals(SEND, sut.admit(SEND, isTap = true)) + } + + @Test + fun `another tag passes at once`() { + sut.admit(SEND, isTap = true) + + assertEquals(OTHER, sut.admit(OTHER, isTap = true)) + } + + @Test + fun `nothing passes while a send is under way, and it passes again afterwards`() { + sendMonitor.begin() + + assertNull(sut.admit(SEND)) + assertNull(sut.admit(LaunchRequest.Receive)) + assertNull(sut.admit(OTHER, isTap = true)) + assertNull(sut.admit(null, isTap = true, tapData = "lnurlw:abc")) + + sendMonitor.end() + assertEquals(SEND, sut.admit(SEND)) + } + + @Test + fun `a tag dropped during a send stays dropped while the watch rests on it after the send`() { + sendMonitor.begin() + assertNull(sut.admit(SEND, isTap = true)) + sendMonitor.end() + + time += 1_000 + assertNull(sut.admit(SEND, isTap = true)) + } + + @Test + fun `a tag without a payment request the watch takes asks for its refusal, once`() { + assertEquals(LaunchRequest.TagRefused, sut.admit(null, isTap = true, tapData = "lnurlw:abc")) + + time += 1_000 + assertNull(sut.admit(null, isTap = true, tapData = "lnurlw:abc")) + } + + @Test + fun `a tag's intent never opens the receive qr`() { + assertEquals(LaunchRequest.TagRefused, sut.admit(LaunchRequest.Receive, isTap = true)) + } + + private companion object { + val SEND = LaunchRequest.Send("lightning:lnbcrt1invoice") + val OTHER = LaunchRequest.Send("lightning:lnbcrt1other") + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt index f1c5d31f74..5a7756cfe8 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -1,7 +1,10 @@ package to.bitkit.wear.ui import android.content.Intent +import android.nfc.NfcAdapter import org.junit.Test +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentUri import kotlin.test.assertEquals import kotlin.test.assertNull @@ -46,4 +49,92 @@ class LaunchRequestTest { assertNull(LaunchRequest.from(Intent.ACTION_VIEW, link, open = null), link) } } + + // region nfc tag + + @Test + fun `a tapped tag asks for a send of its payment request`() { + val links = listOf( + "lightning:lnbcrt1abc", + "bitcoin:bcrt1q?lightning=lnbcrt1abc", + "lnurl:lnurl1abc", + "lnurlp://pay.example/lnurlp/satoshi", + "spark:sprt1abc", + ) + for (link in links) { + assertEquals(LaunchRequest.Send(link), fromTag(data = link), link) + assertEquals(LaunchRequest.Send(link), fromTag(data = link, texts = listOf(link)), link) + } + } + + @Test + fun `a tag is read from its records when the intent carries them, not from the intent's data`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbcrt1abc") + + val request = fromTag(data = "lightning:lnbcrt1other", texts = NdefCodec.decodeTexts(message)) + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), request) + } + + @Test + fun `the tag another bitkit offers for its receive invoice asks for a send of that invoice`() { + val uri = nfcPaymentUri("lnbcrt1abc")!! + val tag = NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri)) + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), fromTag(data = uri, texts = tag)) + } + + @Test + fun `a bip321 tag without an address asks for a send of its lightning invoice`() { + val uri = "bitcoin:?lightning=lnbcrt1abc" + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), fromTag(data = uri, texts = listOf(uri))) + } + + @Test + fun `a tag whose records repeat one request asks for it once`() { + val texts = listOf("lightning:lnbcrt1abc", " lightning:lnbcrt1abc ") + + assertEquals(LaunchRequest.Send("lightning:lnbcrt1abc"), fromTag(data = texts.first(), texts = texts)) + } + + @Test + fun `a tag with several different requests asks for nothing`() { + val texts = listOf("lightning:lnbcrt1abc", "lightning:lnbcrt1other") + + assertNull(fromTag(data = texts.first(), texts = texts)) + } + + @Test + fun `a tag whose request has a required parameter asks for nothing`() { + val uri = "bitcoin:bcrt1q?lightning=lnbcrt1abc&req-pop=callback" + + assertNull(fromTag(data = uri)) + assertNull(fromTag(data = uri, texts = listOf(uri))) + } + + @Test + fun `a tag with no readable record, or with another kind of link, asks for nothing`() { + assertNull(fromTag(data = "lightning:lnbcrt1abc", texts = emptyList())) + assertNull(fromTag(data = null)) + assertNull(fromTag(data = "https://bitkit.to", texts = listOf("https://bitkit.to"))) + assertNull(fromTag(data = "lnurlw://pay.example/withdraw")) + assertNull(fromTag(data = "lightning:lnbcrt1abc", texts = listOf("Coffee"))) + } + + @Test + fun `the tile's extra wins over a tag`() { + val request = LaunchRequest.from( + NfcAdapter.ACTION_NDEF_DISCOVERED, + data = "lightning:lnbcrt1abc", + open = LaunchRequest.OPEN_RECEIVE, + ) + + assertEquals(LaunchRequest.Receive, request) + } + + // endregion + + private fun fromTag(data: String?, texts: List? = null) = + LaunchRequest.from(NfcAdapter.ACTION_NDEF_DISCOVERED, data, open = null, tagTexts = texts) } diff --git a/wear/src/test/java/to/bitkit/wear/ui/components/NfcTagEffectTest.kt b/wear/src/test/java/to/bitkit/wear/ui/components/NfcTagEffectTest.kt new file mode 100644 index 0000000000..31215dc008 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/components/NfcTagEffectTest.kt @@ -0,0 +1,193 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.lifecycle.Lifecycle +import org.junit.After +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.NfcTagEmitter +import to.bitkit.wear.nfc.TagRoute +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** The tag is offered only while its screen is resumed with a request, and stopped on every way out. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class NfcTagEffectTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + private val route = FakeRoute() + private var uri by mutableStateOf(URI) + private var isShown by mutableStateOf(true) + private var isOffered = false + private var isCurrent = true + + @After + fun tearDown() { + assertEquals(route.opens, route.closes + if (NfcTagEmitter.currentMessage() == null) 0 else 1) + } + + @Test + fun `a resumed screen with a request offers it, registering once`() { + setContent() + + assertOffered(URI) + assertEquals(1, route.opens) + assertEquals(0, route.closes) + } + + @Test + fun `a screen without a request offers nothing`() { + uri = null + setContent() + + assertStopped() + assertEquals(0, route.opens) + } + + @Test + fun `the offer stops when the request is taken away, and starts again with a new one`() { + setContent() + + uri = null + composeRule.waitForIdle() + assertStopped() + + uri = OTHER_URI + composeRule.waitForIdle() + assertOffered(OTHER_URI) + } + + @Test + fun `a new request replaces the old one`() { + setContent() + + uri = OTHER_URI + composeRule.waitForIdle() + + assertOffered(OTHER_URI) + assertEquals(1, route.closes) + } + + @Test + fun `the offer stops when the screen leaves`() { + setContent() + + isShown = false + composeRule.waitForIdle() + + assertStopped() + } + + @Test + fun `the offer stops when the app is paused or stopped, and starts again when it returns`() { + setContent() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.STARTED) + composeRule.waitForIdle() + assertStopped() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.CREATED) + assertStopped() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.RESUMED) + composeRule.waitForIdle() + assertOffered(URI) + } + + @Test + fun `a request that is no longer current is not offered`() { + isCurrent = false + setContent() + + assertStopped() + assertEquals(0, route.opens) + } + + @Test + fun `a request that stopped being current while the app was away is not offered on return`() { + setContent() + composeRule.activityRule.scenario.moveToState(Lifecycle.State.STARTED) + composeRule.waitForIdle() + + isCurrent = false + composeRule.activityRule.scenario.moveToState(Lifecycle.State.RESUMED) + composeRule.waitForIdle() + + assertStopped() + assertEquals(1, route.opens) + } + + @Test + fun `the offer stops when the activity is destroyed`() { + setContent() + + composeRule.activityRule.scenario.moveToState(Lifecycle.State.DESTROYED) + + assertNull(NfcTagEmitter.currentMessage()) + assertEquals(route.opens, route.closes) + } + + @Test + fun `a tag that cannot be registered is not offered`() { + route.canOpen = false + setContent() + + assertFalse(isOffered) + assertNull(NfcTagEmitter.currentMessage()) + route.canOpen = true + route.opens = 0 + } + + private fun setContent() { + composeRule.setContent { + if (isShown) { + NfcTagEffect(uri = uri, route = route, onOfferChange = { isOffered = it }, isCurrent = { isCurrent }) + } + } + composeRule.waitForIdle() + } + + private fun assertOffered(uri: String) { + assertTrue(isOffered) + assertContentEquals(NdefCodec.encodeUriMessage(uri), NfcTagEmitter.currentMessage()) + } + + private fun assertStopped() { + assertFalse(isOffered) + assertNull(NfcTagEmitter.currentMessage()) + assertEquals(route.opens, route.closes) + } + + private class FakeRoute : TagRoute { + var canOpen = true + var opens = 0 + var closes = 0 + + override fun open(): Boolean { + opens++ + return canOpen + } + + override fun close() { + closes++ + } + } + + private companion object { + const val URI = "lightning:lnbcrt1invoice" + const val OTHER_URI = "lightning:lnbcrt1other" + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt index ec15e28161..8117d95898 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt @@ -1,6 +1,10 @@ package to.bitkit.wear.ui.screens.receive import androidx.activity.ComponentActivity +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.assertHasNoClickAction import androidx.compose.ui.test.click @@ -16,9 +20,11 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowSystemClock +import to.bitkit.wear.ui.components.NfcHintState import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.screens.home.DisplayAmount import kotlin.test.assertEquals +import kotlin.test.assertTrue import kotlin.time.Duration.Companion.seconds import kotlin.time.toJavaDuration @@ -32,6 +38,7 @@ class ReceiveQrContentTest { private val paid = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "50 000")) private val shown = ReceiveUiState(qrContent = "LNBCRT1TEST") private var shows = 0 + private var nfcSettingsOpens = 0 @Test fun `a paid invoice shows the check with its amount`() { @@ -78,7 +85,100 @@ class ReceiveQrContentTest { composeRule.onNodeWithTag("WatchReceiveQr").assertDoesNotExist() } - private fun setContent(uiState: ReceiveUiState, isAmbient: Boolean, isResting: Boolean = false) { + @Test + fun `the nfc hint shows below the qr, clear of its square`() = assertHintPlaced() + + @Test + @Config(sdk = [34], qualifiers = "w192dp-h192dp-round") + fun `the nfc hint shows below the qr, clear of its square, on the smallest round screen`() = assertHintPlaced() + + @Test + fun `the nfc hint with nfc off sits in the same place and opens the nfc settings`() = assertDisabledHint() + + @Test + @Config(sdk = [34], qualifiers = "w192dp-h192dp-round") + fun `the nfc hint with nfc off stays on the smallest round screen and opens the nfc settings`() = + assertDisabledHint() + + private fun assertHintPlaced() { + setContent(shown, isAmbient = false, nfcHint = NfcHintState.Active) + + val hint = composeRule.onNodeWithTag("WatchReceiveNfc") + hint.assertContentDescriptionEquals("Tap to receive") + val qr = composeRule.onNodeWithTag("WatchReceiveQr").fetchSemanticsNode().boundsInRoot + val bounds = hint.fetchSemanticsNode().boundsInRoot + val screen = composeRule.onRoot().fetchSemanticsNode().boundsInRoot + assertTrue(bounds.top >= qr.bottom, "$bounds overlaps $qr") + assertTrue(bounds.bottom <= screen.bottom, "$bounds leaves $screen") + assertEquals(screen.center.x, bounds.center.x, 1f) + // Its corners stay inside the round screen. + val radius = screen.width / 2 + val corner = bounds.bottomRight - screen.center + assertTrue(corner.getDistance() <= radius, "$bounds leaves the round screen") + } + + /** The disabled hint's bounds are its touch area: on screen, around the place of the active hint's icon. */ + private fun assertDisabledHint() { + setContent(shown, isAmbient = false, nfcHint = NfcHintState.Disabled) + + val hint = composeRule.onNodeWithTag("WatchReceiveNfcOff") + hint.assertContentDescriptionEquals("NFC off") + hint.assert( + SemanticsMatcher("click label is 'Open NFC settings'") { + it.config.getOrNull(SemanticsActions.OnClick)?.label == "Open NFC settings" + } + ) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + val bounds = hint.fetchSemanticsNode().boundsInRoot + val screen = composeRule.onRoot().fetchSemanticsNode().boundsInRoot + val qr = composeRule.onNodeWithTag("WatchReceiveQr").fetchSemanticsNode().boundsInRoot + assertTrue(bounds.bottom <= screen.bottom + 0.5f, "$bounds leaves $screen") + assertTrue(bounds.top >= screen.top && bounds.left >= screen.left && bounds.right <= screen.right) + assertEquals(screen.center.x, bounds.center.x, 1f) + // The icon keeps the active hint's place: centred in the strip below the QR's square. + val density = composeRule.density.density + val iconCenterY = bounds.top + 14 * density + 10 * density + assertEquals((qr.bottom + screen.bottom) / 2, iconCenterY, 1.5f) + ShadowSystemClock.advanceBy(2.seconds.toJavaDuration()) + hint.performTouchInput { click() } + composeRule.waitForIdle() + + assertEquals(1, nfcSettingsOpens) + } + + @Test + fun `no nfc hint shows in ambient mode`() { + setContent(shown, isAmbient = true, nfcHint = NfcHintState.Active) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + } + + @Test + fun `no nfc hint shows while the qr rests`() { + setContent(shown, isAmbient = false, isResting = true, nfcHint = NfcHintState.Active) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + } + + @Test + fun `no nfc hint shows once paid`() { + setContent(paid, isAmbient = false, nfcHint = NfcHintState.Active) + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + } + + @Test + fun `the qr shows without a hint when there is none`() { + setContent(shown, isAmbient = false) + + composeRule.onNodeWithTag("WatchReceiveQr").assertExists() + composeRule.onNodeWithTag("WatchReceiveNfc").assertDoesNotExist() + composeRule.onNodeWithTag("WatchReceiveNfcOff").assertDoesNotExist() + } + + private fun setContent( + uiState: ReceiveUiState, + isAmbient: Boolean, + isResting: Boolean = false, + nfcHint: NfcHintState = NfcHintState.Hidden, + ) { composeRule.setContent { WearPreview { ReceiveQrContent( @@ -86,7 +186,9 @@ class ReceiveQrContentTest { isAmbient = isAmbient, onRefreshClick = {}, isResting = isResting, + nfcHint = nfcHint, onShowClick = { shows++ }, + onNfcSettingsClick = { nfcSettingsOpens++ }, ) } } diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveTagTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveTagTest.kt new file mode 100644 index 0000000000..f1d2ddc5df --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveTagTest.kt @@ -0,0 +1,125 @@ +package to.bitkit.wear.ui.screens.receive + +import org.junit.Test +import to.bitkit.wear.data.NfcState +import to.bitkit.wear.ui.components.NfcHintState +import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** When the receive QR offers its invoice as an NFC tag, and what the hint below the QR shows. */ +class ReceiveTagTest { + private val shown = ReceiveUiState(qrContent = "LNBCRT1INVOICE", nfcUri = URI) + + @Test + fun `the invoice on screen is offered with nfc on`() { + assertEquals(URI, tagUri()) + assertEquals(NfcHintState.Active, hint(isOffered = true)) + } + + @Test + fun `an invoice being replaced is still offered while it shows`() { + assertEquals(URI, tagUri(shown.copy(isLoading = true))) + } + + @Test + fun `nothing is offered in ambient mode`() { + assertNull(tagUri(isAmbient = true)) + assertEquals(NfcHintState.Hidden, hint(isAmbient = true, isOffered = true)) + } + + @Test + fun `nothing is offered while the qr rests`() { + assertNull(tagUri(isResting = true)) + assertEquals(NfcHintState.Hidden, hint(isResting = true, isOffered = true)) + } + + @Test + fun `nothing is offered once paid`() { + val paid = ReceiveUiState(paidAmount = DisplayAmount("₿", "21 000")) + assertNull(tagUri(paid)) + // Not even if a request were left behind in the state. + assertNull(tagUri(paid.copy(qrContent = "LNBCRT1INVOICE", nfcUri = URI))) + assertEquals(NfcHintState.Hidden, hint(paid, isOffered = true)) + } + + @Test + fun `nothing is offered while the view model holds the request back`() { + // The wallet is not ready, or the invoice expired: see ReceiveViewModelTest. + val held = shown.copy(nfcUri = null) + assertNull(tagUri(held)) + assertEquals(NfcHintState.Hidden, hint(held, isOffered = true)) + assertEquals(NfcHintState.Hidden, hint(held, nfc = NfcState.Off)) + } + + @Test + fun `nothing is offered, and no hint shows, while the repeat guard holds reader mode`() { + assertNull(tagUri(isReaderHeld = true)) + assertEquals(NfcHintState.Hidden, hint(isOffered = true, isReaderHeld = true)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Off, isReaderHeld = true)) + } + + @Test + fun `nothing is offered while there is no invoice`() { + for (state in listOf(ReceiveUiState(isLoading = true), ReceiveUiState(isError = true), ReceiveUiState())) { + assertNull(tagUri(state)) + assertNull(tagUri(state.copy(nfcUri = URI))) + assertEquals(NfcHintState.Hidden, hint(state, isOffered = true)) + } + } + + @Test + fun `nothing is offered unless nfc is on`() { + for (nfc in NfcState.entries - NfcState.On) { + assertNull(tagUri(nfc = nfc), "$nfc") + } + } + + @Test + fun `nothing is offered on a watch that cannot act as a tag`() { + assertNull(tagUri(hasCardEmulation = false)) + assertEquals(NfcHintState.Hidden, hint(hasCardEmulation = false, isOffered = true)) + assertEquals(NfcHintState.Hidden, hint(hasCardEmulation = false, nfc = NfcState.Off)) + } + + @Test + fun `the hint is the disabled one with nfc off, only where the tag would be offered`() { + assertEquals(NfcHintState.Disabled, hint(nfc = NfcState.Off)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Off, isAmbient = true)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Off, isResting = true)) + } + + @Test + fun `the hint is hidden without nfc hardware and until the nfc state was read`() { + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Unavailable, isOffered = true)) + assertEquals(NfcHintState.Hidden, hint(nfc = NfcState.Unknown, isOffered = true)) + } + + @Test + fun `the hint is hidden while the tag is not offered, as when it could not be registered`() { + assertEquals(NfcHintState.Hidden, hint(isOffered = false)) + } + + private fun tagUri( + uiState: ReceiveUiState = shown, + nfc: NfcState = NfcState.On, + hasCardEmulation: Boolean = true, + isAmbient: Boolean = false, + isResting: Boolean = false, + isReaderHeld: Boolean = false, + ) = receiveTagUri(uiState, nfc, hasCardEmulation, isAmbient, isResting, isReaderHeld) + + private fun hint( + uiState: ReceiveUiState = shown, + nfc: NfcState = NfcState.On, + hasCardEmulation: Boolean = true, + isAmbient: Boolean = false, + isResting: Boolean = false, + isOffered: Boolean = false, + isReaderHeld: Boolean = false, + ) = receiveNfcHintState(uiState, nfc, hasCardEmulation, isAmbient, isResting, isOffered, isReaderHeld) + + private companion object { + const val URI = "lightning:lnbcrt1invoice" + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt index ebf2d0089c..ba4f3d57af 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveViewModelTest.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch import org.junit.Before import org.junit.Test import org.mockito.kotlin.any @@ -27,6 +28,7 @@ import to.bitkit.wear.repositories.PaymentsRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus +import to.bitkit.wear.security.FakeNfcMonitor import to.bitkit.wear.test.BaseUnitTest import to.bitkit.wear.ui.screens.home.DisplayAmount import kotlin.test.assertEquals @@ -41,14 +43,23 @@ class ReceiveViewModelTest : BaseUnitTest() { private val settingsStore = mock { on { data } doReturn flowOf(WatchSettings()) } private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 0uL, hasSynced = true)) + /** The watch's wall clock, which the tests move apart from the scheduler's time, as a sleeping watch does. */ + private var now = NOW + private var revocations = 0 + @Before fun setUp() { whenever(walletRepo.walletState).thenReturn(walletState) + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.success(null)) } private val created = mutableListOf() - private fun createSut() = ReceiveViewModel(paymentsRepo, walletRepo, settingsStore) { NOW }.also { created += it } + private val nfcMonitor = FakeNfcMonitor() + + private fun createSut() = + ReceiveViewModel(paymentsRepo, walletRepo, settingsStore, nfcMonitor, { now }, { revocations++ }) + .also { created += it } /** An unpaid invoice is replaced forever, so the view models stop before the test drains its scheduler. */ override fun onTestEnd() = created.forEach { it.viewModelScope.cancel() } @@ -255,6 +266,348 @@ class ReceiveViewModelTest : BaseUnitTest() { assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) } + // region nfc tag + + @Test + fun `the invoice on screen is the tag's request, as a lowercase lightning uri`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + } + + @Test + fun `no tag request exists while the invoice is made or failed`() = test { + walletState.update { it.copy(status = WalletStatus.Connecting) } + whenever(paymentsRepo.createInvoice()).thenReturn(Result.failure(ReceiveError.NotReady())) + val sut = createSut() + assertNull(sut.uiState.value.nfcUri) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertTrue(sut.uiState.value.isError) + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `the tag request is taken away whenever the wallet stops being ready, and comes back with it`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + assertNull(sut.uiState.value.nfcUri, "$status") + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent, "$status") + + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri, "$status") + } + } + + @Test + fun `a paid invoice is no longer the tag's request`() = test { + val paid = CompletableDeferred() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { paid.await() } + val sut = createSut() + val states = mutableListOf() + val collector = backgroundScope.launch { sut.uiState.collect { states += it } } + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + paid.complete(payment(21_000uL)) + + assertNull(sut.uiState.value.nfcUri) + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + // Nor in any state between the payment and the check. + val afterPaid = states.dropWhile { it.nfcUri == null }.dropWhile { it.nfcUri != null } + assertTrue(afterPaid.isNotEmpty()) + assertTrue(afterPaid.all { it.nfcUri == null }) + collector.cancel() + + // The wallet's status moving afterwards brings nothing back. + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `the replacement becomes the tag's request, and the replaced invoice never returns`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.success(invoice("lnbcrt1next", hash = "cd34"))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + testScheduler.advanceTimeBy(LIFETIME.seconds - ReceiveViewModel.EXPIRY_MARGIN - 1.seconds) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + testScheduler.advanceTimeBy(2.seconds) + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + + // Past the first invoice's expiry, and across a wallet that reconnects, the tag stays on the new invoice. + testScheduler.advanceTimeBy(EXPIRY_MARGIN_AND_MORE) + walletState.update { it.copy(status = WalletStatus.Connecting) } + assertNull(sut.uiState.value.nfcUri) + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + } + + @Test + fun `an invoice still on screen at its expiry is no longer the tag's request`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.failure(ReceiveError.NotReady())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + testScheduler.advanceTimeBy(LIFETIME.seconds - 1.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + testScheduler.advanceTimeBy(2.seconds) + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `an invoice the watch's clock takes for expired shows as a qr but is never the tag's request`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice(lifetime = 0))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertNull(sut.uiState.value.nfcUri) + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `asking for a new invoice drops the old tag request before the new invoice exists`() = test { + val next = CompletableDeferred>() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).doSuspendableAnswer { next.await() } + + sut.onRefreshClick() + + assertNull(sut.uiState.value.nfcUri) + next.complete(Result.success(invoice("lnbcrt1next", hash = "cd34"))) + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + } + + @Test + fun `a paid invoice's request is taken from the nfc service at once`() = test { + val paid = CompletableDeferred() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { paid.await() } + createSut() + assertEquals(0, revocations) + + paid.complete(payment(21_000uL)) + + assertEquals(1, revocations) + } + + @Test + fun `a payment takes whatever the nfc service holds, also when the invoice on screen has no tag request`() = test { + val paid = CompletableDeferred() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { paid.await() } + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Connecting) } + assertNull(sut.uiState.value.nfcUri) + + paid.complete(payment(21_000uL)) + + assertEquals(1, revocations) + } + + @Test + fun `an invoice without a tag request is not current for the tag, though it has not expired`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertTrue(sut.isTagCurrent()) + + walletState.update { it.copy(status = WalletStatus.Connecting) } + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertFalse(sut.isTagCurrent()) + } + + @Test + fun `an invoice the watch slept past is not the tag's request when the wallet is ready again`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertTrue(sut.isTagCurrent()) + + // The wall clock passes the expiry while the timers stand still, as in deep sleep. + walletState.update { it.copy(status = WalletStatus.Paused) } + now += LIFETIME + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertNull(sut.uiState.value.nfcUri) + assertFalse(sut.isTagCurrent()) + } + + @Test + fun `an invoice the watch slept past loses its tag request and is replaced when the screen shows again`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.success(invoice("lnbcrt1next", lifetime = 3 * LIFETIME, hash = "cd34"))) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + now += LIFETIME + 1 + // Still offered by the timers alone, which did not move; the screen asks before it starts the tag. + assertFalse(sut.isTagCurrent()) + sut.onShow() + + assertEquals("LNBCRT1NEXT", sut.uiState.value.qrContent) + assertEquals("lightning:lnbcrt1next", sut.uiState.value.nfcUri) + assertTrue(sut.isTagCurrent()) + verify(paymentsRepo, times(2)).createInvoice() + } + + @Test + fun `an expired invoice is not shown while its replacement is made`() = test { + val next = CompletableDeferred>() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).doSuspendableAnswer { next.await() } + + now += LIFETIME + 1 + sut.onShow() + + assertNull(sut.uiState.value.qrContent) + assertNull(sut.uiState.value.nfcUri) + assertTrue(sut.uiState.value.isLoading) + } + + @Test + fun `a screen that shows again before the invoice is due changes nothing`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + now += LIFETIME - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds - 1 + sut.onShow() + + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + verify(paymentsRepo, times(1)).createInvoice() + } + + @Test + fun `a screen that shows again after a sleep has the invoice replaced on time by the wall clock`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + + // Half the invoice's life passes in sleep, where the timers stand still, and the watch stays awake after. + now += LIFETIME / 2 + sut.onShow() + verify(paymentsRepo, times(1)).createInvoice() + + val left = LIFETIME / 2 - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds + now += left - 1 + testScheduler.advanceTimeBy((left - 1).seconds) + verify(paymentsRepo, times(1)).createInvoice() + + now += 2 + testScheduler.advanceTimeBy(2.seconds) + verify(paymentsRepo, times(2)).createInvoice() + } + + @Test + fun `a screen that shows again after a sleep ends the tag request at the wall clock's expiry`() = test { + whenever(paymentsRepo.createInvoice()) + .thenReturn(Result.success(invoice())) + .thenReturn(Result.failure(ReceiveError.NotReady())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + // The replacement is under way, and fails for as long as it is tried. + val awake = LIFETIME - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds + 1 + now += awake + testScheduler.advanceTimeBy(awake.seconds) + + // Half a minute of sleep, then awake again with less than that left on the invoice. + now += 30 + sut.onShow() + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + now += 28 + testScheduler.advanceTimeBy(28.seconds) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + + // The replacement's own timer runs half a minute late, so the QR is still there; the tag is not. + now += 2 + testScheduler.advanceTimeBy(2.seconds) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertNull(sut.uiState.value.nfcUri) + } + + @Test + fun `an invoice near its expiry stays on screen while the screen that shows again has it replaced`() = test { + val next = CompletableDeferred>() + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever(paymentsRepo.createInvoice()).doSuspendableAnswer { next.await() } + + now += LIFETIME - ReceiveViewModel.EXPIRY_MARGIN.inWholeSeconds + 1 + sut.onShow() + + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + assertTrue(sut.uiState.value.isLoading) + } + + @Test + fun `an invoice paid while the wallet was away never returns as the tag's request`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + val states = mutableListOf() + walletState.update { it.copy(status = WalletStatus.Paused) } + val collector = backgroundScope.launch { sut.uiState.collect { states += it } } + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.success(payment(21_000uL))) + + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertTrue(states.all { it.nfcUri == null }) + assertEquals(DisplayAmount("₿", "21 000"), sut.uiState.value.paidAmount) + collector.cancel() + } + + @Test + fun `the tag request stays away while spark's list cannot be read after the wallet was away`() = test { + whenever(paymentsRepo.createInvoice()).thenReturn(Result.success(invoice())) + whenever(paymentsRepo.awaitPaid(any())).doSuspendableAnswer { awaitCancellation() } + val sut = createSut() + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.failure(IllegalStateException("offline"))) + + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertNull(sut.uiState.value.nfcUri) + assertEquals(BOLT11.uppercase(), sut.uiState.value.qrContent) + + whenever { paymentsRepo.findPaid(any()) }.thenReturn(Result.success(null)) + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals("lightning:$BOLT11", sut.uiState.value.nfcUri) + } + + // endregion + private fun invoice(bolt11: String = BOLT11, lifetime: Long = LIFETIME, hash: String = PAYMENT_HASH) = ReceiveInvoice(bolt11, hash, (NOW + lifetime).toULong()) @@ -272,5 +625,6 @@ class ReceiveViewModelTest : BaseUnitTest() { const val PAYMENT_HASH = "ab12" const val NOW = 1_800_000_000L const val LIFETIME = 3_600L + val EXPIRY_MARGIN_AND_MORE = ReceiveViewModel.EXPIRY_MARGIN + 10.seconds } } diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index a45733a614..c63c34ca2e 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -1,5 +1,6 @@ package to.bitkit.wear.ui.screens.send +import android.nfc.NfcAdapter import androidx.lifecycle.SavedStateHandle import app.cash.turbine.test import breez_sdk_spark.PrepareSendPaymentResponse @@ -30,6 +31,8 @@ import to.bitkit.wear.models.PreparedSend import to.bitkit.wear.models.SendError import to.bitkit.wear.models.SendRequest import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.nfc.NdefCodec +import to.bitkit.wear.nfc.nfcPaymentUri import to.bitkit.wear.repositories.CurrencyRepo import to.bitkit.wear.repositories.PaymentsRepo import to.bitkit.wear.repositories.WalletRepo @@ -37,6 +40,7 @@ import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus import to.bitkit.wear.security.FakeForegroundMonitor import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wear.ui.LaunchRequest import to.bitkit.wear.ui.Routes import to.bitkit.wear.ui.screens.home.DisplayAmount import kotlin.test.assertEquals @@ -318,6 +322,45 @@ class SendViewModelTest : BaseUnitTest() { verify(paymentsRepo, never()).send(any()) } + @Test + fun `a flow whose screen left while quickpay was decided sends nothing`() = test { + val prepared = prepared() + stubInvoice(prepared) + val decision = CompletableDeferred() + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { + decision.await() + it.getArgument<() -> Boolean>(1)() + } + val sut = createSut() + + // Another request took this flow off the back stack: its entry stops before its view model is cleared. + sut.onShownChange(false) + decision.complete(Unit) + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a flow whose screen is not shown asks no quickpay`() = test { + val parsed = CompletableDeferred() + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.prepare(any(), anyOrNull())).doSuspendableAnswer { + parsed.await() + Result.success(prepared) + } + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + val sut = createSut() + + sut.onShownChange(false) + parsed.complete(Unit) + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + @Test fun `a quickpay send that fails shows the failure like any other`() = test { val prepared = prepared() @@ -593,6 +636,108 @@ class SendViewModelTest : BaseUnitTest() { assertFalse(assertIs(sut.uiState.value.step).isOutOfRange) } + // region nfc tap + + @Test + fun `a tapped tag opens the review of its request, and nothing is sent before the hold`() = test { + stubInvoice(prepared(amountSats = 21_000uL)) + + val sut = createSut(tapped()) + + val step = assertIs(sut.uiState.value.step) + assertEquals(DisplayAmount("₿", "21 000"), step.amount) + verify(paymentsRepo).parse(INPUT) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a tap counts as attended, so quickpay pays it without the hold`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut(tapped()) + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, times(1)).send(prepared) + } + + @Test + fun `a tap that brought the app back from the background is attended once the wallet runs again`() = test { + walletState.update { it.copy(status = WalletStatus.Paused) } + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut(tapped()) + walletState.update { it.copy(status = WalletStatus.Connecting) } + elapsedMs += 5_000 + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step) + } + + @Test + fun `a tap on a locked watch, or one the wearer left, is reviewed and held`() = test { + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + walletState.update { it.copy(status = WalletStatus.Locked) } + val locked = createSut(tapped()) + walletState.update { it.copy(status = WalletStatus.Ready) } + assertIs(locked.uiState.value.step) + + walletState.update { it.copy(status = WalletStatus.Connecting) } + val left = createSut(tapped()) + foregroundMonitor.isForeground.value = false + foregroundMonitor.isForeground.value = true + walletState.update { it.copy(status = WalletStatus.Ready) } + assertIs(left.uiState.value.step) + + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a tap while offline ends on the offline error`() = test { + walletState.update { it.copy(status = WalletStatus.Offline) } + + val sut = createSut(tapped()) + + assertEquals(SendStep.Offline, sut.uiState.value.step) + verify(paymentsRepo, never()).parse(any()) + } + + @Test + fun `a tap on a tag with the watch's own invoice ends on the own invoice error`() = test { + whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.failure(SendError.OwnInvoice())) + + val sut = createSut(tapped()) + + assertEquals(SendStep.Failed(SendFailure.OwnInvoice), sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + /** + * The saved state of the send flow a tapped tag opens: the tag another Bitkit offers for [BOLT11], read from its + * record, taken as a launch request and passed on as the route's input, as `WearNavHost` does. + */ + private fun tapped(): SavedStateHandle { + val uri = nfcPaymentUri(BOLT11)!! + val request = LaunchRequest.from( + NfcAdapter.ACTION_NDEF_DISCOVERED, + data = uri, + open = null, + tagTexts = NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri)), + ) + return SavedStateHandle(mapOf(Routes.SEND_INPUT to assertIs(request).input)) + } + + // endregion + private suspend fun stubInvoice(prepared: PreparedSend) { whenever(paymentsRepo.parse(INPUT)).thenReturn(Result.success(INVOICE)) whenever(paymentsRepo.prepare(INVOICE, null)).thenReturn(Result.success(prepared)) diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/TagRefusedTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/TagRefusedTest.kt new file mode 100644 index 0000000000..7451a0a679 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/TagRefusedTest.kt @@ -0,0 +1,38 @@ +package to.bitkit.wear.ui.screens.send + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.wear.ui.components.WearPreview +import kotlin.test.assertEquals + +/** What a tapped tag without a payment request the watch takes ends on. */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class TagRefusedTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + @Test + fun `a refused tag shows one line and closes on its one action`() { + var closes = 0 + composeRule.setContent { + WearPreview { + TagRefusedScreen(onClose = { closes++ }) + } + } + + composeRule.onNodeWithTag("WatchTagRefused").assertTextEquals("Not supported") + composeRule.onNodeWithTag("WatchSendClose").performClick() + composeRule.waitForIdle() + + assertEquals(1, closes) + } +}