diff --git a/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt new file mode 100644 index 0000000000..52817bf0f9 --- /dev/null +++ b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt @@ -0,0 +1,87 @@ +package to.bitkit.models + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assume.assumeFalse +import org.junit.Assume.assumeTrue +import org.junit.Test +import to.bitkit.data.SettingsData +import to.bitkit.di.json +import to.bitkit.env.Env +import java.io.File +import kotlin.test.assertEquals + +/** + * The Wear OS app imports the phone's settings by reading the settings backup from VSS (docs/wear.md, Settings + * sync). `wear/src/test/resources/phone-backup-contract.json` holds what it relies on: the backup's key, six + * settings as this app encodes them, and where each network's backups live. The watch's `PhoneBackupContractTest` + * reads the same file. When a test here fails, the watch stops reading the phone's settings: change the watch's + * reader and the file together with the phone. + */ +class WatchBackupContractTest { + private val contract: JsonObject by lazy { + val file = generateSequence(File("").absoluteFile) { it.parentFile } + .map { File(it, "wear/src/test/resources/phone-backup-contract.json") } + .first { it.isFile } + Json.parseToJsonElement(file.readText()).jsonObject + } + + @Test + fun `the settings backup is stored under the key the watch reads`() { + assertEquals(contract.getValue("settingsKey").jsonPrimitive.content, BackupCategory.SETTINGS.name) + } + + @Test + fun `the settings backup holds the six settings the watch reads, in the form it reads`() { + val expected = contract.getValue("settingsBackup").jsonObject + val expectedSettings = expected.getValue("settings").jsonObject + val settings = SettingsData( + primaryDisplay = PrimaryDisplay.FIAT, + displayUnit = BitcoinDisplayUnit.CLASSIC, + selectedCurrency = "EUR", + isQuickPayEnabled = true, + quickPayAmount = 10, + quickPayDailyLimitMultiplier = 3, + ) + + val written = written(settings) + + assertEquals(expected.getValue("version"), written.getValue("version")) + val writtenSettings = written.getValue("settings").jsonObject + assertEquals(expectedSettings, JsonObject(writtenSettings.filterKeys { it in expectedSettings.keys })) + } + + @Test + fun `default settings are written too, so the watch always finds all six`() { + val keys = contract.getValue("settingsBackup").jsonObject.getValue("settings").jsonObject.keys + + val written = written(SettingsData()).getValue("settings").jsonObject + + assertEquals(keys, written.keys.intersect(keys)) + } + + @Test + fun `this network's backups live where the watch looks for them`() { + // An E2E build may point the backups at a local server, which the watch never reads. + assumeFalse(Env.isE2eTest) + val network = contract.getValue("networks").jsonObject[Env.network.name]?.jsonObject + // The watch runs on fewer networks than the phone. + assumeTrue(network != null) + + val expected = checkNotNull(network).mapValues { it.value.jsonPrimitive.content } + val actual = mapOf( + "storeIdPrefix" to Env.vssStoreIdPrefix, + "vssServerUrl" to Env.vssServerUrl, + "lnurlAuthServerUrl" to Env.lnurlAuthServerUrl, + ) + assertEquals(expected, actual) + } + + /** The settings backup of [settings] as this app uploads it. */ + private fun written(settings: SettingsData): JsonObject { + val backup = SettingsBackupV1(createdAt = 0, settings = settings) + return json.parseToJsonElement(json.encodeToString(SettingsBackupV1.serializer(), backup)).jsonObject + } +} diff --git a/docs/wear.md b/docs/wear.md index 47f85a1919..cbda663fc8 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -3,7 +3,8 @@ > Do not publish the watch app yet: two live Spark instances on one seed are unsafe until #2152 is resolved. The `:wear` module is a standalone Wear OS app (issue #2105, epic #2077). It runs its own Spark wallet through the -Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only needed to set it up (from PR 3). +Breez SDK, with no LDK node, no Room database and no Firebase. It needs no phone nearby: it adopts the phone's +settings by reading the phone's backup (see Settings sync). ## Module overview @@ -66,17 +67,22 @@ Breez SDK, with no LDK node, no Room database and no Firebase. The phone is only bitkit-core, as on the phone. - `services`: `WatchSparkService` (connect, disconnect, sync, info, storage wipe, invoices, sends and the payment list, with the phone's SDK settings and the local regtest fixture), `SparkSendKey` (the idempotency keys of - sends, a copy of the phone's), `InputDecoder` (bitkit-core's reader of payment inputs) and `SelfSendGuard`. + sends, a copy of the phone's), `InputDecoder` (bitkit-core's reader of payment inputs), `SelfSendGuard` and + `PhoneBackupReader`, the read-only way to the phone's backups on VSS. - `repositories`: `WalletRepo` (wallet state and balance, restore, start, lock, background and network handling, wipe and its recovery at launch), `PaymentsRepo` (receive, read an input, price, send, recent payments; see - Payments) and `CurrencyRepo` (Blocktank rates and the unit shown first). -- `data`: `SettingsStore` (display settings and the wipe's notes, with `WipeMarker` for the note itself), - `OwnInvoiceStore` (the invoices this wallet created, in the settings file), the rates + Payments), `CurrencyRepo` (Blocktank rates and the unit shown first), `SettingsSyncRepo` (the import of the + phone's settings) and `QuickPayRepo` (whether a send may skip the hold to pay). +- `data`: `SettingsStore` (display settings, what was imported from the phone and the wipe's notes, with + `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) and `ForegroundMonitor` (the process lifecycle: whether the app is on - screen). + `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, + sleep included, for ages). - `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 @@ -152,7 +158,8 @@ On-screen copy stays short: a title or one line of at most about six words per s disconnect that already began always finishes, and the wallet then connects again. When Spark cannot be disconnected, the app keeps hold of it so the next lock, pause or wipe tries again: each of them disconnects whatever the wallet's status says, as does a start that finds the watch locked. Ambient mode is not the - background: the app stays on screen and connected. + background: the app stays on screen and connected. `AmbientMonitor` carries it from the activity to what runs + outside the screens: in ambient mode the phone's settings are not imported and no send goes out under QuickPay. - **Receive.** The Receive page is one large round QR button (`WatchReceiveOpen`); it has no amount entry. It opens the receive QR (`WatchReceiveQr`): an amountless invoice, uppercased so the code uses QR's alphanumeric mode, black on white with the standard four-module quiet zone, error correction L, filling the largest square inside the round @@ -173,19 +180,19 @@ On-screen copy stays short: a title or one line of at most about six words per s 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. - **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 - (white, as on the Balance page) and a round Brand orange edge button with the QR icon ("Receive" to accessibility - services), which opens the app on the receive QR: the launch intent carries the extra `to.bitkit.wear.OPEN` with - `receive`, which `LaunchRequest` reads as `Receive`, and the receive QR opens above Home, as a payment link's send - does. Without a wallet it shows the Bitkit mark and a "Restore" edge button that opens the app. Tiles cannot use - the app's fonts, so the balance is in the system font. + 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 + edge button with the QR icon ("Receive" to accessibility services), which opens the app on the receive QR: the + launch intent carries the extra `to.bitkit.wear.OPEN` with `receive`, which `LaunchRequest` reads as `Receive`, + and the receive QR opens above Home, as a payment link's send does. Without a wallet it shows the Bitkit mark and + a "Restore" edge button that opens the app. Tiles cannot use the app's fonts, so the balance is in the system font. - The tile only reads `WalletRepo`'s state in memory and never starts the wallet, so the balance shows only once the app loaded it in this process and a sync confirmed it, as on the Balance page; until then, and while the watch is locked, the dimmed mark stands in for it. A removed wallet shows the signed-out tile at once. - - `TileUpdates`, started by `WearApp`, asks the system to draw the tile again whenever the balance shown or the - wallet's status changes, and once when the process starts, so a tile drawn by an earlier process drops a balance - the new one has not loaded. Each tile is fresh for 15 min, after which the system asks again; a tile drawn just - before the process died can show the last balance until then. + - `TileUpdates`, started by `WearApp`, asks the system to draw the tile again whenever the balance shown, its + unit or the wallet's status changes, and once when the process starts, so a tile drawn by an earlier process drops + a balance the new one has not loaded. Each tile is fresh for 15 min, after which the system asks again; a tile + drawn just before the process died can show the last balance until then. - Privacy: the tile shows the balance on the tile carousel, so it hides it while the wallet is disconnected because the watch locked (`WalletStatus.Locked`). Tiles have no ambient mode: in ambient the system shows the watch face, so the app's rule that the always-on screen shows no amount holds without code in the tile. The tile carries no secret: the receive invoice is made by the @@ -205,7 +212,9 @@ On-screen copy stays short: a title or one line of at most about six words per s without an amount, an amountless invoice, a Spark address or an LNURL with a range, gets a minimal amount entry (the number keyboard, the LNURL range below it); Receive never has one. - Review: the amount in the balance's large style, fiat below in the small style, the fee only when it is at - least 1 % of the amount, and one line naming the payee when the input names one. The pay button is the edge + least 1 % of the amount, and one line naming the payee when the input names one. The fee line + (`WatchSendFee`) may wrap to 2 lines and is never cut: under Classic a long translation, as the Italian + "Commissione ₿ 0.00001234", does not fit one. The pay button is the edge button, "Hold to pay" (`WatchSendHold`). - Hold to pay: holding the button fills a ring around the bezel (`HoldToPayRing`, the geometry of `BezelLoading`) over 1.2 s, with a light tick (`SegmentTick`) at each quarter and the confirm haptic at the end, and only then @@ -218,7 +227,8 @@ On-screen copy stays short: a title or one line of at most about six words per s request is dropped, never kept to pay when the network returns, so nothing (QuickPay included) pays it later. Once the hold completed and the send started, going offline changes nothing: the send keeps its pending or unknown outcome. - `PaymentsRepo.skipConfirmation` is asked before the hold; it is always false until QuickPay (PR 3). + `PaymentsRepo.skipConfirmation` is asked once the send is priced, for a send the wearer is there for: under + the phone's QuickPay the review and the hold are skipped and the send goes out at once (see QuickPay). - Screen readers: a screen reader's wearer cannot hold, and the button's click pays nothing, so the button offers "Pay" as a custom accessibility action, picked from the actions menu, and as its long click (a double tap and hold); both only while the hold is enabled. `SendReviewTest` checks the three; the actions menu of @@ -237,19 +247,24 @@ On-screen copy stays short: a title or one line of at most about six words per s unreadable invoice and an own invoice end there before any hold. - **Activity.** The Activity page lists the newest 20 payments from Spark's local list: a direction icon (or a clock for pending, a cross for failed), the amount with its sign and how long ago (`WatchActivityItem-0` onwards). + An amount too long for one line, as with eight decimals on a small screen, takes a second line. It is read when Spark connects and after every payment or sync, and the last list stays while Spark is disconnected, with its times counted again every minute; a list just read counts from its own time. A tap opens the detail: the amount, the fee of a send, the date and time and the status (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). A detail whose payment the list does not hold, while it loads or after newer payments pushed it out, shows the dimmed icon (`WatchActivityDetailMissing`). Ambient mode hides the amounts. -- **Settings.** A short list of icon rows: About and Remove wallet. The unit has no setting: tapping the balance is - the only way to switch it, and the choice is kept in the settings store across restarts. Remove wallet asks with a - one-line title and the two round ✕/✓ buttons. +- **Settings.** A short list of icon rows: About, Phone settings and Remove wallet. The watch has no settings of + its own to edit: the units, the currency and QuickPay come from the phone (see Settings sync). The Phone settings + row (`WatchSettingsSync`) shows how long ago they were last imported (`WatchSettingsSyncTime`, absent until a first + import, or after the phone's backup was found missing or unreadable; it moves on every minute while the page is + open), and a tap imports them now under the loading ring. An import from the tap that fails shows one line under + the row (`WatchSettingsSyncFailed`). Tapping the balance still swaps which unit shows first, and the choice is kept across restarts until the + phone's own setting changes. Remove wallet asks with a one-line title and the two round ✕/✓ buttons. - **Loading.** Every wait shows `BezelLoading`: an indeterminate ring around the screen edge (test tag `BezelLoading`), with the screen's content readable inside it. It covers connecting and syncing on Balance, saving - the restored wallet, removing the wallet, making an invoice, the first activity list, and a send being read, - priced and sent. It is hidden in ambient mode. Accessibility services report only + the restored wallet, removing the wallet, importing the phone's settings from the Settings page, making an + invoice, the first activity list, and a send being read, priced and sent. It is hidden in ambient mode. Accessibility services report only content that no node above it covers, so the full-screen ring has no semantics; its one progress node (`BezelLoading`) is a stroke-sized spot at the top of the ring, and the content beneath stays reachable by TalkBack and `android layout`. `BezelPadding` and `BezelStrokeWidth` hold the ring's padding and stroke for other edge @@ -329,8 +344,181 @@ in any other state. the invoice. The same holds the other way round for a send of unknown outcome on the watch that the phone's list does not show. A transfer to a Spark address has no shared key at all: the phone and the watch each pay it when asked. Pairing closes both by sharing the send records. -- **QuickPay.** `PaymentsRepo.skipConfirmation` is the one place that decides whether a send skips the hold to - pay. It is always false until the watch has QuickPay settings (PR 3). +- **QuickPay.** `PaymentsRepo.skipConfirmation` is the one place that decides whether a send skips the review and + the hold to pay. See QuickPay below. + +### QuickPay + +The watch has no QuickPay switch. It follows the phone's: QuickPay on or off, the amount per payment in US dollars +and the daily limit, which is that amount times a multiplier, all read from the phone's settings backup (see +Settings sync). The decision follows the rules of the phone's own `QuickPayRepo`, with two differences that the +watch needs, listed below. A send skips the review and the hold, and goes from pricing straight to sending and the +usual result screens, only when every one of these holds: + +- The wallet is connected and synced (`WalletStatus.Ready`), and no wipe runs. +- The send was priced by `PaymentsRepo.prepare`, so the self-send guard, the expiry, the balance and every other + check before the hold passed. A request those checks refuse never reaches QuickPay. +- The request fixes the amount, as on the phone: a BOLT11 invoice that carries its amount, also the one inside a + `bitcoin:` URI, or an LNURL-pay link or a Lightning address whose smallest and largest amount are the same. The + link's scheme and case change nothing, since the request is what `PaymentsRepo.decoderInput` leaves of it: an + uppercase `BITCOIN:` URI with an amount counts like a lowercase one, and an `lnurlp://` link like any LNURL. An + amount the wearer typed always gets the review and the hold, and so does a Spark address, which names no amount. +- QuickPay is on in the settings last imported from the phone. They count however long ago the import was, as the + phone's own settings do on the phone. +- The amount, without the fee, is no more than the phone's QuickPay amount. As on the phone, the QuickPay amount is + turned into sats at the dollar rate, rounded half up, and the invoice's sats are compared with that. The + invoice's unrounded dollar value is compared with the QuickPay amount too, which is the phone's check when it + pays: where the sats rounded up, the last sat is worth a fraction of a cent too much and is reviewed. +- Today's QuickPay payments from this watch, with this one, stay within the daily limit. The payment counts as its + dollar value in cents, rounded half up and at least one cent, as on the phone. +- The wearer is there: the first of the two differences below. + +The rate is the last one the watch fetched, whatever its age: the phone has no age limit on its rates either. The +phone keeps its rates across restarts and the watch does not, so when QuickPay is on and no dollar rate is in yet, +as for a link that started the app, the decision first fetches the rates, for 5 s at most under the loading ring +(`QuickPayRepo.awaitRate`). Without a rate the answer is no. + +The two differences from the phone: + +- **The wearer has to be there** (`SendViewModel`, `MainActivity`). The phone turns QuickPay off for a scan it put + off across its lock, since whoever unlocks did not confirm it. The watch has the same case in more shapes, so: + - The send is priced within 30 s of its link arriving (`QUICKPAY_WINDOW`), and from the link to the decision the + app stayed on screen and out of ambient mode, the watch was never locked, and the wallet was not paused again + once it ran. A link that waited longer for the wallet, as one opened on a wallet that takes minutes to + connect, always ends on the review and the hold. The 30 s cover a wallet that connects and syncs as + 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. + - 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 + QuickPay, whenever it is built. + - 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. +- **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 + phone's sliders offer (1 to 50 dollars, 1× to 50×). An import that fails, as without a network, changes nothing. + +Anything that cannot be read answers no, and the wearer holds to pay as without QuickPay: no rate, a settings file +or a count that cannot be read. + +- **Daily limit.** `QuickPaySpendStore` keeps one day and its spend in cents in the settings file, which the wipe + clears. A payment is counted when QuickPay lets it out, before it is sent. As on the phone, it is taken out + again when it did not go out, as when the wearer turned out to have looked away meanwhile, and when it failed + (`PaymentsRepo.send`), and when the send flow was closed while QuickPay was decided. It stays counted when it + was paid, when it is still pending, when its outcome is unknown and when the send ended in an error the watch + does not know. The phone goes on to take out a pending payment that fails later, from its ledger; the watch keeps no + ledger, so that one stays counted, and so does a payment the app was closed during. The count can only run ahead + of what was paid, never behind. The day is the watch's local date; a date earlier than the one last counted + starts no new count, so setting the watch's clock back frees nothing. +- **Known gap: a change on the phone takes an import to arrive.** QuickPay turned off or lowered on the phone + applies on the watch from the first import after the phone uploaded its settings. A watch that cannot read the + 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) + 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 + 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 + the watch; turning QuickPay off on the phone is the wearer's way to rule it out. +- **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. + +## 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 +from VSS and never writes there. + +- **What the phone stores.** The phone uploads its whole settings file as the backup category `SETTINGS`: one JSON + envelope (`SettingsBackupV1`) with `version` 1, `createdAt` and `settings` (`BackupRepo.getBackupDataBytes`, + `SettingsData` in the phone's `SettingsStore.kt`), stored on VSS under the key `SETTINGS`. The phone uploads it + about 5 s after a setting changes. The phone reads a bitkit-ios backup under the same keys, with enums in + Swift's form (`BackupJson.kt`), and the watch reads those the same way; no bitkit-ios backup was tried. +- **What the watch adopts.** Six of those keys, and nothing else: + - `primaryDisplay` (bitcoin or fiat first) and `displayUnit` (`MODERN` for sats, `CLASSIC` for bitcoin with + eight decimals). The balance, the send review and result, the paid receive and the activity list and detail + are written in that unit; the amount entry of a send stays in sats. + - `selectedCurrency`, the fiat currency. + - `isQuickPayEnabled`, `quickPayAmount` (US dollars) and `quickPayDailyLimitMultiplier`. + + The phone stores no other QuickPay value and no watch-specific limit; none is invented here. +- **Access.** `VssPhoneBackupReader` sets vss-client up exactly as the phone's `VssBackupClient` and + `VssStoreIdProvider` do: the server (`Env.vssServerUrl`), the store id derived from the recovery phrase and + passphrase with the prefix `bitkit_v1_` plus the network name, and the LNURL-auth sign-in + (`Env.lnurlAuthServerUrl`) whose key the library derives from the same seed. The library decrypts the object with + a key from the seed too. Dev and tnet builds use Blocktank's staging servers, as the phone does; the phone's + `E2E_VSS_SERVER_URL` override for local backup tests has no counterpart on the watch. +- **Kept equal to the phone.** `wear/src/test/resources/phone-backup-contract.json` holds what the watch relies on: + the backup's key, the six settings in the phone's encoding, and each network's store id prefix and two servers. + The phone's `WatchBackupContractTest` compares it with what the phone app's own serializer writes and with the + phone's `Env` for the network it is built for; the watch's `PhoneBackupContractTest` reads the same file with the + watch's parser and compares the watch's `Env` for every network. A renamed setting or a moved server fails one of + them. The phone's values for mainnet and testnet are compared only when its tests run in a build for that network. +- **Read-only, by structure.** `PhoneBackupReader` is the watch's only way to VSS and has one call, a read of one + key. Its implementation is the only source file that names the VSS library, and it imports four of its + functions, derive the store id, sign in, get one object, shut the client down, and its error type. + `PhoneBackupReaderTest` fails the + build when the interface gains a call, when another file names the library, or when any source names one of the + library's store, delete, put, list or LDK calls. The sign-in itself asks the LNURL-auth server for a token and + changes nothing on VSS; in the library's source the client's constructor and its get make no put or delete + request (read at the head of synonymdev/vss-rust-client-ffi on 2026-11-28; the shipped binary is 0.5.26-rc2). +- **No client kept.** The library keeps one client for the process, with keys derived from the seed. Each import + builds it, reads and shuts it down, so nothing of the wallet stays in it once the read is over. The library runs + each of its calls to the end on the calling thread (`block_on`), so a read cannot be interrupted: one that was + given up is abandoned, ends with the HTTP call it is in and only then shuts its client down. Until then, a + moment after a lock or a pause, the client is still alive. +- **The library's timeouts** (read in synonymdev/vss-rust-client-ffi at `v0.5.26-rc2` and its `vss-client-ng` + 0.4.0). Each request to the VSS server ends after 10 s, for the connection, for a read and in all, and a failed + one is tried again up to 10 times with at most 15 s of pauses in total, so a read of the backup ends by itself. + The sign-in before it does not: the LNURL-auth requests go through an HTTP client built without a timeout. A + sign-in server that accepts the connection and never answers would hold the read, and the reader behind it, + until the connection drops, and every later import would wait its 30 s behind it and import nothing until the + app's process ends. The watch then goes on with the settings last imported, and a tap on the Phone settings row + shows the failure. A timeout there has to come from the library. +- **Who waits.** `SettingsSyncRepo` runs each import in a scope of its own, and the read apart from the import. + A caller only waits: one that is cancelled returns at once, and the import goes on and lands. The import stops waiting for its read after 30 s or when the wallet stops being + ready, at once in both cases, and then writes nothing. +- **When.** While Home is open, each time the wallet is ready with the app on screen and out of ambient mode, so at + every start, every return to the app and every wake from ambient mode, and every 5 minutes from then; and on a tap on the Phone settings row. An import + within a minute of the last read of this wallet's backup is skipped (`MIN_READ_GAP`), so a wallet that keeps + losing and finding its network does not sign in each time; the tap is never skipped. None is started in the + background or in ambient mode, and none for a wallet that is not connected and synced: a read under way is given + up the moment the wallet stops being ready, as on a lock or a pause, whoever started it, and its client is shut + down when its HTTP call returns. An import under way when the watch goes ambient or its caller leaves still + lands. Reading takes about 2 s; it is given up after 30 s. +- **Outcomes.** A backup that was read replaces the six values. The phone's `primaryDisplay` is adopted when it + differs from the one last imported, so the wearer's own swap on the balance lasts until the phone's setting + changes. A display value the backup lacks, or holds in a form the watch cannot read, keeps the watch's. A backup + that is missing, cannot be decrypted or decoded, is not the envelope, or has a `version` above 1 keeps the display + values and turns QuickPay off at once. The library reports an object it fetched and cannot decrypt or decode as + its get error and every failure to reach the server or sign in as another error (read in + synonymdev/vss-rust-client-ffi), so `VssPhoneBackupReader` takes a get error for an unreadable backup. QuickPay + values that are missing, mistyped or out of the phone's range turn QuickPay off. A read that fails, as without a + network, changes nothing, and QuickPay goes on with the settings last imported. Failures are + logged and never thrown. Only the wearer's own tap shows one, as one line under the row + (`WatchSettingsSyncFailed`, "Couldn't import"), until the next tap. +- **Parsing.** `PhoneSettingsParser` reads the JSON tree key by key rather than into the phone's settings class, so + unknown keys, new settings and other types never fail it. An envelope above 256 KB is refused. +- **Wipe.** Everything imported lives in the settings file, which the wallet's wipe clears: the units, the + currency, QuickPay, the import time and the day's QuickPay spend. An import that a wipe overtook is taken out + again, so a removed wallet's settings never reach the next wallet. +- **Logging.** The import logs its outcome only. The seed, the store id and the backup's content are never logged. +- **Size.** vss-client adds `libvss_rust_client_ffi.so` to the watch app: 4.3 MB for `arm64-v8a`, 2.8 MB for + `armeabi-v7a` and 4.8 MB for `x86_64`, about 2.0 MB gzipped for arm64, plus about 0.2 MB of bindings in the + debug dex. It ships its own R8 rules, and `:wear:minifyDevReleaseWithR8` passes with it. +- **Checked on the emulator.** On the API 37 emulator a dev build signed in to the staging VSS and imported the + 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. ### Self-send guard @@ -566,3 +754,7 @@ Measured on the emulator (Wear OS 7, API 37, 454×454 round, x86_64) unless note the screen off. - Re-wrapping the seed under an unlocked-device key when the wearer adds a screen lock after restoring. - 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 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/README.md b/journeys/README.md index e6ba53a396..d3debdcb68 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -139,6 +139,7 @@ journey PR, which is what made this file conflict on every merge. | Deep links, addresses and invoices handed to the app | `adb shell am start -a android.intent.action.VIEW -d ""`; `bitkit://` screen and sheet routes sit behind the dev-mode gate — [Running a journey](#running-a-journey), [deeplinks](deeplinks) | | A watch to run the Wear OS app on | a Wear OS watch emulator (`Wear_Large_Round_API37`, `Wear_Small_Round_API34`), or a physical watch over Wi-Fi debugging — [wear](wear/README.md) | | Watch gestures: pager swipes, swipe-to-dismiss, rotary crown, ambient mode | `adb shell input swipe`, `adb shell input rotaryencoder scroll --axis SCROLL,` and `KEYCODE_SLEEP`/`KEYCODE_WAKEUP` on the emulator; the real crown, bezel and wrist on a physical watch — [wear](wear/README.md#watch-gestures) | +| The phone's settings on the watch (units, currency, QuickPay) | a phone dev build with the same private settings wallet (the test phrase with a passphrase kept on this machine), never the public test phrase alone, writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) | | Typing on the watch keyboard | `adb shell input text` after closing the Wear OS keyboard with Back, which otherwise swallows the input — [wear](wear/README.md#typing) | ## Cross-platform diff --git a/journeys/wear/README.md b/journeys/wear/README.md index 71cbb2973e..0c0e287425 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -125,11 +125,34 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `activity-list.xml` | local | yes, after `receive-paid.xml` and `send-deeplink-bolt11.xml` | | `receive-paid-ambient.xml` | local | no, it funds the wallet with 1 000 sats | | `tile-balance.xml` | hosted or local | no | - -Paying an LNURL-pay link or a Lightning address has no journey: the local stack's LNURL server serves only the -Lightning addresses its Spark wallets registered, over plain HTTP, and nothing in it registers one. It is covered by -`PaymentsRepoTest.kt` and `SendViewModelTest.kt`, which check the range, the amount entry and the invoice the service -returns. +| `settings-import-units.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, any balance above 0 | +| `settings-swap-survives-import.xml` | as `settings-import-units.xml`, after it | yes, any balance above 0 | +| `quickpay-skips-hold.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, 2 000 sats | +| `quickpay-on-app-start.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | +| `quickpay-over-limit-holds.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, 12 000 sats | +| `quickpay-off-holds.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | + +The six settings journeys read the phone's settings backup from Blocktank's hosted staging VSS, which every dev +build uses whatever its Spark network is: a watch on the local `./spark` stack reads the same backup as one on hosted +regtest. Nothing extra runs locally, no VSS and no LNURL-auth server. They need a phone app that wrote the backup +first: see [Phone settings on VSS](#phone-settings-on-vss). They never run on the public test phrase, whose backup +every other journey reads too: see [Private settings wallet](#private-settings-wallet). + +The daily QuickPay limit, a failed QuickPay payment that is taken out of the day's count, an amount the wearer +typed, and a missing, unreadable or newer backup have no journey: they depend on the exchange rate of the day, a +payment that fails on demand, an amountless invoice the local stack does not make, or a backup only a broken phone +would write. `QuickPayRepoTest.kt`, `QuickPaySpendStoreTest.kt`, `PaymentsRepoTest.kt`, `SettingsSyncRepoTest.kt` +and `PhoneSettingsParserTest.kt` cover them. + +A payment link opened again from Recents, which the watch takes as a plain launch, has no journey either: it was +not tried on a device, and `ReplayedLaunchTest.kt` covers the check. To try it by hand: with the app not running, +open a link as in `send-deeplink-bolt11.xml`, leave the review and Home with Back, open Bitkit from the watch's +Recents and check that Home shows and `WatchSendHold` does not. + +Paying an LNURL-pay link or a Lightning address has no journey, under QuickPay or with the hold: the local stack's +LNURL server serves only the Lightning addresses its Spark wallets registered, over plain HTTP, and nothing in it +registers one. It is covered by `PaymentsRepoTest.kt` and `SendViewModelTest.kt`, which check the range, the amount +entry, the invoice the service returns and that only a link with one amount goes out under QuickPay. ### Local `./spark` stack @@ -149,7 +172,7 @@ regtest. A local wallet is new to that chain, so it starts at 0. ### Funding the test wallet On the local stack, `receive-paid.xml` funds the watch through its own receive QR. Otherwise, or for an on-chain -deposit, take the deposit address or invoice from the phone app with the same recovery phrase: restore [the test wallet](#the-test-wallet) in a phone dev build on the same Spark network, read the +deposit, take the deposit address or invoice from the phone app with the same recovery phrase: restore [the test wallet](#the-test-wallet) in a phone dev build on the same Spark network (and change none of its settings there, see [Private settings wallet](#private-settings-wallet)), read the Spark deposit address at Settings › Advanced › Lightning Connections › Spark (`SparkDepositAddress`), fund it, then close the phone app before you start the watch again. Two live Spark instances on one seed are unsafe (#2152), so never keep both open. @@ -213,6 +236,146 @@ The test wallet restored with no passphrase, its balance loaded, Bitcoin as the A wallet restored by an earlier journey can stay: only [Fresh app](#fresh-app) and `remove-wallet.xml` remove it. +The watch imports the settings backup of whatever phrase it holds, so these journeys count on the public phrase's +backup holding the phone's defaults (Bitcoin first, sats, USD, QuickPay off) or not existing. If the balance shows +another currency or eight decimals, a phone app changed that backup: run the journeys with a private 12-word phrase +of your own instead, which they support (see [The test wallet](#the-test-wallet)). That phrase's phone settings must +be at their defaults too, so not the [Private settings wallet](#private-settings-wallet), whose backup holds +whatever the last settings journey set. + +### Private settings wallet + +Every journey that changes the phone's settings (`settings-*.xml`, `quickpay-*.xml`) runs on a wallet of its own, +never on the public test phrase. That phrase's settings backup is one object on the hosted staging VSS, shared by +hosted regtest and the local `./spark` stack and by everyone who restores the phrase: fiat first, euros or QuickPay +written there would reach every other watch on that phrase and break the journeys that expect the defaults. + +The private wallet is the public test phrase with a passphrase made on this machine. With a passphrase the phrase +is another wallet, with a settings backup of its own, so each machine's settings journeys stay apart from everyone +else's. + +The passphrase is not a secret. The phrase it is added to is public and the wallet holds regtest coins of no value; +the passphrase only keeps one machine's settings backup apart from another's. It may show in a layout dump or a +screenshot on your own machine. It still must not leave the machine, since anyone who has it can write to the same +backup: never commit it, never put it in a journey file, a pull request's text or media, and never paste it into an +issue. A screenshot or a recording of the phone's restore screen, or of the watch's passphrase screen, is not PR +media. + +1. Make the passphrase, once per machine, in a file outside the repository: + + ```bash + F=~/.config/bitkit-journeys/settings-passphrase + mkdir -p "${F%/*}" + [ -s "$F" ] || LC_ALL=C tr -dc a-z0-9 "$F" + ``` + + It keeps a passphrase that is already there. Twelve lowercase letters and digits are short and plain enough for + `adb shell input text`, which drops characters from long or dotted strings. +2. Restore it in the phone app, a plain dev build (see [Phone settings on VSS](#phone-settings-on-vss), step 1). From + a fresh install go through the onboarding to the Restore wallet screen (`RestoreWallet`, then + `MultipleDevices-button`). For each word, tap its field (`Word-0` to `Word-11`) and run + `adb shell input text `: eleven times `abandon`, then `about`. Tap `AdvancedButton`, tap `PassphraseInput` + and type the passphrase: + + ```bash + adb shell input text "$(cat ~/.config/bitkit-journeys/settings-passphrase)" + ``` + + [Check it](#checking-the-passphrase), then tap `RestoreButton`. +3. Set the phone's settings to where the journeys start: Default Unit Bitcoin, Denomination Modern, Local Currency + USD and QuickPay off. A new wallet has them already. On a rerun the restore brings back whatever the last run + left, as the currency first, Classic and EUR after a run that stopped at `settings-import-units.xml`: set them + back and keep the app open for 20 s, so it uploads them + ([Phone settings on VSS](#phone-settings-on-vss), steps 3 and 4). Then close the phone app + (`adb shell am force-stop to.bitkit.dev`). +4. Restore it on the watch: [Restored wallet](#restored-wallet) steps 1 to 3, then tap `RestorePassphraseAdd` + instead of `RestorePassphraseSkip`, tap `RestorePassphraseInput`, close the keyboard with Back + ([Typing](#typing)) and run the same `adb shell input text "$(cat …)"` command. [Check it](#checking-the-passphrase), + tap `RestorePassphraseConfirm` and wait for `WatchHomeBalance`. It reads `0` for a wallet that was never funded; + on a rerun against a local stack that kept its data it reads what the last run left. +5. Fund it before the phone's settings change: on the local `./spark` stack run `receive-paid.xml` on this wallet + while the phone's settings are still the ones of step 3. That journey expects "50 000", which is what a watch + on Bitcoin and Modern shows for a wallet that held nothing; after `settings-import-units.xml` set Classic, the + same payment reads "0.00050000". On a rerun with at least 12 000 sats left, skip this step. +6. Only now set what a journey asks for on the phone: [Phone settings on VSS](#phone-settings-on-vss). + +One private wallet serves all six journeys, in the order of the table: the settings journeys first, then the +QuickPay ones, whose preconditions set the units and the currency back. Remove it from the watch +(`remove-wallet.xml` or [Fresh app](#fresh-app)) before the journeys on the public phrase run again. + +To start over with an empty backup, delete `~/.config/bitkit-journeys/settings-passphrase` and begin at step 1: a +new passphrase is a new wallet with no backup and no balance. + +#### Checking the passphrase + +`adb shell input text` can drop a character, and a passphrase that differs by one names another wallet with no +backup. Check the field before you confirm: the layout dump has to hold the passphrase as typed, so this prints `1` +or more. + +```bash +android layout | grep -c -F "$(cat ~/.config/bitkit-journeys/settings-passphrase)" +``` + +On `0`, select all in the field, delete and type again, with the key events of +[Replacing a word](#replacing-a-word), then check again. The proof that phone and watch hold the same wallet comes +with the first import after step 6: the watch logs `Imported the phone's settings` once the phone wrote its backup. +It logs `Found no settings backup of the phone` when the two differ, and also before the phone ever changed a +setting. + +### Phone settings on VSS + +The watch never writes settings; it imports the ones a phone app backed up for the same recovery phrase +(Settings sync in [docs/wear.md](../../docs/wear.md)). So a phone has to write them first, once per journey that +names this precondition: + +1. Stop the watch emulator if this machine runs one emulator at a time, and start a phone emulator or connect a phone + ([journeys/README.md](../README.md) has the phone setup). Install a plain dev build of the phone app there with + `just install`: not an E2E build with `E2E_VSS_SERVER_URL` set, which would back up to a local server the watch + never reads. +2. Use the [Private settings wallet](#private-settings-wallet) in the phone app, restored there with its + passphrase. Never restore the public test phrase without that passphrase in a phone app to change its settings. + The recovery phrase and passphrase must be the same on phone and watch, since they name the backup. +3. Set what the journey asks for in the phone's Settings (`HeaderMenu`, `DrawerSettings`, `Tab-general`): + - Default Unit (`UnitSettings`): Bitcoin or the currency first, and the denomination (`DenominationModern`, + `DenominationClassic`). + - Local Currency (`CurrenciesSettings`). + - The QuickPay journeys read sats and dollars, so each of them asks for Default Unit Bitcoin, Denomination Modern + and Local Currency USD besides its QuickPay values: `settings-import-units.xml` leaves the wallet on the + currency, Classic and EUR. + - QuickPay (`QuickpaySettings`, past `QuickpayIntro-button` the first time): the switch (`QuickpayToggle`), the + amount (`QuickpayAmountSlider`, stops $1 to $50) and the daily limit (`QuickpayDailyLimitSlider`, 1× to 50×). + Tap the slider track above a stop's label, as in `settings/quickpay-payment-pin.xml`. +4. Keep the phone app open and online for 20 s: it uploads the settings about 5 s after the last change. Settings › + Security › Data Backups (`BackupSettings`) lists Settings with the time of its last backup. +5. Close the phone app (`adb shell am force-stop to.bitkit.dev` on the phone). The phone and the watch must never be + open on the same Spark network with one recovery phrase at the same time (#2152). +6. Start the watch again. It imports the settings when its wallet is ready, at every start and every 5 minutes, but + not within a minute of the last import and not in ambient mode; a tap on `WatchSettingsSync` on the Settings page + imports at once, and shows `WatchSettingsSyncFailed` when it could not. Debug builds log + `Imported the phone's settings`: + + ```bash + adb logcat -d -s BitkitWear | grep "SettingsSyncRepo" + ``` + +**Gotcha:** the public test phrase's backup belongs to everyone who restores it on a dev build, so its settings can +change without notice. That is why no settings journey reads or writes it, and why a phone app that holds the public +phrase without a passphrase, as for [Funding the test wallet](#funding-the-test-wallet), must leave its units, currency and QuickPay at +their defaults. + +**Gotcha:** QuickPay pays only a link that the wearer is there for: the send has to be priced within 30 s of the +link, with the watch unlocked, the app on screen and out of ambient mode all that time. A journey that sends its link +to a watch that is asleep, locked or still connecting for longer gets the review and the hold instead. A watch that +is offline gets neither: the flow ends on "Can't pay offline" and the link is dropped (`send-offline-error.xml`). + +**Gotcha:** the daily limit is counted per watch and per day on the watch's date, and every run of a paying QuickPay +journey adds to it. After about a dozen runs on one day the next one gets the review and the hold, and +`WatchSendSent` never shows. `remove-wallet.xml` or clearing the watch app's data clears the count; so does the next +day. + +**Never install the phone app on the watch or the watch app on the phone:** they share one application id. +`just install` and `just wear-install` each pick a device by `ANDROID_SERIAL`; set it before every install. + ### Restart The journeys restart the app with: diff --git a/journeys/wear/quickpay-off-holds.xml b/journeys/wear/quickpay-off-holds.xml new file mode 100644 index 0000000000..aa17ea6546 --- /dev/null +++ b/journeys/wear/quickpay-off-holds.xml @@ -0,0 +1,28 @@ + + + QuickPay turned off on the phone stops on the watch with the next import: the same small invoice that QuickPay + paid by itself now opens the review and waits for the hold. A watch that never imported the phone's settings + behaves the same. Emulator and physical watch. + + Precondition: run quickpay-skips-hold.xml first, on its Private settings wallet and never the public test phrase + alone. Then, on the phone with the same wallet, turn QuickPay off and leave Default Unit Bitcoin, Denomination + Modern and Local Currency USD as that journey set them, so the amount below reads in sats; wait for the backup + and close the phone app, see journeys/wear/README.md › Phone settings on VSS. Watch: the + wallet of quickpay-skips-hold.xml on the local ./spark stack with at least 2 000 sats, the app open on the Balance + page and the loading ring stopped. README › Holding to pay has the hold gesture. + + + Swipe left three times to the Settings page (README › Watch gestures) + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Swipe right three times to the Balance page + Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendHold" is listed + Verify "WatchSendAmount" reads "200" + Verify "WatchSendSent" does not get listed within 5 s: nothing was paid + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + + diff --git a/journeys/wear/quickpay-on-app-start.xml b/journeys/wear/quickpay-on-app-start.xml new file mode 100644 index 0000000000..e309cb8d11 --- /dev/null +++ b/journeys/wear/quickpay-on-app-start.xml @@ -0,0 +1,25 @@ + + + A payment link that starts the app is paid under QuickPay too: the watch reads the settings it last imported + from the phone, however long ago, as the phone reads its own, and fetches the rates it does not keep across a + restart before it decides. The send goes out without the review and the hold. Emulator, or a physical watch that + stays on the wrist and unlocked. + + Precondition: run quickpay-skips-hold.xml first, so the watch's last import has QuickPay on with Default Unit + Bitcoin, Denomination Modern and Local Currency USD, which the amount below counts on, and change nothing on the + phone since. Watch: the wallet of quickpay-skips-hold.xml on the local ./spark stack with at least 2 000 sats and + a network on which the balance comes back within 20 s of a start. A wallet that needs more than 30 s shows the + review and the hold instead, which is as designed and fails this journey. So does a locked watch: KEYCODE_WAKEUP + lights the screen and unlocks nothing, and QuickPay never pays on a locked watch. + + + Run `adb shell am force-stop to.bitkit.dev` + Run `adb shell input keyevent KEYCODE_WAKEUP` + Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> + Run `adb logcat -c` + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev`, which starts the app + Wait up to 40 s until "WatchSendSent" is listed, touching nothing + Verify "WatchSendResultAmount" reads "200" + Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" + + diff --git a/journeys/wear/quickpay-over-limit-holds.xml b/journeys/wear/quickpay-over-limit-holds.xml new file mode 100644 index 0000000000..3fc1dc40f8 --- /dev/null +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -0,0 +1,28 @@ + + + With QuickPay on in the phone's settings, an invoice above the phone's QuickPay amount still opens the review and + is paid only by the hold. Emulator and physical watch. + + Precondition, in this order, as quickpay-skips-hold.xml: Private settings wallet, never the public test phrase + alone, restored on the watch on the local ./spark stack and funded there with at least 12 000 sats before any + phone setting changed (journeys/wear/README.md › Private settings wallet, step 5). Then Phone settings on VSS, + see README › Phone settings on VSS, with Default Unit Bitcoin, Denomination Modern, Local Currency USD and + QuickPay on at $1 and 5×, and the phone app closed. Watch: the app open on the Balance page and the loading ring + stopped. The fiat value below is in dollars, which is what those units give. 10 000 sats are above $1 while a bitcoin costs more than $10 000. README › Holding to pay + has the hold gesture. + + + Swipe left three times to the Settings page (README › Watch gestures) + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Swipe right three times to the Balance page + Wait up to 1 minute until "WatchHomeBalanceSecondary" reads a fiat value: without the rates QuickPay holds whatever the amount + Run `../bitkit-docker/spark invoice 10000` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendHold" is listed + Verify "WatchSendSent" does not get listed within 5 s: nothing was paid + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + + diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml new file mode 100644 index 0000000000..513ea02e9d --- /dev/null +++ b/journeys/wear/quickpay-skips-hold.xml @@ -0,0 +1,31 @@ + + + With QuickPay on in the phone's settings, an invoice under the phone's QuickPay amount is paid without the review + and without the hold: the link goes straight to sending and the same "Sent" check, and the flow closes by itself. + Emulator and physical watch. + + Precondition, in this order: Private settings wallet, see journeys/wear/README.md › Private settings wallet, + never the public test phrase alone, restored on the watch on the local ./spark stack (README › Local ./spark + stack) and funded there with at least 2 000 sats before any phone setting changed (README › Private settings + wallet, step 5). Then Phone settings on VSS, see README › Phone settings on VSS, with Default Unit Bitcoin, + Denomination Modern, Local Currency USD, QuickPay on at $1 and the daily limit at 5× on the phone, and the phone + app closed. Watch: the app open on the Balance page and the loading ring stopped. The amounts below are in sats + and the fiat value in dollars, which is what those units give. The watch reads the phone's settings from the + hosted staging VSS whatever Spark network it is on. 200 sats are under $1 while a bitcoin costs less than + $500 000. + + + Swipe left three times to the Settings page (README › Watch gestures) + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Swipe right three times to the Balance page + Wait up to 1 minute until "WatchHomeBalanceSecondary" reads a fiat value: QuickPay needs the rates + Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> + Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` + Wait up to 20 s until "WatchSendSent" is listed, touching nothing + Verify "WatchSendResultAmount" reads "200" + Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" + Wait up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself + + diff --git a/journeys/wear/receive-paid.xml b/journeys/wear/receive-paid.xml index b28c58af0c..72d42d017b 100644 --- a/journeys/wear/receive-paid.xml +++ b/journeys/wear/receive-paid.xml @@ -3,8 +3,12 @@ Paying the receive QR's invoice turns the QR into a check with the amount, with a firm haptic; a tap on the check shows a new invoice. This also funds the wallet for the send journeys. Emulator and physical watch. - Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and - › Restored wallet, on the Balance page with the loading ring stopped. Gestures are written for the 454 px screen. + Precondition: a wallet restored on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack: the + Restored wallet (README › Restored wallet), or the Private settings wallet (README › Private settings wallet) + when this funds it for the settings and QuickPay journeys. Either way the phone's settings of that wallet are + still the defaults, Bitcoin first and Denomination Modern, so the paid amount reads in sats: on the private + wallet run this before any settings journey, since under Classic the same amount reads "0.00050000". The app is + on the Balance page with the loading ring stopped. Gestures are written for the 454 px screen. The haptic cannot be checked over adb; feel it on a physical watch. diff --git a/journeys/wear/settings-import-units.xml b/journeys/wear/settings-import-units.xml new file mode 100644 index 0000000000..2d14787e86 --- /dev/null +++ b/journeys/wear/settings-import-units.xml @@ -0,0 +1,26 @@ + + + The watch adopts the phone's units and currency from the phone's settings backup: fiat first, euros, and bitcoin + written with eight decimals. The Settings page shows when the phone's settings were last imported, and a tap on + that row imports them again. Emulator and physical watch. + + Precondition, in this order: Private settings wallet, see journeys/wear/README.md › Private settings wallet, + never the public test phrase alone, restored on the watch on the local ./spark stack (README › Local ./spark + stack) and funded there with a balance above 0 before any phone setting changed (README › Private settings + wallet, step 5: receive-paid.xml reads its amount in sats). Only then Phone settings on VSS, see README › Phone + settings on VSS, with Default Unit set to the currency, Denomination set to Classic, Local Currency set to EUR + and QuickPay off on the phone, and the phone app closed. + + + Restart the app (README › Restart) + Dump `android layout` every 5 s until "WatchHomeBalanceSymbol" reads "€", for up to 1 minute: the import follows the first sync, and the rates load after the balance + Verify "WatchHomeBalanceSecondary" reads the balance in bitcoin with eight decimals, such as "0.00050000" + Swipe left three times to the Settings page (README › Watch gestures) + Verify "WatchSettingsSync" is listed and reads "Phone settings" + Verify "WatchSettingsSyncTime" reads a time of at most a few minutes ago, such as "0 min. ago" + Run `adb logcat -c` + Tap "WatchSettingsSync" + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Verify "WatchSettingsSyncFailed" is not listed + + diff --git a/journeys/wear/settings-swap-survives-import.xml b/journeys/wear/settings-swap-survives-import.xml new file mode 100644 index 0000000000..8b218b1ab4 --- /dev/null +++ b/journeys/wear/settings-swap-survives-import.xml @@ -0,0 +1,21 @@ + + + The wearer's own swap of the balance's unit lasts across an import of the phone's settings, as long as the phone's + setting stays the same: with fiat first on the phone, a tap puts bitcoin first on the watch, and it is still first + after a restart and the import that follows it. Emulator and physical watch. + + Precondition: run settings-import-units.xml first, and change nothing on the phone since. Watch: the wallet of + settings-import-units.xml, the app open on the Settings page, where that journey ends. + + + Swipe right three times to the Balance page (README › Watch gestures) + Verify "WatchHomeBalanceSymbol" reads "€" + Tap "WatchHomeBalanceToggle" + Verify "WatchHomeBalanceSymbol" reads "₿" + Verify "WatchHomeBalance" reads the balance with eight decimals, such as "0.00050000" + Run `adb logcat -c` + Restart the app (README › Restart) + Wait up to 1 minute until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" + Verify "WatchHomeBalanceSymbol" still reads "₿": the wearer's swap lasts while the phone's setting stays the same + + diff --git a/wear/build.gradle.kts b/wear/build.gradle.kts index 1e7e270c23..85d12e9b6c 100644 --- a/wear/build.gradle.kts +++ b/wear/build.gradle.kts @@ -230,6 +230,8 @@ dependencies { implementation(libs.bitkit.core) implementation(libs.zxing) implementation(libs.breez.sdk.spark) { exclude(group = "net.java.dev.jna", module = "jna") } + // Read-only import of the phone's settings backup; see docs/wear.md, Settings sync. + implementation(libs.vss.client) // Lifecycle implementation(libs.lifecycle.viewmodel.compose) implementation(libs.lifecycle.runtime.compose) diff --git a/wear/src/main/java/to/bitkit/wear/data/AmbientMonitor.kt b/wear/src/main/java/to/bitkit/wear/data/AmbientMonitor.kt new file mode 100644 index 0000000000..b8d1314031 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/AmbientMonitor.kt @@ -0,0 +1,20 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Whether the watch shows the app dimmed in ambient (always-on) mode, where nobody is taken to be looking. The + * activity reports it, so what runs outside the screens can tell ambient mode from the app in use. + */ +@Singleton +class AmbientMonitor @Inject constructor() { + private val _isAmbient = MutableStateFlow(false) + val isAmbient: StateFlow = _isAmbient.asStateFlow() + + fun set(isAmbient: Boolean) = _isAmbient.update { isAmbient } +} diff --git a/wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt b/wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt new file mode 100644 index 0000000000..6f6c5d88b7 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt @@ -0,0 +1,9 @@ +package to.bitkit.wear.data + +/** + * The time since the watch booted, in milliseconds. Unlike the wall clock it cannot be set, and unlike + * `System.nanoTime` it keeps counting while the watch sleeps, so it measures how old something is. + */ +fun interface ElapsedClock { + fun nowMs(): Long +} diff --git a/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt new file mode 100644 index 0000000000..959a3771fd --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt @@ -0,0 +1,54 @@ +package to.bitkit.wear.data + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.longPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import javax.inject.Inject +import javax.inject.Singleton + +/** What the watch's QuickPay payments added up to today, in US cents, for the daily limit. */ +interface QuickPaySpendStore { + /** + * Adds [cents] to the spend of [dayKey], an ISO date, unless that takes the day above [capCents]. Returns the day + * it was added to, or null when it was not. A day earlier than the one last counted does not start a new count: + * the payment is added to the day last counted, so setting the watch's date back frees nothing. + */ + suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? + + /** Takes [cents] out of the spend of [dayKey] again, when that is still the day counted. */ + suspend fun release(dayKey: String, cents: Long) +} + +/** [QuickPaySpendStore] in the watch's settings file, so the wallet's wipe clears it with the settings. */ +@Singleton +class SettingsQuickPaySpendStore @Inject constructor( + private val dataStore: DataStore, +) : QuickPaySpendStore { + private val dayKey = stringPreferencesKey("quickpay_spend_day") + private val centsKey = longPreferencesKey("quickpay_spend_cents") + + override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? { + if (cents <= 0 || capCents <= 0) return null + var reservedDay: String? = null + dataStore.edit { prefs -> + val countedDay = prefs[this.dayKey] + val day = if (countedDay == null || dayKey > countedDay) dayKey else countedDay + val spent = if (day == countedDay) prefs[centsKey] ?: 0L else 0L + if (spent < 0 || cents > capCents - spent) return@edit + prefs[this.dayKey] = day + prefs[centsKey] = spent + cents + reservedDay = day + } + return reservedDay + } + + override suspend fun release(dayKey: String, cents: Long) { + if (cents <= 0) return + dataStore.edit { prefs -> + if (prefs[this.dayKey] != dayKey) return@edit + prefs[centsKey] = ((prefs[centsKey] ?: 0L) - cents).coerceAtLeast(0L) + } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt b/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt index 64bd5d18fc..b14363bd5f 100644 --- a/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt @@ -2,17 +2,23 @@ package to.bitkit.wear.data import androidx.datastore.core.DataStore import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import androidx.datastore.preferences.core.MutablePreferences import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.QuickPayLimits import to.bitkit.wear.models.USD import java.io.File import javax.inject.Inject @@ -29,7 +35,10 @@ fun settingsDataStore(scope: CoroutineScope, produceFile: () -> File): DataStore produceFile = produceFile, ) -/** The watch's display preferences and the wallet wipe's progress notes. It holds nothing secret. */ +/** + * The watch's display preferences, what it imported from the phone's settings, and the wallet wipe's progress notes. + * It holds nothing secret. + */ @Singleton class SettingsStore @Inject constructor( private val dataStore: DataStore, @@ -38,6 +47,12 @@ class SettingsStore @Inject constructor( private val primaryDisplayKey = stringPreferencesKey("primary_display") private val selectedCurrencyKey = stringPreferencesKey("selected_currency") private val removedNoticeKey = booleanPreferencesKey("wallet_removed_notice") + private val displayUnitKey = stringPreferencesKey("display_unit") + private val phonePrimaryDisplayKey = stringPreferencesKey("phone_primary_display") + private val quickPayEnabledKey = booleanPreferencesKey("quickpay_enabled") + private val quickPayAmountKey = intPreferencesKey("quickpay_amount_usd") + private val quickPayMultiplierKey = intPreferencesKey("quickpay_daily_multiplier") + private val phoneSyncedAtKey = longPreferencesKey("phone_settings_synced_at") val data: Flow = dataStore.data.map { prefs -> WatchSettings( @@ -45,9 +60,72 @@ class SettingsStore @Inject constructor( ?.let { runCatching { PrimaryDisplay.valueOf(it) }.getOrNull() } ?: PrimaryDisplay.BITCOIN, selectedCurrency = prefs[selectedCurrencyKey] ?: USD, + displayUnit = prefs[displayUnitKey] + ?.let { runCatching { BitcoinDisplayUnit.valueOf(it) }.getOrNull() } + ?: BitcoinDisplayUnit.MODERN, + quickPay = quickPay(prefs), + phoneSyncedAtMs = prefs[phoneSyncedAtKey], ) } + private fun quickPay(prefs: Preferences): QuickPayLimits? { + val amountUsd = prefs[quickPayAmountKey] ?: return null + val multiplier = prefs[quickPayMultiplierKey] ?: return null + return QuickPayLimits(prefs[quickPayEnabledKey] == true, amountUsd, multiplier) + } + + /** + * Adopts [settings], read from the phone's backup at [syncedAtMs]. A display value the backup does not hold + * keeps the watch's. The phone's primary display is adopted when it differs from the one last imported, so the + * wearer's own swap on the balance lasts until the phone's setting changes. QuickPay is replaced as a whole and + * is off when the backup's values cannot be read. + */ + suspend fun applyPhoneSettings(settings: PhoneSettings, syncedAtMs: Long) { + dataStore.edit { prefs -> + settings.primaryDisplay?.let { + if (prefs[phonePrimaryDisplayKey] != it.name) prefs[primaryDisplayKey] = it.name + prefs[phonePrimaryDisplayKey] = it.name + } + settings.displayUnit?.let { prefs[displayUnitKey] = it.name } + settings.selectedCurrency?.let { prefs[selectedCurrencyKey] = it } + val quickPay = settings.quickPay + if (quickPay == null) { + prefs.clearQuickPay() + } else { + prefs[quickPayEnabledKey] = quickPay.isEnabled + prefs[quickPayAmountKey] = quickPay.amountUsd + prefs[quickPayMultiplierKey] = quickPay.dailyMultiplier + } + prefs[phoneSyncedAtKey] = syncedAtMs + } + } + + /** + * Turns QuickPay off and forgets when the phone's settings were last read, as when the phone's backup is missing + * or cannot be read. The display values stay. + */ + suspend fun clearQuickPay() { + dataStore.edit { prefs -> + prefs.clearQuickPay() + prefs.remove(phoneSyncedAtKey) + } + } + + private fun MutablePreferences.clearQuickPay() { + remove(quickPayEnabledKey) + remove(quickPayAmountKey) + remove(quickPayMultiplierKey) + } + + /** Forgets everything imported from the phone, back to the watch's defaults: an import that a wipe overtook. */ + suspend fun clearPhoneSettings() { + dataStore.edit { prefs -> + prefs.clearQuickPay() + listOf(phoneSyncedAtKey, phonePrimaryDisplayKey, primaryDisplayKey, displayUnitKey, selectedCurrencyKey) + .forEach { prefs.remove(it) } + } + } + suspend fun setPrimaryDisplay(display: PrimaryDisplay) { dataStore.edit { it[primaryDisplayKey] = display.name } } @@ -82,7 +160,14 @@ class SettingsStore @Inject constructor( } } +/** + * [quickPay] is the phone's QuickPay as last imported, or null when none was. [phoneSyncedAtMs] is when the phone's + * settings were last read, in epoch milliseconds, or null when they never were or the last read found none. + */ data class WatchSettings( val primaryDisplay: PrimaryDisplay = PrimaryDisplay.BITCOIN, val selectedCurrency: String = USD, + val displayUnit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN, + val quickPay: QuickPayLimits? = null, + val phoneSyncedAtMs: Long? = null, ) diff --git a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt index 4a929673d6..c50325e683 100644 --- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt +++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt @@ -1,6 +1,7 @@ package to.bitkit.wear.di import android.content.Context +import android.os.SystemClock import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile @@ -15,12 +16,15 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import to.bitkit.wear.data.AdapterNfcMonitor import to.bitkit.wear.data.ConnectivityNetworkMonitor +import to.bitkit.wear.data.ElapsedClock import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.NetworkMonitor import to.bitkit.wear.data.NfcMonitor import to.bitkit.wear.data.OwnInvoiceStore import to.bitkit.wear.data.ProcessForegroundMonitor +import to.bitkit.wear.data.QuickPaySpendStore import to.bitkit.wear.data.SettingsOwnInvoiceStore +import to.bitkit.wear.data.SettingsQuickPaySpendStore import to.bitkit.wear.data.SettingsUncertainSendStore import to.bitkit.wear.data.UncertainSendStore import to.bitkit.wear.data.WipeMarker @@ -36,7 +40,9 @@ import to.bitkit.wear.security.SeedKey import to.bitkit.wear.security.SeedStore import to.bitkit.wear.services.CoreInputDecoder import to.bitkit.wear.services.InputDecoder +import to.bitkit.wear.services.PhoneBackupReader import to.bitkit.wear.services.SelfSendGuard +import to.bitkit.wear.services.VssPhoneBackupReader import to.bitkit.wear.services.WalletSelfSendGuard import java.io.File import javax.inject.Singleton @@ -84,6 +90,14 @@ abstract class SecurityModule { @Singleton abstract fun bindSelfSendGuard(guard: WalletSelfSendGuard): SelfSendGuard + @Binds + @Singleton + abstract fun bindQuickPaySpendStore(store: SettingsQuickPaySpendStore): QuickPaySpendStore + + @Binds + @Singleton + abstract fun bindPhoneBackupReader(reader: VssPhoneBackupReader): PhoneBackupReader + companion object { private const val SEED_DIR = "seed" private const val SETTINGS_NAME = "settings" @@ -103,6 +117,10 @@ abstract class SecurityModule { deviceLock: DeviceLock, ): SeedStore = KeystoreSeedStore(seedDirectory(context), key, deviceLock, isSoftwareKeyAllowed = Env.isDebug) + @Provides + @Singleton + fun provideElapsedClock(): ElapsedClock = ElapsedClock { SystemClock.elapsedRealtime() } + @Provides @Singleton fun provideWipeMarker(@ApplicationContext context: Context): WipeMarker = WipeMarker(seedDirectory(context)) diff --git a/wear/src/main/java/to/bitkit/wear/env/Env.kt b/wear/src/main/java/to/bitkit/wear/env/Env.kt index 726e391de9..5b85496390 100644 --- a/wear/src/main/java/to/bitkit/wear/env/Env.kt +++ b/wear/src/main/java/to/bitkit/wear/env/Env.kt @@ -47,6 +47,25 @@ internal object Env { WalletNetwork.TESTNET -> null } + /** + * The namespace of [network]'s backups on VSS, the phone's `Env.vssStoreIdPrefix`. This and the two servers + * below must equal the phone's: `phone-backup-contract.json` in the tests holds them, and a test on each side + * compares its own values with that file. + */ + fun vssStoreIdPrefix(network: WalletNetwork = this.network): String = "bitkit_v1_${network.name.lowercase()}" + + /** The phone's backup server. The watch only ever reads from it. */ + fun vssServerUrl(network: WalletNetwork = this.network): String = when (network) { + WalletNetwork.BITCOIN -> "https://api.bitkit.to/vss_rs_auth" + else -> "https://bitkit.stag0.blocktank.to/vss_rs_auth" + } + + /** The LNURL-auth server that signs the watch in to [vssServerUrl], as it does the phone. */ + fun lnurlAuthServerUrl(network: WalletNetwork = this.network): String = when (network) { + WalletNetwork.BITCOIN -> "https://bitkit.to/lnurl_auth/auth" + else -> "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" + } + val btcRatesServer: String get() = when (network) { WalletNetwork.BITCOIN -> "https://api1.blocktank.to/api/fx/rates/btc" diff --git a/wear/src/main/java/to/bitkit/wear/models/Currency.kt b/wear/src/main/java/to/bitkit/wear/models/Currency.kt index 768bf3b1cb..5a6a78b5bf 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Currency.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Currency.kt @@ -12,6 +12,7 @@ import java.util.Locale const val BITCOIN_SYMBOL = "₿" const val SATS_IN_BTC = 100_000_000 const val BTC_SCALE = 8 +const val CLASSIC_DECIMALS = 8 const val SATS_GROUPING_SEPARATOR = ' ' const val FIAT_GROUPING_SEPARATOR = ',' const val DECIMAL_SEPARATOR = '.' @@ -48,6 +49,9 @@ enum class PrimaryDisplay { } } +/** How a bitcoin amount is written: [MODERN] in sats, [CLASSIC] in bitcoin with eight decimals, as on the phone. */ +enum class BitcoinDisplayUnit { MODERN, CLASSIC } + /** [sats] in the currency of [rate], or null when the rate is unusable. */ fun fiatValue(sats: Long, rate: FxRate): BigDecimal? { if (rate.rate <= 0.0) return null @@ -66,6 +70,23 @@ fun Long.formatToModernDisplay(locale: Locale = Locale.getDefault()): String { return formatter.format(this) } +fun Long.formatToClassicDisplay(locale: Locale = Locale.getDefault()): String { + val symbols = DecimalFormatSymbols(locale).apply { + decimalSeparator = DECIMAL_SEPARATOR + } + val formatter = DecimalFormat("0.${"0".repeat(CLASSIC_DECIMALS)}", symbols).apply { + minimumFractionDigits = CLASSIC_DECIMALS + maximumFractionDigits = CLASSIC_DECIMALS + isGroupingUsed = false + } + return formatter.format(BigDecimal.valueOf(this).movePointLeft(BTC_SCALE)) +} + +fun Long.formatMoney(unit: BitcoinDisplayUnit, locale: Locale = Locale.getDefault()): String = when (unit) { + BitcoinDisplayUnit.MODERN -> formatToModernDisplay(locale) + BitcoinDisplayUnit.CLASSIC -> formatToClassicDisplay(locale) +} + /** Whether [currencyCode]'s symbol follows the amount, as the phone shows it. */ fun isSymbolSuffix(currencyCode: String): Boolean = currencyCode in SUFFIX_SYMBOL_CURRENCIES diff --git a/wear/src/main/java/to/bitkit/wear/models/Payments.kt b/wear/src/main/java/to/bitkit/wear/models/Payments.kt index 8a605918eb..2438050276 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Payments.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -74,6 +74,12 @@ class PreparedSend internal constructor( * unless an earlier transfer to that wallet is still in doubt: then its key is used again. */ internal val transferKey: String, + /** + * Whether the request fixes the amount, the only kind of send QuickPay covers: a BOLT11 invoice that carries its + * amount, or an LNURL or a Lightning address whose smallest and largest amount are the same, as on the phone. An + * amount the wearer typed is never fixed, and neither is a Spark address payment. + */ + internal val isAmountFixed: Boolean = false, ) { val totalSats: ULong get() = amountSats + feeSats } diff --git a/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt b/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt new file mode 100644 index 0000000000..1f24a57271 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt @@ -0,0 +1,115 @@ +package to.bitkit.wear.models + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.intOrNull +import to.bitkit.wear.utils.AppError + +/** + * The phone's QuickPay settings: payments of up to [amountUsd] US dollars skip the confirmation, up to + * [amountUsd] times [dailyMultiplier] dollars a day. + */ +data class QuickPayLimits( + val isEnabled: Boolean, + val amountUsd: Int, + val dailyMultiplier: Int, +) { + val thresholdCents: Long get() = amountUsd * CENTS_PER_USD + val dailyCapCents: Long get() = thresholdCents * dailyMultiplier + + companion object { + private const val CENTS_PER_USD = 100L + + /** The largest values the phone's QuickPay sliders offer; a backup with more is not the phone's. */ + const val MAX_AMOUNT_USD = 50 + const val MAX_DAILY_MULTIPLIER = 50 + } +} + +/** + * What the watch adopts from the phone's settings backup. A display value is null when the backup does not hold a + * readable one, and the watch then keeps its own. [quickPay] is null when its values cannot all be read, which turns + * QuickPay off on the watch. + */ +data class PhoneSettings( + val primaryDisplay: PrimaryDisplay?, + val displayUnit: BitcoinDisplayUnit?, + val selectedCurrency: String?, + val quickPay: QuickPayLimits?, +) + +sealed class PhoneSettingsError(message: String, cause: Throwable? = null) : AppError(message, cause) { + /** The backup is not the JSON envelope the phone writes. */ + class Unreadable(cause: Throwable? = null) : PhoneSettingsError("The settings backup cannot be read", cause) + + /** The backup was written in a layout newer than this app knows. */ + class NewerSchema(version: Int) : PhoneSettingsError("The settings backup has version '$version'") +} + +/** + * Reads the phone's `BackupCategory.SETTINGS` envelope (`SettingsBackupV1`: `version`, `createdAt`, `settings`), as + * bitkit-android and bitkit-ios write it. Only the keys the watch adopts are read; every other key is ignored. + */ +object PhoneSettingsParser { + /** The newest envelope version this reader knows. */ + const val SCHEMA_VERSION = 1 + + /** A settings envelope is a few kilobytes; anything larger than this is not one. */ + const val MAX_BYTES = 256 * 1024 + + private val json = Json { isLenient = true } + + /** Fails with a [PhoneSettingsError]. */ + fun parse(bytes: ByteArray): PhoneSettings { + if (bytes.size > MAX_BYTES) throw PhoneSettingsError.Unreadable() + val root = runCatching { json.parseToJsonElement(bytes.decodeToString()) as JsonObject } + .getOrElse { throw PhoneSettingsError.Unreadable(it) } + val version = when (val element = root["version"]) { + null -> SCHEMA_VERSION + else -> (element as? JsonPrimitive)?.intOrNull ?: throw PhoneSettingsError.Unreadable() + } + if (version > SCHEMA_VERSION) throw PhoneSettingsError.NewerSchema(version) + if (version < 1) throw PhoneSettingsError.Unreadable() + val settings = root["settings"] as? JsonObject ?: throw PhoneSettingsError.Unreadable() + return PhoneSettings( + primaryDisplay = settings["primaryDisplay"].enumOrNull(), + displayUnit = settings["displayUnit"].enumOrNull(), + selectedCurrency = settings["selectedCurrency"].stringOrNull()?.takeIf { CURRENCY_CODE.matches(it) }, + quickPay = quickPay(settings), + ) + } + + private fun quickPay(settings: JsonObject): QuickPayLimits? { + val isEnabled = (settings["isQuickPayEnabled"] as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull + val amountUsd = settings["quickPayAmount"].intOrNull() + val multiplier = settings["quickPayDailyLimitMultiplier"].intOrNull() + if (isEnabled == null || amountUsd == null || multiplier == null) return null + if (amountUsd !in 1..QuickPayLimits.MAX_AMOUNT_USD) return null + if (multiplier !in 1..QuickPayLimits.MAX_DAILY_MULTIPLIER) return null + return QuickPayLimits(isEnabled, amountUsd, multiplier) + } + + private fun JsonElement?.intOrNull(): Int? = (this as? JsonPrimitive)?.takeIf { !it.isString }?.intOrNull + + private fun JsonElement?.stringOrNull(): String? = (this as? JsonPrimitive)?.takeIf { it.isString }?.content + + /** + * An enum as kotlinx writes it, a string, or as Swift's `Codable` does, an object with the case as its one key. + * Names match without their case and underscores, as in the phone's reader. + */ + private inline fun > JsonElement?.enumOrNull(): T? { + val name = when (this) { + is JsonPrimitive -> stringOrNull() + is JsonObject -> keys.singleOrNull() + else -> null + } ?: return null + return enumValues().firstOrNull { it.name.normalized() == name.normalized() } + } + + private fun String.normalized() = filter { it != '_' }.lowercase() + + private val CURRENCY_CODE = Regex("^[A-Z]{3}$") +} 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 61392554ae..adde658df7 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -12,10 +12,12 @@ import breez_sdk_spark.SendPaymentMethod import com.synonym.bitkitcore.LightningInvoice import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.Scanner +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope @@ -50,6 +52,7 @@ import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.utils.Logger import java.net.URI import java.util.UUID +import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.seconds @@ -67,6 +70,7 @@ class PaymentsRepo @Inject constructor( private val selfSendGuard: SelfSendGuard, private val ownInvoiceStore: OwnInvoiceStore, private val uncertainSendStore: UncertainSendStore, + private val quickPayRepo: QuickPayRepo, ) { companion object { private const val TAG = "PaymentsRepo" @@ -138,12 +142,49 @@ class PaymentsRepo @Inject constructor( /** Emits whenever Spark reports a payment or a sync, so the activity list reads [recentPayments] again. */ val paymentChanges: Flow get() = sparkService.events.map { } + /** What [skipConfirmation] counted against the QuickPay limit, by [PreparedSend.transferKey], until [send] ends. */ + private val quickPayReservations = ConcurrentHashMap() + /** - * Whether a send goes out without the hold to pay (QuickPay). Always false until the watch has QuickPay settings - * (PR 3), which check [prepared] against the wearer's limit here and nowhere else. + * Whether [prepared] goes out without the hold to pay (QuickPay), by the phone's rules. This is the one place + * that decides it. It does only when all of these hold: + * - the wallet is ready; + * - [prepared] came from [prepare], so the self-send guard and every check before the hold passed; + * - its request fixes the amount, as a BOLT11 invoice with an amount, also inside a `bitcoin:` URI, or an LNURL + * or a Lightning address that takes one amount only; an amount the wearer typed is always reviewed, and so is + * a Spark address; + * - [QuickPayRepo.reserve] takes the payment's amount, without its fee, under the phone's QuickPay settings; + * - [canSend] still says yes after all of that, which is where the caller answers for the wearer being there: + * see `SendViewModel`. + * + * A yes counts the payment against today's QuickPay limit, so ask once per send and only when about to [send], + * which takes it out again when nothing was paid. A no counts nothing, and neither does a caller that is + * cancelled before it hears the yes. Anything that cannot be told answers no, and the wearer holds to pay. */ - @Suppress("FunctionOnlyReturningConstant", "UNUSED_PARAMETER") - fun skipConfirmation(prepared: PreparedSend): Boolean = false + suspend fun skipConfirmation(prepared: PreparedSend, canSend: () -> Boolean): Boolean = try { + withContext(ioDispatcher) { + if (!isReady() || sparkService.isWiping) return@withContext false + if (!prepared.isAmountFixed) return@withContext false + quickPayRepo.awaitRate() + // A caller that goes away meanwhile does not stop this halfway, with a count that nothing takes out. + withContext(NonCancellable) { + val reservation = quickPayRepo.reserve(prepared.amountSats) ?: return@withContext false + // The wallet may have locked, paused or been wiped, or the wearer left, while the limit was read. + if (!isReady() || sparkService.isWiping || !canSend()) { + quickPayRepo.release(reservation) + return@withContext false + } + quickPayReservations[prepared.transferKey] = reservation + true + } + } + } catch (e: CancellationException) { + // The caller went away and never hears the yes, so it sends nothing. + withContext(NonCancellable) { + quickPayReservations.remove(prepared.transferKey)?.let { quickPayRepo.release(it) } + } + throw e + } /** * Creates an amountless BOLT11 invoice paid into the Spark balance, valid for [INVOICE_EXPIRY_SECS], and @@ -272,7 +313,14 @@ class PaymentsRepo @Inject constructor( when (request) { is SendRequest.Invoice -> { ensureAmount(amount, 1uL, MAX_SATS) - prepare(request.bolt11, amount, isAmountInRequest = request.amountSats != null, request.payee) + val isAmountInRequest = request.amountSats != null + prepare( + paymentRequest = request.bolt11, + amountSats = amount, + isAmountInRequest = isAmountInRequest, + payee = request.payee, + isAmountFixed = isAmountInRequest, + ) } is SendRequest.Lnurl -> { ensureAmount(amount, request.minSats, request.maxSats) @@ -282,6 +330,7 @@ class PaymentsRepo @Inject constructor( isAmountInRequest = true, payee = request.payee, exactMsats = amount * MSATS_PER_SAT, + isAmountFixed = request.data.minSendable == request.data.maxSendable, ) } is SendRequest.SparkAddress -> { @@ -325,6 +374,7 @@ class PaymentsRepo @Inject constructor( payee: String?, exactMsats: ULong? = null, sparkPayee: String? = null, + isAmountFixed: Boolean = false, ): PreparedSend { ensureNotOwn(paymentRequest) val response = runSuspendCatching { @@ -355,6 +405,7 @@ class PaymentsRepo @Inject constructor( expiresAtSecs = invoice?.expiresAt, sparkPayee = sparkPayee.takeIf { invoice == null }, transferKey = UUID.randomUUID().toString(), + isAmountFixed = isAmountFixed, ) } @@ -397,6 +448,9 @@ class PaymentsRepo @Inject constructor( * address encodes, until its outcome is known, and a retry goes out under the same key. Every send is noted there * before it goes out, so a refusal that follows an attempt of unknown outcome, also one the app was closed * during, is never read as nothing sent. + * + * 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]. */ suspend fun send(prepared: PreparedSend): Result = sendScope.async { runSuspendCatching { @@ -422,6 +476,14 @@ class PaymentsRepo @Inject constructor( } }.onFailure { Logger.error("Failed to send a payment", it, context = TAG) + }.also { result -> + // As on the phone, a QuickPay payment that did not go out or failed is not counted. One whose outcome + // is unknown may have been paid, so it stays counted, and so does one that failed in a way not foreseen. + val reservation = quickPayReservations.remove(prepared.transferKey) + val error = result.exceptionOrNull() + if (reservation != null && error is SendError && error !is SendError.Unknown) { + quickPayRepo.release(reservation) + } } }.await() diff --git a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt new file mode 100644 index 0000000000..419668aca6 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -0,0 +1,128 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.QuickPaySpendStore +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BTC_SCALE +import to.bitkit.wear.models.FxRate +import to.bitkit.wear.models.QuickPayLimits +import to.bitkit.wear.models.SATS_IN_BTC +import to.bitkit.wear.models.USD +import to.bitkit.wear.models.fiatValue +import to.bitkit.wear.utils.Logger +import java.math.BigDecimal +import java.math.RoundingMode +import java.time.Instant +import java.time.ZoneId +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.seconds + +/** + * Decides whether a payment goes out under the phone's QuickPay settings, which the watch imports and never sets, by + * the rules of the phone's own `QuickPayRepo`: the same amount, rate, rounding and daily count. It reads the settings + * as last imported, however long ago. Everything that is missing or unreadable answers no. + */ +@Singleton +class QuickPayRepo internal constructor( + private val ioDispatcher: CoroutineDispatcher, + private val settingsStore: SettingsStore, + private val currencyRepo: CurrencyRepo, + private val spendStore: QuickPaySpendStore, + private val nowMs: () -> Long, + private val zone: () -> ZoneId, +) { + companion object { + private const val TAG = "QuickPayRepo" + private const val CENTS_SCALE = 2 + + /** How long [awaitRate] holds a payment back for the dollar rate before it goes on without. */ + val RATE_TIMEOUT = 5.seconds + } + + @Inject + constructor( + @IoDispatcher ioDispatcher: CoroutineDispatcher, + settingsStore: SettingsStore, + currencyRepo: CurrencyRepo, + spendStore: QuickPaySpendStore, + ) : this( + ioDispatcher, + settingsStore, + currencyRepo, + spendStore, + System::currentTimeMillis, + ZoneId::systemDefault, + ) + + private val mutex = Mutex() + + /** + * Fetches the rates when QuickPay is on and no dollar rate is in yet, as for a payment whose link started the + * app: the watch keeps no rates across restarts, where the phone has its cached ones. It waits at most + * [RATE_TIMEOUT] and decides nothing: without a rate [reserve] answers no. + */ + suspend fun awaitRate(): Unit = withContext(ioDispatcher) { + runSuspendCatching { + if (settingsStore.data.first().quickPay?.isEnabled != true) return@runSuspendCatching + if (currencyRepo.rates.value.rateFor(USD) != null) return@runSuspendCatching + withTimeoutOrNull(RATE_TIMEOUT) { currencyRepo.refresh() } + }.onFailure { Logger.warn("Failed to fetch the rate QuickPay reads", it, context = TAG) } + } + + /** + * Whether a payment of [amountSats], its fee not counted, may skip the hold to pay; if so it is counted against + * today's limit and returned as what [release] takes back. It may when QuickPay is on in the last import, the + * amount is no more than the phone's QuickPay amount, in sats and in unrounded dollars at the dollar rate (the + * phone checks the one when it offers QuickPay and the other when it pays), and today's QuickPay payments + * from this watch stay within the phone's daily limit with it. Any failure to read or count answers null. + */ + suspend fun reserve(amountSats: ULong): QuickPayReservation? = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { reserveLocked(amountSats) } } + .onFailure { Logger.warn("Failed to check QuickPay", it, context = TAG) } + .getOrNull() + } + + /** + * Takes [reservation] out of its day's count again, for a payment that did not go out or that failed, as the + * phone does. A count that cannot be written stays, which only makes the day's limit tighter. + */ + suspend fun release(reservation: QuickPayReservation): Unit = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { spendStore.release(reservation.dayKey, reservation.cents) } } + .onFailure { Logger.warn("Failed to release a QuickPay payment", it, context = TAG) } + } + + private suspend fun reserveLocked(amountSats: ULong): QuickPayReservation? { + val quickPay = settingsStore.data.first().quickPay?.takeIf { it.isEnabled } ?: return null + if (amountSats == 0uL || amountSats > Long.MAX_VALUE.toULong()) return null + val rate = currencyRepo.rates.value.rateFor(USD) ?: return null + val thresholdSats = thresholdSats(quickPay, rate) ?: return null + if (thresholdSats == 0uL || amountSats > thresholdSats) return null + val fiatCents = fiatValue(amountSats.toLong(), rate)?.movePointRight(CENTS_SCALE) ?: return null + // The threshold in sats may have rounded up, so its last sat can be worth a fraction of a cent too much. + if (fiatCents > BigDecimal.valueOf(quickPay.thresholdCents)) return null + val cents = fiatCents.setScale(0, RoundingMode.HALF_UP).toLong().coerceAtLeast(1L) + val today = Instant.ofEpochMilli(nowMs()).atZone(zone()).toLocalDate().toString() + val dayKey = spendStore.reserve(today, cents, quickPay.dailyCapCents) ?: return null + return QuickPayReservation(dayKey, cents) + } + + private fun thresholdSats(quickPay: QuickPayLimits, rate: FxRate): ULong? { + if (rate.rate <= 0.0) return null + val sats = BigDecimal.valueOf(quickPay.amountUsd.toDouble()) + .divide(BigDecimal.valueOf(rate.rate), BTC_SCALE, RoundingMode.HALF_UP) + .multiply(BigDecimal(SATS_IN_BTC)) + .setScale(0, RoundingMode.HALF_UP) + return runCatching { sats.longValueExact().toULong() }.getOrNull() + } +} + +/** A payment counted against the QuickPay limit of [dayKey], an ISO date, as [cents] US cents. */ +data class QuickPayReservation(val dayKey: String, val cents: Long) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt new file mode 100644 index 0000000000..2b1f506528 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt @@ -0,0 +1,181 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.ElapsedClock +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.di.IoDispatcher +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.PhoneSettingsParser +import to.bitkit.wear.security.SeedStore +import to.bitkit.wear.security.WalletSeed +import to.bitkit.wear.services.PhoneBackupReader +import to.bitkit.wear.services.PhoneBackupUnreadable +import to.bitkit.wear.services.SparkError +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.utils.AppError +import to.bitkit.wear.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * Imports the phone's settings from its backup on VSS, which the watch can read because it holds the same seed. It + * only reads: see [PhoneBackupReader]. The watch adopts the units, the currency and QuickPay, and sets none of them + * itself. + */ +@Singleton +class SettingsSyncRepo internal constructor( + private val ioDispatcher: CoroutineDispatcher, + private val seedStore: SeedStore, + private val backupReader: PhoneBackupReader, + private val settingsStore: SettingsStore, + private val sparkService: WatchSparkService, + private val walletRepo: WalletRepo, + private val clock: ElapsedClock, + private val nowMs: () -> Long, +) { + companion object { + private const val TAG = "SettingsSyncRepo" + + /** The key of the phone's settings backup, the name of its `BackupCategory.SETTINGS`. */ + const val SETTINGS_KEY = "SETTINGS" + + /** How long an import waits for signing in to VSS and reading the backup. */ + val READ_TIMEOUT = 30.seconds + + /** + * How soon after a read of the backup the next one is skipped, unless the wearer asked for it. Each read + * signs in to VSS anew, so a wallet that keeps losing and finding its network must not start one each time. + */ + val MIN_READ_GAP = 1.minutes + } + + @Inject + constructor( + @IoDispatcher ioDispatcher: CoroutineDispatcher, + seedStore: SeedStore, + backupReader: PhoneBackupReader, + settingsStore: SettingsStore, + sparkService: WatchSparkService, + walletRepo: WalletRepo, + clock: ElapsedClock, + ) : this( + ioDispatcher, + seedStore, + backupReader, + settingsStore, + sparkService, + walletRepo, + clock, + System::currentTimeMillis, + ) + + /** + * Where imports and their reads run. Nothing cancels it, so an import lands whoever stopped waiting for it, and + * a read that was given up ends by itself. + */ + private val scope = CoroutineScope(SupervisorJob() + ioDispatcher) + + private val mutex = Mutex() + + /** The wipe token and the [clock] time of the last read that reached the backup. Guarded by [mutex]. */ + private var lastRead: Pair? = null + + /** + * Reads the phone's settings backup and adopts it, for a wallet that is ready. A backup that is missing, cannot + * be decrypted or read, or has a newer layout keeps the watch's display values and turns QuickPay off. A read + * that fails, as without a network, changes nothing: QuickPay goes on with the settings last imported. An import + * that a wallet wipe overtook is taken out again, so nothing of a removed wallet's settings stays. + * + * The import runs in the repo's own scope and the caller only waits for it: a caller that is cancelled or + * timed out returns at once, and the import goes on and lands for the next one to find. The import itself stops + * waiting for its read after [READ_TIMEOUT], or as soon as the wallet stops being ready, as on a lock or a + * pause, and then writes nothing. The VSS library blocks its thread for each of its HTTP calls, so a read that + * was given up is not over at once: it ends with the call it is in, and only then is its client, with the keys + * derived from the seed, shut down. + * + * A call that waited for another import joins it: within [MIN_READ_GAP] of a read of this wallet's backup + * nothing is read again and the call succeeds, unless [isForced], as for the wearer's own tap. + */ + suspend fun sync(isForced: Boolean = false): Result = runSuspendCatching { + val import = scope.async { + runSuspendCatching { mutex.withLock { syncLocked(isForced) } } + .onFailure { Logger.warn("Failed to import the phone's settings", it, context = TAG) } + } + import.await().getOrThrow() + } + + private suspend fun syncLocked(isForced: Boolean) { + val wipeToken = sparkService.wipeToken() ?: throw SparkError.WipeInProgress() + if (walletRepo.walletState.value.status != WalletStatus.Ready) throw SettingsSyncError.NotReady() + if (!isForced && isReadRecently(wipeToken)) return + val seed = seedStore.load().getOrThrow() + val backup = withTimeoutOrNull(READ_TIMEOUT) { readWhileReady(seed) } ?: throw SettingsSyncError.Timeout() + val parsed = backup.fold( + onSuccess = { bytes -> runSuspendCatching { bytes?.let { PhoneSettingsParser.parse(it) } } }, + onFailure = { if (it is PhoneBackupUnreadable) Result.failure(it) else throw it }, + ) + val settings = parsed.getOrNull() + when { + parsed.isFailure -> { + Logger.warn("Failed to read the phone's settings backup", parsed.exceptionOrNull(), context = TAG) + settingsStore.clearQuickPay() + } + settings == null -> { + Logger.info("Found no settings backup of the phone", context = TAG) + settingsStore.clearQuickPay() + } + else -> { + settingsStore.applyPhoneSettings(settings, nowMs()) + Logger.info("Imported the phone's settings", context = TAG) + } + } + lastRead = wipeToken to clock.nowMs() + if (!sparkService.isCurrent(wipeToken)) { + settingsStore.clearPhoneSettings() + throw SparkError.WipeInProgress() + } + } + + private fun isReadRecently(wipeToken: Int): Boolean { + val (token, readAtMs) = lastRead ?: return false + return token == wipeToken && clock.nowMs() - readAtMs in 0 until MIN_READ_GAP.inWholeMilliseconds + } + + /** + * Reads the settings backup, or fails with [SettingsSyncError.NotReady] the moment the wallet is not ready any + * more. The read runs apart in [scope], since it blocks its thread and cannot be interrupted: this returns as + * soon as either side answers or the caller's time is up, and a read that lost is cancelled, which it follows + * at the end of its HTTP call, shutting its client down. + */ + private suspend fun readWhileReady(seed: WalletSeed): Result { + val read = scope.async { runSuspendCatching { backupReader.read(seed, SETTINGS_KEY) } } + try { + return channelFlow { + launch { send(read.await()) } + launch { + walletRepo.walletState.first { it.status != WalletStatus.Ready } + send(Result.failure(SettingsSyncError.NotReady())) + } + }.first() + } finally { + read.cancel() + } + } +} + +sealed class SettingsSyncError(message: String) : AppError(message) { + class NotReady : SettingsSyncError("The wallet is not ready") + + class Timeout : SettingsSyncError("Timed out reading the phone's settings") +} diff --git a/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt new file mode 100644 index 0000000000..6f68ef81ec --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt @@ -0,0 +1,69 @@ +package to.bitkit.wear.services + +import com.synonym.vssclient.VssException +import com.synonym.vssclient.vssDeriveStoreId +import com.synonym.vssclient.vssGet +import com.synonym.vssclient.vssNewClientWithLnurlAuth +import com.synonym.vssclient.vssShutdownClient +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import to.bitkit.wear.env.Env +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.security.WalletSeed +import to.bitkit.wear.utils.AppError +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The watch's only way to the phone's backups on VSS, and it can only read: there is no call here that stores, + * replaces or deletes anything, so the watch can never clobber what the phone backed up. + */ +fun interface PhoneBackupReader { + /** + * The backup object stored under [key] for the wallet of [seed], or null when the phone stored none. Fails with + * [PhoneBackupUnreadable] when an object is stored that this wallet's keys cannot open. + */ + suspend fun read(seed: WalletSeed, key: String): ByteArray? +} + +/** The phone's backup object is stored, but it cannot be decoded or decrypted with the wallet's keys. */ +class PhoneBackupUnreadable : AppError("The phone's backup cannot be decrypted") + +/** + * [PhoneBackupReader] over vss-client, set up as the phone's `VssBackupClient` is: the same server, store id and + * LNURL-auth sign-in, all derived from the seed. This file is the only one that may name the VSS library, and of it + * only the four calls and the error type imported above; `PhoneBackupReaderTest` checks both. The library reports + * an object it fetched and cannot decode or decrypt as a get error, and every failure to reach the server or to + * sign in as another type, so a get error is an unreadable backup. The library keeps one client for the + * process, holding keys derived from the seed, so each read builds it and shuts it down again: nothing of a wallet + * stays behind for a lock, a pause or a wipe to clean up. + * + * The library runs each call to its end on the calling thread, so a read cannot be interrupted: one that is + * cancelled goes on until its HTTP call returns and only then shuts the client down. A caller that must not wait + * that long runs the read apart and stops waiting for it, as `SettingsSyncRepo` does. + */ +@Singleton +class VssPhoneBackupReader @Inject constructor() : PhoneBackupReader { + private val mutex = Mutex() + + override suspend fun read(seed: WalletSeed, key: String): ByteArray? = mutex.withLock { + try { + vssNewClientWithLnurlAuth( + baseUrl = Env.vssServerUrl(), + storeId = vssDeriveStoreId(Env.vssStoreIdPrefix(), seed.mnemonic, seed.passphrase), + mnemonic = seed.mnemonic, + passphrase = seed.passphrase, + lnurlAuthServerUrl = Env.lnurlAuthServerUrl(), + ) + try { + vssGet(key)?.value + } catch (_: VssException.GetException) { + throw PhoneBackupUnreadable() + } + } finally { + withContext(NonCancellable) { runSuspendCatching { vssShutdownClient() } } + } + } +} diff --git a/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt index 567d586a6f..64d06d07f5 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/BalanceTileService.kt @@ -28,7 +28,11 @@ import androidx.wear.tiles.TileBuilders import androidx.wear.tiles.TileService import com.google.common.util.concurrent.ListenableFuture import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.flow.first import to.bitkit.wear.R +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.ui.LaunchRequest import to.bitkit.wear.ui.MainActivity @@ -68,9 +72,14 @@ class BalanceTileService : TileService() { @Inject lateinit var walletRepo: WalletRepo + @Inject + lateinit var settingsStore: SettingsStore + override fun onTileRequest(requestParams: RequestBuilders.TileRequest): ListenableFuture = SuspendToFutureAdapter.launchFuture { - val state = tileState(walletRepo.hasWallet(), walletRepo.walletState.value) + val unit = runSuspendCatching { settingsStore.data.first().displayUnit } + .getOrDefault(BitcoinDisplayUnit.MODERN) + val state = tileState(walletRepo.hasWallet(), walletRepo.walletState.value, unit) TileBuilders.Tile.Builder() .setResourcesVersion(RESOURCES_VERSION) .setFreshnessIntervalMillis(FRESHNESS.inWholeMilliseconds) diff --git a/wear/src/main/java/to/bitkit/wear/tile/TileState.kt b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt index 245cbf1d2c..cbcb2c3ac2 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/TileState.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt @@ -1,5 +1,6 @@ package to.bitkit.wear.tile +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus import to.bitkit.wear.ui.screens.home.DisplayAmount @@ -16,14 +17,19 @@ sealed interface TileState { } /** - * The tile's state for a watch that [hasWallet] in [wallet]'s state. The balance shows only once a sync of this - * process confirmed it, as on the Balance page, and never while the watch is locked; the tile never starts the wallet - * to learn it. + * The tile's state for a watch that [hasWallet] in [wallet]'s state, with the balance in bitcoin written in [unit]. + * The balance shows only once a sync of this process confirmed it, as on the Balance page, and never while the watch + * is locked; the tile never starts the wallet to learn it. */ -fun tileState(hasWallet: Boolean, wallet: WalletState, locale: Locale = Locale.getDefault()): TileState { +fun tileState( + hasWallet: Boolean, + wallet: WalletState, + unit: BitcoinDisplayUnit, + locale: Locale = Locale.getDefault(), +): TileState { if (!hasWallet || wallet.status in walletGoneStatuses) return TileState.SignedOut val sats = wallet.balanceSats?.takeIf { wallet.hasSynced && wallet.status != WalletStatus.Locked }?.toLong() - return TileState.Wallet(sats?.let { bitcoinAmount(it, locale) }) + return TileState.Wallet(sats?.let { bitcoinAmount(it, unit, locale) }) } private val walletGoneStatuses = setOf(WalletStatus.Removed, WalletStatus.Missing) diff --git a/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt index b2e4821edd..74bee90795 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/TileUpdates.kt @@ -6,32 +6,36 @@ import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch +import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.repositories.WalletRepo import javax.inject.Inject import javax.inject.Singleton /** - * Asks the system to draw the tile again whenever what it shows may change: the balance, or the wallet's status, which - * also changes when a wallet is restored or removed. The first state of a process counts too, so a tile drawn by an - * earlier process drops the balance this one has not loaded. + * Asks the system to draw the tile again whenever what it shows may change: the balance, the bitcoin unit imported + * from the phone, or the wallet's status, which also changes when a wallet is restored or removed. The first state of + * a process counts too, so a tile drawn by an earlier process drops the balance this one has not loaded. */ @Singleton class TileUpdates @Inject constructor( @ApplicationContext private val context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher, private val walletRepo: WalletRepo, + private val settingsStore: SettingsStore, ) { private val scope = CoroutineScope(ioDispatcher + SupervisorJob()) /** Follows the wallet for the life of the process. */ fun start() { scope.launch { + val units = settingsStore.data.map { it.displayUnit }.distinctUntilChanged() walletRepo.walletState - .map { tileState(hasWallet = true, wallet = it) to it.status } + .combine(units) { wallet, unit -> tileState(hasWallet = true, wallet, unit) to wallet.status } .distinctUntilChanged() .collect { TileService.getUpdater(context).requestUpdate(BalanceTileService::class.java) } } 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 484495c8fb..2f8ea0425a 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -30,3 +30,9 @@ sealed interface LaunchRequest { intent?.let { from(it.action, it.dataString, it.getStringExtra(EXTRA_OPEN)) } } } + +/** + * Whether an intent with [flags] is one Android replays from Recents: the link or the tile's request that once + * opened the app, sent again long after the wearer saw it. Such an intent is a plain launch, whatever it asks for. + */ +fun isReplayedLaunch(flags: Int): Boolean = flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 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 8ab754f533..0d4811e771 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt @@ -6,6 +6,7 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue @@ -18,9 +19,12 @@ import androidx.wear.compose.foundation.LocalAmbientModeManager 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.ui.components.BezelLoading +import to.bitkit.wear.ui.components.isAmbient import to.bitkit.wear.ui.screens.start.StartErrorScreen import to.bitkit.wear.ui.theme.BitkitWearTheme +import javax.inject.Inject import kotlin.time.Duration.Companion.seconds import kotlin.time.TimeSource @@ -31,6 +35,9 @@ class MainActivity : ComponentActivity() { private val SPLASH_LIMIT = 1.seconds } + @Inject + lateinit var ambientMonitor: AmbientMonitor + private val startViewModel: StartViewModel by viewModels() /** What the intent that opened the app asks for, until the navigation shows it. */ @@ -39,8 +46,8 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) - // A recreated activity has shown its intent's request already. - if (savedInstanceState == null) launchRequest = LaunchRequest.from(intent) + // 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) val splashStart = TimeSource.Monotonic.markNow() splashScreen.setKeepOnScreenCondition { startViewModel.uiState.value.isStarting && splashStart.elapsedNow() < SPLASH_LIMIT @@ -48,6 +55,8 @@ class MainActivity : ComponentActivity() { setContent { BitkitWearTheme { CompositionLocalProvider(LocalAmbientModeManager provides rememberAmbientModeManager()) { + val isAmbient = isAmbient() + SideEffect { ambientMonitor.set(isAmbient) } AppScaffold( modifier = Modifier.semantics { testTagsAsResourceId = true // see https://github.com/appium/appium/issues/15138 diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt index a4eb0654d1..366b3e8d12 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityDetailScreen.kt @@ -19,6 +19,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.Text import to.bitkit.wear.R +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.WatchPayment import to.bitkit.wear.ui.components.BezelLoading @@ -49,7 +50,7 @@ fun ActivityDetailScreen( Missing(isLoading = !uiState.isLoaded, modifier = modifier) return } - Content(payment = payment, isAmbient = isAmbient(), modifier = modifier) + Content(payment = payment, unit = uiState.unit, isAmbient = isAmbient(), modifier = modifier) } /** Stands in for a payment the list does not hold: while the list loads, or after newer payments pushed it out. */ @@ -69,6 +70,7 @@ private fun Missing( @Composable private fun Content( payment: WatchPayment, + unit: BitcoinDisplayUnit, isAmbient: Boolean, modifier: Modifier = Modifier, ) { @@ -76,7 +78,7 @@ private fun Content( if (!isAmbient) { BoxWithConstraints(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) { LargeAmountRow( - amount = bitcoinAmount(payment.amountSats.toLong()), + amount = bitcoinAmount(payment.amountSats.toLong(), unit), maxWidth = maxWidth, amountTag = "WatchActivityDetailAmount", symbolTag = "WatchActivityDetailSymbol", @@ -84,7 +86,7 @@ private fun Content( } } if (payment.isSent && payment.feeSats > 0uL && !isAmbient) { - val fee = bitcoinAmount(payment.feeSats.toLong()) + val fee = bitcoinAmount(payment.feeSats.toLong(), unit) Line( text = stringResource(R.string.send__fee, "${fee.symbol} ${fee.text}"), modifier = Modifier.testTag("WatchActivityDetailFee") @@ -138,6 +140,6 @@ private fun Line( @Composable private fun Preview() { WearPreview { - Content(payment = PreviewPayment, isAmbient = false) + Content(payment = PreviewPayment, unit = BitcoinDisplayUnit.MODERN, isAmbient = false) } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt index fe5ff61586..7c6a2b5ec1 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt @@ -26,9 +26,10 @@ import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.delay import to.bitkit.wear.R import to.bitkit.wear.models.BITCOIN_SYMBOL +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.WatchPayment -import to.bitkit.wear.models.formatToModernDisplay +import to.bitkit.wear.models.formatMoney import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.CenteredScreen import to.bitkit.wear.ui.components.ListScreen @@ -130,7 +131,7 @@ private fun List( FilledTonalButton( onClick = { onPaymentClick(payment.id) }, icon = { DirectionIcon(payment = payment) }, - label = { Text(text = payment.amountText(), maxLines = 1) }, + label = { Text(text = payment.amountText(uiState.unit), maxLines = 2) }, secondaryLabel = { Text(text = relativeTime(payment.timestampSecs.toLong(), uiState.nowSecs), maxLines = 1) }, @@ -167,9 +168,9 @@ internal fun DirectionIcon( } /** The payment's amount in bitcoin, with the phone's sign for its direction. */ -internal fun WatchPayment.amountText(): String { +internal fun WatchPayment.amountText(unit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN): String { val sign = if (isSent) "-" else "+" - return "$sign $BITCOIN_SYMBOL ${amountSats.toLong().formatToModernDisplay()}" + return "$sign $BITCOIN_SYMBOL ${amountSats.toLong().formatMoney(unit)}" } /** How long ago [timestampSecs] was; a time ahead of the watch's clock, set by Spark's servers, counts as now. */ diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt index c0ef8afca9..153dc1c507 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityViewModel.kt @@ -17,6 +17,8 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.WatchPayment import to.bitkit.wear.repositories.PaymentsRepo import to.bitkit.wear.repositories.WalletRepo @@ -32,18 +34,25 @@ import javax.inject.Inject class ActivityViewModel internal constructor( private val paymentsRepo: PaymentsRepo, private val walletRepo: WalletRepo, + private val settingsStore: SettingsStore, private val nowSecs: () -> Long, ) : ViewModel() { @Inject constructor( paymentsRepo: PaymentsRepo, walletRepo: WalletRepo, - ) : this(paymentsRepo, walletRepo, { Instant.now().epochSecond }) + settingsStore: SettingsStore, + ) : this(paymentsRepo, walletRepo, settingsStore, { Instant.now().epochSecond }) private val _uiState = MutableStateFlow(ActivityUiState()) val uiState: StateFlow = _uiState.asStateFlow() init { + viewModelScope.launch { + settingsStore.data.map { it.displayUnit }.distinctUntilChanged().collect { unit -> + _uiState.update { it.copy(unit = unit) } + } + } viewModelScope.launch { val connected = walletRepo.walletState .map { it.status in connectedStatuses } @@ -73,6 +82,8 @@ data class ActivityUiState( val isLoaded: Boolean = false, /** When the list was read, in epoch seconds, which the relative times count from. */ val nowSecs: Long = 0, + /** How bitcoin amounts are written, as on the phone. */ + val unit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN, ) { fun payment(id: String): WatchPayment? = payments.firstOrNull { it.id == id } } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt index f50b0d6f35..718438ce48 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeViewModel.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import to.bitkit.wear.data.AmbientMonitor import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.NetworkMonitor import to.bitkit.wear.data.NfcMonitor @@ -22,13 +23,15 @@ import to.bitkit.wear.data.NfcState import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings import to.bitkit.wear.models.BITCOIN_SYMBOL +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.FxRate import to.bitkit.wear.models.PrimaryDisplay import to.bitkit.wear.models.fiatValue import to.bitkit.wear.models.formatCurrency -import to.bitkit.wear.models.formatToModernDisplay +import to.bitkit.wear.models.formatMoney import to.bitkit.wear.models.isSymbolSuffix import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus @@ -42,7 +45,9 @@ import kotlin.time.Duration.Companion.seconds /** * The home screen's state, and what keeps it fresh while Home is open: it starts the wallet and fetches the exchange * rates when the app comes on screen and every [RATES_REFRESH_INTERVAL] from then, when the wallet becomes ready, - * and when the network returns while there are no rates yet. + * and when the network returns while there are no rates yet. It imports the phone's settings each time the wallet + * is ready with the app on screen and not in ambient mode, so at every start and return, and every + * [SETTINGS_SYNC_INTERVAL] from then; [SettingsSyncRepo.sync] skips an import that follows another too closely. */ @HiltViewModel class HomeViewModel @Inject constructor( @@ -52,6 +57,8 @@ class HomeViewModel @Inject constructor( nfcMonitor: NfcMonitor, networkMonitor: NetworkMonitor, foregroundMonitor: ForegroundMonitor, + private val settingsSyncRepo: SettingsSyncRepo, + ambientMonitor: AmbientMonitor, ) : ViewModel() { companion object { private const val TAG = "HomeViewModel" @@ -61,6 +68,9 @@ class HomeViewModel @Inject constructor( /** How often the exchange rates are fetched again while the app is on screen. */ val RATES_REFRESH_INTERVAL = 5.minutes + + /** How often the phone's settings are imported again while the wallet is ready and the app in use. */ + val SETTINGS_SYNC_INTERVAL = 5.minutes } val uiState: StateFlow = combine( @@ -90,6 +100,20 @@ class HomeViewModel @Inject constructor( .drop(1) .collect { isReady -> if (isReady) fetchRates() } } + viewModelScope.launch { + combine( + foregroundMonitor.isForeground, + walletRepo.walletState.map { it.status == WalletStatus.Ready }, + ambientMonitor.isAmbient, + ) { isForeground, isReady, isAmbient -> isForeground && isReady && !isAmbient } + .distinctUntilChanged() + .collectLatest { canSync -> + while (canSync) { + settingsSyncRepo.sync() + delay(SETTINGS_SYNC_INTERVAL) + } + } + } viewModelScope.launch { // Only a change counts as the network returning, so the value at the start is skipped. networkMonitor.isOnline.drop(1).collect { isOnline -> @@ -133,7 +157,7 @@ internal fun homeUiState( ): HomeUiState { // A balance no sync confirmed this session, such as 0 for a wallet restored offline, is never shown. val sats = wallet.balanceSats?.takeIf { wallet.hasSynced }?.toLong() - val bitcoin = sats?.let { bitcoinAmount(it, locale) } + val bitcoin = sats?.let { bitcoinAmount(it, settings.displayUnit, locale) } val fiat = sats?.let { fiatAmount(it, rates, settings.selectedCurrency, locale) } val showsFiatFirst = settings.primaryDisplay == PrimaryDisplay.FIAT && fiat != null return HomeUiState( @@ -150,9 +174,12 @@ internal fun homeUiState( ) } -/** [sats] in bitcoin, as the balance shows it. */ -fun bitcoinAmount(sats: Long, locale: Locale = Locale.getDefault()): DisplayAmount = - DisplayAmount(BITCOIN_SYMBOL, sats.formatToModernDisplay(locale)) +/** [sats] in bitcoin, written in [unit], as the balance shows it. */ +fun bitcoinAmount( + sats: Long, + unit: BitcoinDisplayUnit = BitcoinDisplayUnit.MODERN, + locale: Locale = Locale.getDefault(), +): DisplayAmount = DisplayAmount(BITCOIN_SYMBOL, sats.formatMoney(unit, locale)) /** [sats] in [currency] at its rate in [rates], or null without that rate. */ fun fiatAmount( 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 2dd406e1b9..32e2adf60c 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 @@ -17,7 +17,10 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull +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.repositories.PaymentsRepo @@ -39,6 +42,7 @@ import kotlin.time.Duration.Companion.seconds class ReceiveViewModel internal constructor( private val paymentsRepo: PaymentsRepo, private val walletRepo: WalletRepo, + private val settingsStore: SettingsStore, private val nowSecs: () -> Long, ) : ViewModel() { companion object { @@ -61,7 +65,8 @@ class ReceiveViewModel internal constructor( constructor( paymentsRepo: PaymentsRepo, walletRepo: WalletRepo, - ) : this(paymentsRepo, walletRepo, { Instant.now().epochSecond }) + settingsStore: SettingsStore, + ) : this(paymentsRepo, walletRepo, settingsStore, { Instant.now().epochSecond }) private val _uiState = MutableStateFlow(ReceiveUiState()) val uiState: StateFlow = _uiState.asStateFlow() @@ -86,7 +91,9 @@ class ReceiveViewModel internal constructor( rotation.cancelAndJoin() coroutineContext.cancelChildren() Logger.info("Received payment '${payment.id}'", context = TAG) - _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(payment.amountSats.toLong())) } + val unit = runSuspendCatching { settingsStore.data.first().displayUnit } + .getOrDefault(BitcoinDisplayUnit.MODERN) + _uiState.update { ReceiveUiState(paidAmount = bitcoinAmount(payment.amountSats.toLong(), unit)) } } } 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 f7548ea64a..37acb772ac 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 @@ -343,6 +343,8 @@ internal fun Review( step.fee?.let { Line( text = stringResource(R.string.send__fee, "${it.symbol} ${it.text}"), + // The fee is never cut: in bitcoin with its eight decimals a long translation wraps instead. + maxLines = 2, modifier = Modifier.testTag("WatchSendFee") ) } @@ -458,13 +460,14 @@ private fun Line( text: String, modifier: Modifier = Modifier, color: Color = Colors.White64, + maxLines: Int = 1, ) { Text( text = text, style = MaterialTheme.typography.bodySmall, color = color, textAlign = TextAlign.Center, - maxLines = 1, + maxLines = maxLines, overflow = TextOverflow.Ellipsis, modifier = modifier ) 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 fdc6a2080a..9dd15129bf 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 @@ -13,12 +13,18 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.wear.R +import to.bitkit.wear.data.AmbientMonitor +import to.bitkit.wear.data.ElapsedClock +import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.PreparedSend import to.bitkit.wear.models.SendError @@ -38,9 +44,18 @@ import kotlin.time.Duration.Companion.seconds /** * The send flow for one payment input from a deeplink: it waits for the wallet, reads the input, asks for an amount * only when the input names none, prices the send and shows it for review. The send goes out only after the hold to - * pay completes, unless [PaymentsRepo.skipConfirmation] says otherwise, and the result closes the flow by itself. + * pay completes, unless [PaymentsRepo.skipConfirmation] lets it out under QuickPay, straight from pricing to sending, + * and the result closes the flow by itself. * The app pays only online: a wallet that is offline before the send starts ends the flow on [SendStep.Offline], * and the request is dropped, not kept for when the network returns. + * + * 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. */ @HiltViewModel class SendViewModel @Inject constructor( @@ -49,6 +64,9 @@ class SendViewModel @Inject constructor( private val walletRepo: WalletRepo, private val currencyRepo: CurrencyRepo, private val settingsStore: SettingsStore, + private val foregroundMonitor: ForegroundMonitor, + private val ambientMonitor: AmbientMonitor, + private val clock: ElapsedClock, ) : ViewModel() { companion object { private const val TAG = "SendViewModel" @@ -67,6 +85,15 @@ class SendViewModel @Inject constructor( /** The longest amount the wearer can type, in digits: more than every bitcoin there will be, in sats. */ const val MAX_AMOUNT_DIGITS = 16 + + /** + * How long after its link arrived a send may still go out under QuickPay: long enough for a wallet that + * connects and syncs as the link opens the app, and short enough that the wearer still looks at it. + */ + val QUICKPAY_WINDOW = 30.seconds + + /** The saved state's mark that a flow already ran for this link, so a rebuilt one never asks QuickPay. */ + const val KEY_STARTED = "send_started" } private val input: String = savedStateHandle.get(Routes.SEND_INPUT).orEmpty() @@ -79,12 +106,39 @@ class SendViewModel @Inject constructor( private var request: SendRequest? = null private var prepared: PreparedSend? = null + private var unit = BitcoinDisplayUnit.MODERN /** Reads, prices and shows the request before the send; cancelled when the wallet goes offline. */ private var flow: Job? = null + /** When the link arrived, on [clock]. */ + private val arrivedAtMs = clock.nowMs() + + /** + * Whether the wearer was away at some time since the link arrived: see [isAttended]. It never turns back, and a + * flow rebuilt for a link that already had one starts with it set, however long ago the link arrived. + */ + @Volatile + private var wasAway = savedStateHandle.get(KEY_STARTED) == true + + /** Whether the wallet was seen out of [WalletStatus.Paused], which it may be in only while the app returns. */ + private var hasLeftPause = false + init { + savedStateHandle[KEY_STARTED] = true flow = viewModelScope.launch { start() } + viewModelScope.launch { + combine( + walletRepo.walletState, + foregroundMonitor.isForeground, + ambientMonitor.isAmbient, + ) { wallet, isForeground, isAmbient -> Triple(wallet.status, isForeground, isAmbient) } + .collect { (status, isForeground, isAmbient) -> + val isPausedAgain = status == WalletStatus.Paused && hasLeftPause + if (status != WalletStatus.Paused) hasLeftPause = true + if (!isThere(status, isForeground, isAmbient) || isPausedAgain) wasAway = true + } + } viewModelScope.launch { walletRepo.walletState.collect { wallet -> _uiState.update { it.copy(isWalletReady = wallet.status == WalletStatus.Ready) } @@ -170,21 +224,50 @@ class SendViewModel @Inject constructor( } if (_uiState.value.step is SendStep.Offline) return prepared = result - if (paymentsRepo.skipConfirmation(result)) { + unit = runSuspendCatching { settingsStore.data.first().displayUnit }.getOrDefault(BitcoinDisplayUnit.MODERN) + // Asked last and only when it can apply, since a yes is counted against the day's limit. The wearer may + // have looked away while it was answered, hence the second look, which the repo takes before it says yes. + if (isQuickPayOpen() && paymentsRepo.skipConfirmation(result, ::canQuickPay)) { + Logger.info("Skipped the hold to pay under QuickPay", context = TAG) send(result) return } show(review(result, request)) } + /** Whether QuickPay may be asked for a send priced now: see the class. */ + private fun isQuickPayOpen(): Boolean = + 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. + */ + private fun canQuickPay(): Boolean = isAttended() && + walletRepo.walletState.value.status != WalletStatus.Offline && + _uiState.value.step !is SendStep.Offline + + /** + * Whether the wearer was there since the link arrived and still is: the app on screen, not in ambient mode, the + * watch never locked, and the wallet never paused after it ran. + */ + private fun isAttended(): Boolean = !wasAway && isThere( + walletRepo.walletState.value.status, + foregroundMonitor.isForeground.value, + ambientMonitor.isAmbient.value, + ) + + private fun isThere(status: WalletStatus, isForeground: Boolean, isAmbient: Boolean): Boolean = + isForeground && !isAmbient && status != WalletStatus.Locked + private suspend fun review(prepared: PreparedSend, request: SendRequest): SendStep.Review { val currency = settingsStore.data.first().selectedCurrency val amount = prepared.amountSats.toLong() val isFeeShown = prepared.feeSats > 0uL && prepared.feeSats * 100uL >= prepared.amountSats * FEE_SHOWN_PERCENT return SendStep.Review( - amount = bitcoinAmount(amount), + amount = bitcoinAmount(amount, unit), fiat = fiatAmount(amount, currencyRepo.rates.value, currency), - fee = if (isFeeShown) bitcoinAmount(prepared.feeSats.toLong()) else null, + fee = if (isFeeShown) bitcoinAmount(prepared.feeSats.toLong(), unit) else null, payee = (prepared.payee ?: request.payee)?.takeIf { it.isNotBlank() }, ) } @@ -223,7 +306,7 @@ class SendViewModel @Inject constructor( /** Shows [result] with [amountSats] and then closes the flow. */ private suspend fun finish(result: SendResult, amountSats: ULong) { - _uiState.update { it.copy(step = SendStep.Done(result, bitcoinAmount(amountSats.toLong()))) } + _uiState.update { it.copy(step = SendStep.Done(result, bitcoinAmount(amountSats.toLong(), unit))) } delay(if (result == SendResult.Sent) SENT_CLOSE_DELAY else PENDING_CLOSE_DELAY) _effects.send(SendEffect.Close) } diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt index ef73968884..ba1e9ae17e 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt @@ -1,5 +1,6 @@ package to.bitkit.wear.ui.screens.settings +import android.text.format.DateUtils import androidx.annotation.DrawableRes import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize @@ -30,6 +31,7 @@ import to.bitkit.wear.ui.components.BezelLoading import to.bitkit.wear.ui.components.ListScreen import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.components.WearPreviewDevices +import to.bitkit.wear.ui.screens.activity.rememberNowSecs @Composable fun SettingsScreen( @@ -38,9 +40,13 @@ fun SettingsScreen( viewModel: SettingsViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() + // Moves on every minute, so the import's age also grows while the page stays open. + val syncedSecs = (uiState.phoneSyncedAtMs ?: 0) / DateUtils.SECOND_IN_MILLIS Content( uiState = uiState, + nowMs = rememberNowSecs(loadedSecs = syncedSecs) * DateUtils.SECOND_IN_MILLIS, onAboutClick = onAboutClick, + onSyncClick = viewModel::onSyncClick, onRemoveClick = viewModel::onRemoveClick, onRemoveConfirm = viewModel::onRemoveConfirm, onRemoveDismiss = viewModel::onRemoveDismiss, @@ -51,7 +57,9 @@ fun SettingsScreen( @Composable private fun Content( uiState: SettingsUiState, + nowMs: Long, onAboutClick: () -> Unit, + onSyncClick: () -> Unit, onRemoveClick: () -> Unit, onRemoveConfirm: () -> Unit, onRemoveDismiss: () -> Unit, @@ -79,6 +87,42 @@ private fun Content( .testTag("WatchSettingsAbout") ) } + item { + FilledTonalButton( + onClick = onSyncClick, + enabled = !uiState.isSyncing && !uiState.isRemoving, + icon = { RowIcon(R.drawable.ic_sync) }, + label = { Text(stringResource(R.string.settings__phone_settings)) }, + secondaryLabel = uiState.phoneSyncedAtMs?.let { syncedAtMs -> + { + Text( + text = syncedAgo(syncedAtMs, nowMs), + maxLines = 1, + modifier = Modifier.testTag("WatchSettingsSyncTime") + ) + } + }, + transformation = SurfaceTransformation(spec), + modifier = Modifier + .fillMaxWidth() + .transformedHeight(this, spec) + .testTag("WatchSettingsSync") + ) + } + if (uiState.isSyncFailed) { + item { + Text( + text = stringResource(R.string.settings__phone_settings_failed), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .transformedHeight(this, spec) + .testTag("WatchSettingsSyncFailed") + ) + } + } item { FilledTonalButton( onClick = onRemoveClick, @@ -111,7 +155,7 @@ private fun Content( } } } - if (uiState.isRemoving) BezelLoading() + if (uiState.isRemoving || uiState.isSyncing) BezelLoading() } AlertDialog( visible = uiState.isRemoveDialogVisible, @@ -133,6 +177,14 @@ private fun Content( ) } +/** How long before [nowMs] the phone's settings were imported; a time ahead of it counts as now. */ +private fun syncedAgo(syncedAtMs: Long, nowMs: Long): String = DateUtils.getRelativeTimeSpanString( + syncedAtMs.coerceAtMost(nowMs), + nowMs, + DateUtils.MINUTE_IN_MILLIS, + DateUtils.FORMAT_ABBREV_RELATIVE, +).toString() + @Composable private fun RowIcon( @DrawableRes id: Int, @@ -146,8 +198,10 @@ private fun RowIcon( private fun Preview() { WearPreview { Content( - uiState = SettingsUiState(), + uiState = SettingsUiState(phoneSyncedAtMs = 0, isSyncFailed = true), + nowMs = 120_000, onAboutClick = {}, + onSyncClick = {}, onRemoveClick = {}, onRemoveConfirm = {}, onRemoveDismiss = {}, @@ -161,7 +215,9 @@ private fun PreviewRemoveConfirm() { WearPreview { Content( uiState = SettingsUiState(isRemoveDialogVisible = true), + nowMs = 0, onAboutClick = {}, + onSyncClick = {}, onRemoveClick = {}, onRemoveConfirm = {}, onRemoveDismiss = {}, diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt index 1e646b76ba..0ca553a1d4 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt @@ -7,18 +7,45 @@ import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val walletRepo: WalletRepo, + private val settingsSyncRepo: SettingsSyncRepo, + settingsStore: SettingsStore, ) : ViewModel() { private val _uiState = MutableStateFlow(SettingsUiState()) val uiState: StateFlow = _uiState.asStateFlow() + init { + viewModelScope.launch { + settingsStore.data.map { it.phoneSyncedAtMs }.distinctUntilChanged().collect { syncedAtMs -> + _uiState.update { it.copy(phoneSyncedAtMs = syncedAtMs) } + } + } + } + + /** + * Imports the phone's settings now, from the row that shows when they were last imported. The wearer asked, so + * it reads also right after another import, and a failure shows. + */ + fun onSyncClick() { + if (_uiState.value.isSyncing) return + _uiState.update { it.copy(isSyncing = true, isSyncFailed = false) } + viewModelScope.launch { + settingsSyncRepo.sync(isForced = true).onFailure { _uiState.update { it.copy(isSyncFailed = true) } } + _uiState.update { it.copy(isSyncing = false) } + } + } + fun onRemoveClick() { _uiState.update { it.copy(isRemoveDialogVisible = true, isRemoveFailed = false) } } @@ -46,4 +73,8 @@ data class SettingsUiState( val isRemoveDialogVisible: Boolean = false, val isRemoving: Boolean = false, val isRemoveFailed: Boolean = false, + val isSyncing: Boolean = false, + val isSyncFailed: Boolean = false, + /** When the phone's settings were last imported, in epoch milliseconds, or null when there is no import. */ + val phoneSyncedAtMs: Long? = null, ) diff --git a/wear/src/main/res/drawable/ic_sync.xml b/wear/src/main/res/drawable/ic_sync.xml new file mode 100644 index 0000000000..3a9cc0a862 --- /dev/null +++ b/wear/src/main/res/drawable/ic_sync.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index 8689cf9896..6a019b9691 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -68,6 +68,8 @@ تم الإرسال تحقق من النشاط في انتظار الشبكة + إعدادات الهاتف + تعذّر الاستيراد إزالة المحفظة إزالة المحفظة؟ تعذّرت إزالة المحفظة 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 d1f10a669f..6c6cf80683 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -65,6 +65,8 @@ Enviado Revisa la actividad Esperando la red + Ajustes del teléfono + No se pudo importar Eliminar billetera ¿Eliminar billetera? No se pudo eliminar la billetera diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index 860dfe7069..752d58a710 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -65,6 +65,8 @@ Enviat Revisa l\'activitat Esperant la xarxa + Configuració del telèfon + No s\'ha pogut importar Elimina la cartera Eliminar la cartera? No s\'ha pogut eliminar la cartera diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index c8e1d3e862..db62d4b208 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -66,6 +66,8 @@ Odesláno Zkontrolujte aktivitu Čekání na síť + Nastavení telefonu + Import se nezdařil Odebrat peněženku Odebrat peněženku? Peněženku nelze odebrat diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index 6ebbb244b7..c127f5e8d1 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -64,6 +64,8 @@ Gesendet Aktivität prüfen Warte auf Netzwerk + Telefon-Einstellungen + Import fehlgeschlagen Wallet entfernen Wallet entfernen? Wallet konnte nicht entfernt werden diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index 5de15f71cc..2ff5822172 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -64,6 +64,8 @@ Στάλθηκε Δες τη δραστηριότητα Αναμονή για δίκτυο + Ρυθμίσεις τηλεφώνου + Αδυναμία εισαγωγής Αφαίρεση πορτοφολιού Αφαίρεση πορτοφολιού; Αδυναμία αφαίρεσης πορτοφολιού diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index d5d8892c48..ab02c5e19b 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -65,6 +65,8 @@ Enviado Revisa la actividad Esperando a la red + Ajustes del teléfono + No se pudo importar Eliminar cartera ¿Eliminar cartera? No se pudo eliminar la cartera diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index d5d8892c48..ab02c5e19b 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -65,6 +65,8 @@ Enviado Revisa la actividad Esperando a la red + Ajustes del teléfono + No se pudo importar Eliminar cartera ¿Eliminar cartera? No se pudo eliminar la cartera diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index 16369dae9a..3302738046 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -65,6 +65,8 @@ Envoyé Voir l\'activité En attente du réseau + Paramètres du téléphone + Échec de l\'importation Supprimer le wallet Supprimer le wallet ? Impossible de supprimer le wallet diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index 455d808235..daee4e3424 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -65,6 +65,8 @@ Inviato Controlla l\'attività In attesa della rete + Impostazioni telefono + Importazione non riuscita Rimuovi portafoglio Rimuovere il portafoglio? Impossibile rimuovere il portafoglio diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index fe9594fcf2..79a1d475ed 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -64,6 +64,8 @@ Verzonden Bekijk activiteit Wachten op netwerk + Telefooninstellingen + Importeren mislukt Wallet verwijderen Wallet verwijderen? Wallet verwijderen mislukt diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index 141f583229..3ce8962352 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -66,6 +66,8 @@ Wysłano Sprawdź aktywność Czekam na sieć + Ustawienia telefonu + Import nie powiódł się Usuń portfel Usunąć portfel? Nie udało się usunąć portfela diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index 62223ee6f2..9496751b26 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -65,6 +65,8 @@ Enviado Veja a atividade Aguardando a rede + Ajustes do celular + Não foi possível importar Remover carteira Remover carteira? Não foi possível remover a carteira diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index 6fe44a3ebb..c2c80f951c 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -65,6 +65,8 @@ Enviado Veja a atividade À espera da rede + Ajustes do telemóvel + Não foi possível importar Remover carteira Remover carteira? Não foi possível remover a carteira diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index b7af04dbe9..c916fe53d7 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -66,6 +66,8 @@ Отправлено Проверьте активность Ожидание сети + Настройки телефона + Не удалось импортировать Удалить кошелёк Удалить кошелёк? Не удалось удалить кошелёк diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index b42d4c16ae..380d38685d 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -64,6 +64,8 @@ Sent Check activity Waiting for network + Phone settings + Couldn\'t import Remove wallet Remove wallet? Couldn\'t remove wallet diff --git a/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt new file mode 100644 index 0000000000..b2e81f9d82 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt @@ -0,0 +1,158 @@ +package to.bitkit.wear.data + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.job +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import to.bitkit.wear.test.BaseUnitTest +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** A [QuickPaySpendStore] in memory, counting as the real one does. */ +class FakeQuickPaySpendStore : QuickPaySpendStore { + var day: String? = null + var spentCents = 0L + var failure: Throwable? = null + + override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? { + failure?.let { throw it } + if (cents <= 0 || capCents <= 0) return null + val isNewDay = day.let { it == null || dayKey > it } + val spent = if (isNewDay) 0L else spentCents + if (cents > capCents - spent) return null + if (isNewDay) day = dayKey + spentCents = spent + cents + return day + } + + override suspend fun release(dayKey: String, cents: Long) { + failure?.let { throw it } + if (dayKey == day) spentCents = (spentCents - cents).coerceAtLeast(0L) + } +} + +/** The store against the real settings file, in a temporary directory. Each [open] is a new process. */ +class QuickPaySpendStoreTest : BaseUnitTest() { + private companion object { + const val TODAY = "2026-11-28" + const val TOMORROW = "2026-11-29" + } + + @get:Rule + val folder = TemporaryFolder() + + private val settingsFile by lazy { File(folder.root, "datastore/settings.preferences_pb") } + private var scope: CoroutineScope? = null + + @Test + fun `a day takes payments up to its cap and not a cent more, also after a restart`() = test { + val sut = open().first + assertNotNull(sut.reserve(TODAY, cents = 400, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 500, capCents = 1_000)) + close() + val next = open().first + + assertNull(next.reserve(TODAY, cents = 101, capCents = 1_000)) + assertNotNull(next.reserve(TODAY, cents = 100, capCents = 1_000)) + assertNull(next.reserve(TODAY, cents = 1, capCents = 1_000)) + close() + } + + @Test + fun `a refused payment counts for nothing`() = test { + val sut = open().first + + assertNull(sut.reserve(TODAY, cents = 1_001, capCents = 1_000)) + + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a new day starts from nothing and an earlier day does not`() = test { + val sut = open().first + assertNotNull(sut.reserve(TOMORROW, cents = 1_000, capCents = 1_000)) + + assertNull(sut.reserve(TODAY, cents = 1, capCents = 1_000)) + assertNull(sut.reserve(TOMORROW, cents = 1, capCents = 1_000)) + + assertNotNull(sut.reserve("2026-11-30", cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a payment of an earlier day is counted under the day last counted`() = test { + val sut = open().first + assertEquals(TOMORROW, sut.reserve(TOMORROW, cents = 400, capCents = 1_000)) + + assertEquals(TOMORROW, sut.reserve(TODAY, cents = 600, capCents = 1_000)) + assertNull(sut.reserve(TOMORROW, cents = 1, capCents = 1_000)) + close() + } + + @Test + fun `a released payment frees its cents in the day counted, and nothing in another day`() = test { + val sut = open().first + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + + sut.release(TOMORROW, cents = 1_000) + sut.release(TODAY, cents = 0) + assertNull(sut.reserve(TODAY, cents = 1, capCents = 1_000)) + + sut.release(TODAY, cents = 400) + assertNull(sut.reserve(TODAY, cents = 401, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 400, capCents = 1_000)) + + sut.release(TODAY, cents = 5_000) + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a lowered cap counts what was already spent`() = test { + val sut = open().first + assertNotNull(sut.reserve(TODAY, cents = 800, capCents = 1_000)) + + assertNull(sut.reserve(TODAY, cents = 1, capCents = 500)) + close() + } + + @Test + fun `nothing and less than nothing are refused`() = test { + val sut = open().first + + assertNull(sut.reserve(TODAY, cents = 0, capCents = 1_000)) + assertNull(sut.reserve(TODAY, cents = -5, capCents = 1_000)) + assertNull(sut.reserve(TODAY, cents = 1, capCents = 0)) + assertNull(sut.reserve(TODAY, cents = Long.MAX_VALUE, capCents = 1_000)) + close() + } + + @Test + fun `the wallet's wipe forgets the day's spend with the settings`() = test { + val (sut, settings) = open() + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + + settings.finishWipe() + + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + close() + } + + private fun open(): Pair { + val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } + val dataStore = settingsDataStore(opened) { settingsFile } + val settings = SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") })) + return SettingsQuickPaySpendStore(dataStore) to settings + } + + private suspend fun close() { + scope?.coroutineContext?.job?.cancelAndJoin() + scope = null + } +} diff --git a/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt index 3b0a096de9..86a51f8746 100644 --- a/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt @@ -8,7 +8,10 @@ import kotlinx.coroutines.job import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.QuickPayLimits import to.bitkit.wear.security.FakeDeviceLock import to.bitkit.wear.security.FakeSeedKey import to.bitkit.wear.security.KeystoreSeedStore @@ -19,6 +22,7 @@ import java.io.IOException import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue /** @@ -26,6 +30,11 @@ import kotlin.test.assertTrue * a new process over what is on disk. */ class SettingsStoreTest : BaseUnitTest() { + private companion object { + val QUICK_PAY = QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3) + val PHONE_SETTINGS = PhoneSettings(PrimaryDisplay.FIAT, BitcoinDisplayUnit.CLASSIC, "EUR", QUICK_PAY) + } + @get:Rule val folder = TemporaryFolder() @@ -80,6 +89,100 @@ class SettingsStoreTest : BaseUnitTest() { close() } + @Test + fun `the phone's settings are adopted and survive a restart`() = test { + open().applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + close() + + val settings = open().data.first() + + assertEquals( + WatchSettings( + primaryDisplay = PrimaryDisplay.FIAT, + selectedCurrency = "EUR", + displayUnit = BitcoinDisplayUnit.CLASSIC, + quickPay = QUICK_PAY, + phoneSyncedAtMs = 5_000L, + ), + settings, + ) + close() + } + + @Test + fun `nothing is imported until the phone's settings are applied`() = test { + val settings = open().data.first() + + assertNull(settings.quickPay) + assertNull(settings.phoneSyncedAtMs) + assertEquals(BitcoinDisplayUnit.MODERN, settings.displayUnit) + close() + } + + @Test + fun `display values the backup does not hold keep the watch's, and unreadable quickpay turns it off`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + + sut.applyPhoneSettings(PhoneSettings(null, null, null, quickPay = null), syncedAtMs = 6_000L) + + val settings = sut.data.first() + assertEquals(PrimaryDisplay.FIAT, settings.primaryDisplay) + assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) + assertEquals("EUR", settings.selectedCurrency) + assertNull(settings.quickPay) + assertEquals(6_000L, settings.phoneSyncedAtMs) + close() + } + + @Test + fun `the wearer's unit swap lasts until the phone's setting changes`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + sut.setPrimaryDisplay(PrimaryDisplay.BITCOIN) + + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 6_000L) + assertEquals(PrimaryDisplay.BITCOIN, sut.data.first().primaryDisplay) + + sut.applyPhoneSettings(PHONE_SETTINGS.copy(primaryDisplay = PrimaryDisplay.BITCOIN), syncedAtMs = 7_000L) + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 8_000L) + assertEquals(PrimaryDisplay.FIAT, sut.data.first().primaryDisplay) + close() + } + + @Test + fun `clearing quickpay keeps the display values and forgets the import time`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + + sut.clearQuickPay() + + val settings = sut.data.first() + assertNull(settings.quickPay) + assertNull(settings.phoneSyncedAtMs) + assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) + assertEquals("EUR", settings.selectedCurrency) + close() + } + + @Test + fun `the wallet's wipe clears everything imported from the phone, as does an overtaken import`() = test { + val sut = open() + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + + sut.finishWipe() + + assertEquals(WatchSettings(), sut.data.first()) + + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + sut.clearPhoneSettings() + + assertEquals(WatchSettings(), sut.data.first()) + close() + assertEquals(WatchSettings(), open().data.first()) + close() + } + @Test fun `a wipe note survives the seed being deleted`() = test { val seedStore = KeystoreSeedStore(lazy { seedDirectory }, FakeSeedKey(), FakeDeviceLock(), false) diff --git a/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt b/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt index cad19e7d9c..6e9db736be 100644 --- a/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt +++ b/wear/src/test/java/to/bitkit/wear/models/CurrencyTest.kt @@ -14,6 +14,14 @@ class CurrencyTest { assertEquals("21 000 000", 21_000_000L.formatToModernDisplay(Locale.US)) } + @Test + fun `the classic unit writes bitcoin with eight decimals`() { + assertEquals("0.00050000", 50_000L.formatToClassicDisplay(Locale.US)) + assertEquals("1.00000000", 100_000_000L.formatToClassicDisplay(Locale.GERMANY)) + assertEquals("0.00000001", 1L.formatMoney(BitcoinDisplayUnit.CLASSIC, Locale.US)) + assertEquals("50 000", 50_000L.formatMoney(BitcoinDisplayUnit.MODERN, Locale.US)) + } + @Test fun `fiat value converts sats at the rate and formats with the symbol`() { val value = fiatValue(sats = 150_000, rate = rate("100000")) diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt new file mode 100644 index 0000000000..bbc1004c22 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt @@ -0,0 +1,58 @@ +package to.bitkit.wear.models + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Test +import to.bitkit.wear.env.Env +import to.bitkit.wear.env.WalletNetwork +import to.bitkit.wear.repositories.SettingsSyncRepo +import kotlin.test.assertEquals + +/** + * `phone-backup-contract.json` holds what the watch needs the phone to keep writing: the backup's key, the six + * settings in the phone's own encoding, and where each network's backups live. The phone's `WatchBackupContractTest` + * compares the same file with what the phone app really writes and uses, so a renamed field or a moved server fails + * a test instead of silently turning QuickPay off on the watch. + */ +class PhoneBackupContractTest { + private val contract: JsonObject by lazy { + val text = checkNotNull(javaClass.classLoader?.getResource("phone-backup-contract.json")).readText() + Json.parseToJsonElement(text).jsonObject + } + + @Test + fun `the watch reads the settings backup under the phone's key`() { + assertEquals(contract.getValue("settingsKey").jsonPrimitive.content, SettingsSyncRepo.SETTINGS_KEY) + } + + @Test + fun `the watch reads all six settings as the phone writes them`() { + val backup = contract.getValue("settingsBackup").toString().toByteArray() + + val expected = PhoneSettings( + PrimaryDisplay.FIAT, + BitcoinDisplayUnit.CLASSIC, + "EUR", + QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), + ) + assertEquals(expected, PhoneSettingsParser.parse(backup)) + } + + @Test + fun `the watch looks for each network's backups where the phone stores them`() { + val networks = contract.getValue("networks").jsonObject + + assertEquals(WalletNetwork.entries.map { it.name }.toSet(), networks.keys) + for (network in WalletNetwork.entries) { + val expected = networks.getValue(network.name).jsonObject.mapValues { it.value.jsonPrimitive.content } + val actual = mapOf( + "storeIdPrefix" to Env.vssStoreIdPrefix(network), + "vssServerUrl" to Env.vssServerUrl(network), + "lnurlAuthServerUrl" to Env.lnurlAuthServerUrl(network), + ) + assertEquals(expected, actual, "$network") + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt new file mode 100644 index 0000000000..aa2d4bf5c7 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt @@ -0,0 +1,146 @@ +package to.bitkit.wear.models + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull + +class PhoneSettingsParserTest { + private companion object { + /** A cut of what bitkit-android writes: pretty-printed, every default encoded, many keys the watch ignores. */ + val ANDROID_BACKUP = """ + { + "version": 1, + "createdAt": 1800000000000, + "settings": { + "primaryDisplay": "FIAT", + "displayUnit": "CLASSIC", + "selectedCurrency": "EUR", + "hideBalance": true, + "isPinEnabled": false, + "quickPayIntroSeen": true, + "isQuickPayEnabled": true, + "quickPayAmount": 10, + "quickPayDailyLimitMultiplier": 3, + "addressTypesToMonitor": ["NATIVE_SEGWIT"], + "someFutureSetting": {"nested": [1, 2, 3]} + } + } + """.trimIndent() + } + + @Test + fun `the phone's backup gives the units, the currency and quickpay, and ignores every other key`() { + val settings = parse(ANDROID_BACKUP) + + assertEquals( + PhoneSettings( + primaryDisplay = PrimaryDisplay.FIAT, + displayUnit = BitcoinDisplayUnit.CLASSIC, + selectedCurrency = "EUR", + quickPay = QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), + ), + settings, + ) + assertEquals(1_000L, settings.quickPay?.thresholdCents) + assertEquals(3_000L, settings.quickPay?.dailyCapCents) + } + + @Test + fun `enums written by ios are read too`() { + val settings = parse( + """{"version":1,"createdAt":1,"settings":{"primaryDisplay":{"fiat":{}},"displayUnit":"classic"}}""", + ) + + assertEquals(PrimaryDisplay.FIAT, settings.primaryDisplay) + assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) + } + + @Test + fun `a display value that is missing or unreadable is left to the watch`() { + val settings = parse( + """{"version":1,"settings":{"primaryDisplay":"GOLD","displayUnit":7,"selectedCurrency":"dollars"}}""", + ) + + assertNull(settings.primaryDisplay) + assertNull(settings.displayUnit) + assertNull(settings.selectedCurrency) + assertEquals(PhoneSettings(null, null, null, null), parse("""{"settings":{}}""")) + } + + @Test + fun `quickpay that is off keeps its limits`() { + val settings = parse(quickPay("false", "5", "5")) + + assertEquals(QuickPayLimits(isEnabled = false, amountUsd = 5, dailyMultiplier = 5), settings.quickPay) + } + + @Test + fun `quickpay with a missing, mistyped or out of range value is not adopted`() { + val settings = """{"isQuickPayEnabled":true,"quickPayAmount":5}""" + assertNull(parse("""{"version":1,"settings":$settings}""").quickPay) + assertNull(parse("""{"version":1,"settings":{"quickPayAmount":5,"quickPayDailyLimitMultiplier":5}}""").quickPay) + for ((isEnabled, amount, multiplier) in listOf( + Triple("\"true\"", "5", "5"), + Triple("1", "5", "5"), + Triple("null", "5", "5"), + Triple("true", "\"5\"", "5"), + Triple("true", "5.5", "5"), + Triple("true", "0", "5"), + Triple("true", "-5", "5"), + Triple("true", "51", "5"), + Triple("true", "99999999999", "5"), + Triple("true", "5", "0"), + Triple("true", "5", "51"), + Triple("true", "5", "[5]"), + )) { + assertNull(parse(quickPay(isEnabled, amount, multiplier)).quickPay, "$isEnabled $amount $multiplier") + } + } + + @Test + fun `the largest values the phone offers are adopted`() { + val settings = parse(quickPay("true", "50", "50")) + + assertEquals(QuickPayLimits(isEnabled = true, amountUsd = 50, dailyMultiplier = 50), settings.quickPay) + assertEquals(250_000L, settings.quickPay?.dailyCapCents) + } + + @Test + fun `a newer layout is refused`() { + val error = assertFailsWith { + parse("""{"version":2,"createdAt":1,"settings":{"isQuickPayEnabled":true}}""") + } + + assertEquals("The settings backup has version '2'", error.message) + } + + @Test + fun `what is not the phone's envelope is refused`() { + for (raw in listOf( + "", + "not json", + "[]", + "\"SETTINGS\"", + "{}", + """{"version":1}""", + """{"version":1,"settings":[]}""", + """{"version":1,"settings":"{}"}""", + """{"version":"new","settings":{}}""", + """{"version":0,"settings":{}}""", + """{"version":{},"settings":{}}""", + )) { + assertFailsWith(raw) { parse(raw) } + } + assertFailsWith { + PhoneSettingsParser.parse(ByteArray(PhoneSettingsParser.MAX_BYTES + 1) { ' '.code.toByte() }) + } + assertFailsWith { PhoneSettingsParser.parse(byteArrayOf(-1, 0, -2)) } + } + + private fun quickPay(isEnabled: String, amount: String, multiplier: String) = + """{"version":1,"settings":{"isQuickPayEnabled":$isEnabled,"quickPayAmount":$amount,""" + + """"quickPayDailyLimitMultiplier":$multiplier}}""" + + private fun parse(raw: String) = PhoneSettingsParser.parse(raw.toByteArray()) +} 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 483b90ff8d..a06071d199 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -27,8 +27,10 @@ import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.wear.data.FakeOwnInvoiceStore @@ -70,6 +72,7 @@ class PaymentsRepoTest : BaseUnitTest() { const val LNURL_BOLT11 = "lnbcrt1fromlnurl" const val BALANCE = 10_000uL const val FEE = 4uL + val RESERVATION = QuickPayReservation("2026-11-28", cents = 50) } private val sparkService = mock() @@ -79,6 +82,7 @@ class PaymentsRepoTest : BaseUnitTest() { private val ownInvoices = FakeOwnInvoiceStore() private val uncertainSends = FakeUncertainSendStore() private val decoder = FakeInputDecoder() + private val quickPayRepo = mock() private lateinit var sut: PaymentsRepo @@ -101,6 +105,7 @@ class PaymentsRepoTest : BaseUnitTest() { WalletSelfSendGuard(sparkService, ownInvoices), ownInvoices, uncertainSends, + quickPayRepo, ) } @@ -114,6 +119,7 @@ class PaymentsRepoTest : BaseUnitTest() { WalletSelfSendGuard(sparkService, ownInvoices), ownInvoices, uncertainSends, + quickPayRepo, ) } @@ -538,8 +544,268 @@ class PaymentsRepoTest : BaseUnitTest() { } @Test - fun `quickpay never skips the confirmation yet`() = test { - assertFalse(sut.skipConfirmation(preparedSend())) + fun `quickpay skips the hold for an invoice with an amount, at its amount without the fee`() = test { + whenever(quickPayRepo.reserve(500uL)).thenReturn(RESERVATION) + + assertTrue(sut.skipConfirmation(preparedSend()) { true }) + + verify(quickPayRepo, times(1)).reserve(any()) + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `quickpay fetches a missing rate before it reads the limits`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + + sut.skipConfirmation(preparedSend()) { true } + + val order = inOrder(quickPayRepo) + order.verify(quickPayRepo).awaitRate() + order.verify(quickPayRepo).reserve(any()) + } + + @Test + fun `quickpay holds when the wallet stopped being ready while it waited for the rate`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(quickPayRepo.awaitRate()).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Paused) } + } + + assertFalse(sut.skipConfirmation(preparedSend()) { true }) + } + + @Test + fun `quickpay holds when the limits say no`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(null) + + assertFalse(sut.skipConfirmation(preparedSend()) { true }) + } + + @Test + fun `quickpay holds and counts nothing when the wearer left while the limits were read`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val prepared = preparedSend() + + assertFalse(sut.skipConfirmation(prepared) { false }) + + verify(quickPayRepo).release(RESERVATION) + // The wearer then holds to pay, and a failure of that send releases nothing a second time. + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + sut.send(prepared) + verify(quickPayRepo, times(1)).release(any()) + } + + @Test + fun `quickpay never skips the hold for an amount the wearer typed`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val amountless = sut.prepare(SendRequest.Invoice(BOLT11, null, null), amountSats = 500uL).getOrThrow() + val range = SendRequest.Lnurl(lnurl(10_000uL, 20_000uL), minSats = 10uL, maxSats = 20uL, payee = null) + stubLnurlInvoice() + val typed = sut.prepare(range, amountSats = 15uL).getOrThrow() + + assertFalse(sut.skipConfirmation(amountless) { true }) + assertFalse(sut.skipConfirmation(typed) { true }) + + verify(quickPayRepo, never()).awaitRate() + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay skips the hold for an lnurl or a lightning address that takes one amount, as on the phone`() = + test { + whenever(quickPayRepo.reserve(15uL)).thenReturn(RESERVATION) + val fixed = SendRequest.Lnurl(lnurl(15_000uL, 15_000uL), minSats = 15uL, maxSats = 15uL, payee = null) + stubLnurlInvoice() + + assertTrue(sut.skipConfirmation(sut.prepare(fixed).getOrThrow()) { true }) + } + + @Test + fun `quickpay skips the hold for an uppercase bitcoin uri with an amount, like a lowercase one`() = test { + whenever(quickPayRepo.reserve(500uL)).thenReturn(RESERVATION) + decoder.inputs["bitcoin:bcrt1q?lightning=$BOLT11"] = onchain(mapOf("lightning" to BOLT11)) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 500uL) + val links = listOf( + "bitcoin:bcrt1q?lightning=$BOLT11", + "BITCOIN:BCRT1Q?LIGHTNING=${BOLT11.uppercase()}", + ) + + for (link in links) { + val request = sut.parse(link).getOrThrow() + assertEquals(500uL, request.fixedAmountSats, link) + assertTrue(sut.skipConfirmation(sut.prepare(request).getOrThrow()) { true }, link) + } + + verify(quickPayRepo, times(2)).reserve(500uL) + } + + @Test + fun `quickpay never skips the hold for an uppercase bitcoin uri without an amount`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + decoder.inputs["bitcoin:bcrt1q?lightning=$BOLT11"] = onchain(mapOf("lightning" to BOLT11)) + decoder.inputs[BOLT11] = lightning(BOLT11, amountSats = 0uL) + + val request = sut.parse("BITCOIN:BCRT1Q?LIGHTNING=${BOLT11.uppercase()}").getOrThrow() + assertNull(request.fixedAmountSats) + + assertFalse(sut.skipConfirmation(sut.prepare(request, amountSats = 500uL).getOrThrow()) { true }) + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `an lnurlp link follows the lnurl rule for quickpay, one amount only`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + decoder.inputs["https://pay.example/lnurlp/fixed"] = Scanner.LnurlPay(lnurl(15_000uL, 15_000uL)) + decoder.inputs["https://pay.example/lnurlp/range"] = Scanner.LnurlPay(lnurl(10_000uL, 20_000uL)) + stubLnurlInvoice() + + val fixed = sut.parse("lnurlp://pay.example/lnurlp/fixed").getOrThrow() + val range = sut.parse("LNURLP://pay.example/lnurlp/range").getOrThrow() + + assertEquals(15uL, fixed.fixedAmountSats) + assertNull(range.fixedAmountSats) + assertTrue(sut.skipConfirmation(sut.prepare(fixed).getOrThrow()) { true }) + assertFalse(sut.skipConfirmation(sut.prepare(range, amountSats = 15uL).getOrThrow()) { true }) + verify(quickPayRepo, times(1)).reserve(15uL) + } + + @Test + fun `quickpay holds for an lnurl whose range only rounds to one amount, as on the phone`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val rounded = SendRequest.Lnurl(lnurl(14_500uL, 15_500uL), minSats = 15uL, maxSats = 15uL, payee = null) + stubLnurlInvoice() + + assertFalse(sut.skipConfirmation(sut.prepare(rounded).getOrThrow()) { true }) + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold for a spark address`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.parse(SPARK_ADDRESS)).thenReturn(sparkAddressInput(OTHER_IDENTITY)) + whenever(sparkService.prepareSend(SPARK_ADDRESS, 500uL)).thenReturn(preparedTransfer()) + val transfer = sut.prepare(SendRequest.SparkAddress(SPARK_ADDRESS), amountSats = 500uL).getOrThrow() + + assertFalse(sut.skipConfirmation(transfer) { true }) + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold unless the wallet is ready`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + val prepared = preparedSend() + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertFalse(sut.skipConfirmation(prepared) { true }, "$status") + } + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold during a wipe or once the wallet stopped being ready meanwhile`() = test { + val prepared = preparedSend() + whenever(sparkService.isWiping).thenReturn(true) + assertFalse(sut.skipConfirmation(prepared) { true }) + verify(quickPayRepo, never()).reserve(any()) + + whenever(sparkService.isWiping).thenReturn(false) + whenever(quickPayRepo.reserve(any())).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Locked) } + RESERVATION + } + assertFalse(sut.skipConfirmation(prepared) { true }) + verify(quickPayRepo).release(RESERVATION) + } + + @Test + fun `a quickpay send that is paid or still pending stays counted`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + sut.send(prepared).getOrThrow() + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay send that failed or was refused is taken out of the day's count, once`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + assertIs(sut.send(prepared).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(quickPayRepo, times(1)).release(RESERVATION) + } + + @Test + fun `a quickpay send of unknown outcome stays counted`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).doSuspendableAnswer { throw SdkException.NetworkException("reset") } + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay send that ends in an error the watch does not know stays counted`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + whenever(sparkService.releaseSend()).thenThrow(IllegalStateException("released twice")) + val prepared = preparedSend() + sut.skipConfirmation(prepared) { true } + + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a quickpay yes that its caller no longer waits for is taken out of the day's count`() = test { + val reserved = CompletableDeferred() + whenever(quickPayRepo.reserve(any())).doSuspendableAnswer { reserved.await() } + val prepared = preparedSend() + val asking = launch { sut.skipConfirmation(prepared) { true } } + + asking.cancel() + reserved.complete(RESERVATION) + asking.join() + + verify(quickPayRepo, times(1)).release(RESERVATION) + // Nothing is left for a later send of it to take out a second time. + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + sut.send(prepared) + verify(quickPayRepo, times(1)).release(any()) + } + + @Test + fun `a send that was held for releases nothing when it fails`() = test { + whenever(sparkService.send(any(), any())).thenReturn(payment("key-0", PaymentStatus.FAILED)) + + assertIs(sut.send(preparedSend()).exceptionOrNull()) + + verify(quickPayRepo, never()).release(any()) + } + + @Test + fun `a request the checks refuse never reaches quickpay`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) + ownInvoices.add(PAYMENT_HASH, SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY) + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + + verify(quickPayRepo, never()).reserve(any()) } // endregion @@ -1163,6 +1429,13 @@ class PaymentsRepoTest : BaseUnitTest() { collecting.cancel() } + private suspend fun stubLnurlInvoice() { + decoder.lnurlInvoices[15_000uL] = LNURL_BOLT11 + decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 15uL) + whenever(sparkService.parse(LNURL_BOLT11)).thenReturn(invoiceInput(LNURL_BOLT11, "cc".repeat(32))) + whenever(sparkService.prepareSend(LNURL_BOLT11, null)).thenReturn(prepared(amountMsat = 15_000uL)) + } + private suspend fun preparedSend(): PreparedSend = sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).getOrThrow() diff --git a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt new file mode 100644 index 0000000000..2413efa15d --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -0,0 +1,290 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.update +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.FakeQuickPaySpendStore +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.QuickPayLimits +import to.bitkit.wear.models.rate +import to.bitkit.wear.test.BaseUnitTest +import java.io.IOException +import java.time.ZoneId +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes + +/** At 100 000 dollars a bitcoin one sat is a tenth of a cent, so 5 dollars are exactly 5 000 sats. */ +@OptIn(ExperimentalCoroutinesApi::class) +class QuickPayRepoTest : BaseUnitTest() { + private companion object { + /** 2026-11-28T12:00:00Z */ + const val NOW = 1_795_867_200_000L + const val FIVE_DOLLARS = 5_000uL + val LIMITS = QuickPayLimits(isEnabled = true, amountUsd = 5, dailyMultiplier = 3) + } + + private val settingsStore = mock() + private val currencyRepo = mock() + private val spend = FakeQuickPaySpendStore() + private var zone = ZoneId.of("UTC") + private val settings = MutableStateFlow(WatchSettings(quickPay = LIMITS, phoneSyncedAtMs = NOW)) + private val rates = MutableStateFlow(listOf(rate("100000"), rate("90000", quote = "EUR"))) + private var now = NOW + + private lateinit var sut: QuickPayRepo + + @Before + fun setUp() { + whenever(settingsStore.data).thenReturn(settings) + whenever(currencyRepo.rates).thenReturn(rates) + whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) + sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, { now }, { zone }) + } + + @Test + fun `a missing dollar rate is fetched before the payment is decided, while quickpay is on`() = test { + rates.update { listOf(rate("90000", quote = "EUR")) } + whenever(currencyRepo.refresh()).doSuspendableAnswer { + rates.update { listOf(rate("100000")) } + Result.success(Unit) + } + + sut.awaitRate() + + assertNotNull(sut.reserve(1uL)) + verify(currencyRepo, times(1)).refresh() + } + + @Test + fun `the wait for the rate ends after five seconds and the payment then holds`() = test { + rates.update { emptyList() } + whenever(currencyRepo.refresh()).doSuspendableAnswer { awaitCancellation() } + + val waiting = async { sut.awaitRate() } + testScheduler.advanceTimeBy(QuickPayRepo.RATE_TIMEOUT.inWholeMilliseconds - 1) + assertFalse(waiting.isCompleted) + testScheduler.advanceTimeBy(2) + + assertTrue(waiting.isCompleted) + assertNull(sut.reserve(1uL)) + assertEquals(0L, spend.spentCents) + } + + @Test + fun `no rate is fetched with one at hand, with quickpay off or before any import`() = test { + sut.awaitRate() + + rates.update { emptyList() } + settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } + sut.awaitRate() + settings.update { WatchSettings() } + sut.awaitRate() + whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) + sut.awaitRate() + + verify(currencyRepo, never()).refresh() + } + + @Test + fun `the last import decides however old it is, as the phone's own settings do`() = test { + now = NOW + 30.days.inWholeMilliseconds + assertNotNull(sut.reserve(1uL)) + + settings.update { it.copy(phoneSyncedAtMs = null) } + assertNotNull(sut.reserve(1uL)) + } + + @Test + fun `a payment of exactly the phone's amount skips the hold and one sat more does not`() = test { + assertNull(sut.reserve(FIVE_DOLLARS + 1uL)) + assertEquals(0L, spend.spentCents) + + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertEquals(500L, spend.spentCents) + } + + @Test + fun `the last sat of an amount that rounded up is worth more than the phone's amount and holds`() = test { + // 1 dollar is 1 030.9 sats, rounded up to 1 031, which are worth 1.00007 dollars. + rates.update { listOf(rate("97000")) } + settings.update { it.copy(quickPay = LIMITS.copy(amountUsd = 1)) } + + assertNull(sut.reserve(1_031uL)) + assertEquals(0L, spend.spentCents) + + assertNotNull(sut.reserve(1_030uL)) + assertEquals(100L, spend.spentCents) + } + + @Test + fun `the smallest payment skips the hold and counts as a whole cent`() = test { + assertNotNull(sut.reserve(1uL)) + + assertEquals(1L, spend.spentCents) + } + + @Test + fun `nothing skips the hold before the phone's settings were ever imported`() = test { + settings.update { WatchSettings() } + + assertNull(sut.reserve(1uL)) + assertNull(sut.reserve(FIVE_DOLLARS)) + } + + @Test + fun `nothing skips the hold while quickpay is off on the phone`() = test { + settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } + + assertNull(sut.reserve(1uL)) + } + + @Test + fun `without a dollar rate nothing skips the hold`() = test { + rates.update { listOf(rate("90000", quote = "EUR")) } + assertNull(sut.reserve(1uL)) + + for (price in listOf("n/a", "0", "-100000", "")) { + rates.update { listOf(rate(price)) } + assertNull(sut.reserve(1uL), price) + } + assertEquals(0L, spend.spentCents) + + rates.update { listOf(rate("100000")) } + assertNotNull(sut.reserve(1uL)) + } + + @Test + fun `the amount is valued and rounded as on the phone`() = test { + // 5 dollars at 64 321.98 are 7 773.39 sats, which the phone rounds to 7 773. + rates.update { listOf(rate("64321.98")) } + assertNull(sut.reserve(7_774uL)) + + // 7 773 sats are 499.97 cents, counted as 500; 100 sats are 6.43 cents, counted as 6. + assertEquals(500L, sut.reserve(7_773uL)?.cents) + assertEquals(6L, sut.reserve(100uL)?.cents) + } + + @Test + fun `a payment worth more than the phone's amount holds, so none counts for more`() = test { + // At 3 000 000 dollars a bitcoin 5 dollars round up to 167 sats, which are worth 501 cents. + rates.update { listOf(rate("3000000")) } + + assertNull(sut.reserve(167uL)) + assertEquals(498L, sut.reserve(166uL)?.cents) + } + + @Test + fun `a payment that failed is taken out of the day's count again`() = test { + repeat(2) { assertNotNull(sut.reserve(FIVE_DOLLARS)) } + val failed = assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNull(sut.reserve(1uL)) + + sut.release(failed) + + assertEquals(1_000L, spend.spentCents) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + } + + @Test + fun `a payment of an earlier day is not taken out of today's count`() = test { + val yesterday = assertNotNull(sut.reserve(FIVE_DOLLARS)) + now = NOW + 12.hours.inWholeMilliseconds + assertNotNull(sut.reserve(FIVE_DOLLARS)) + + sut.release(yesterday) + + assertEquals(500L, spend.spentCents) + spend.failure = IOException("disk") + sut.release(yesterday) + } + + @Test + fun `the limit follows the rate, not the sats`() = test { + rates.update { listOf(rate("200000")) } + + assertNull(sut.reserve(2_501uL)) + assertNotNull(sut.reserve(2_500uL)) + } + + @Test + fun `no amount and an absurd amount skip nothing`() = test { + assertNull(sut.reserve(0uL)) + assertNull(sut.reserve(ULong.MAX_VALUE)) + assertNull(sut.reserve(Long.MAX_VALUE.toULong())) + } + + @Test + fun `the day's payments stop at the phone's daily limit`() = test { + repeat(3) { assertNotNull(sut.reserve(FIVE_DOLLARS), "payment $it") } + + assertNull(sut.reserve(1uL)) + assertEquals(1_500L, spend.spentCents) + } + + @Test + fun `a payment that would pass the daily limit is refused whole`() = test { + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(4_000uL)) + + // 1 005 sats are 100.5 cents, counted as 101. + assertNull(sut.reserve(1_005uL)) + assertNotNull(sut.reserve(1_000uL)) + } + + @Test + fun `the next day starts a new count`() = test { + repeat(3) { sut.reserve(FIVE_DOLLARS) } + assertNull(sut.reserve(1uL)) + + now = NOW + 12.hours.inWholeMilliseconds + + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertEquals("2026-11-29", spend.day) + } + + @Test + fun `the day is the watch's local date where that differs from the date in UTC`() = test { + // Noon UTC on the 28th is 02:00 on the 29th at UTC+14. + zone = ZoneId.of("Pacific/Kiritimati") + repeat(3) { assertNotNull(sut.reserve(FIVE_DOLLARS)) } + assertEquals("2026-11-29", spend.day) + + // 23:00 UTC, the 28th still, and 13:00 on the 29th there: the same day. + now = NOW + 11.hours.inWholeMilliseconds + assertNull(sut.reserve(1uL)) + + // 10:30 UTC on the 29th is 00:30 on the 30th there: a new day, although UTC's date is the one counted. + now = NOW + 22.hours.inWholeMilliseconds + 30.minutes.inWholeMilliseconds + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertEquals("2026-11-30", spend.day) + } + + @Test + fun `settings or a count that cannot be read skip nothing`() = test { + spend.failure = IOException("disk") + assertNull(sut.reserve(1uL)) + + spend.failure = null + whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) + assertNull(sut.reserve(1uL)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt new file mode 100644 index 0000000000..191dc2314a --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt @@ -0,0 +1,361 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.PhoneSettings +import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.QuickPayLimits +import to.bitkit.wear.security.FakeSeedStore +import to.bitkit.wear.security.SeedStoreError +import to.bitkit.wear.security.WalletSeed +import to.bitkit.wear.services.PhoneBackupReader +import to.bitkit.wear.services.PhoneBackupUnreadable +import to.bitkit.wear.services.SparkError +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.test.BaseUnitTest +import java.io.IOException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +@OptIn(ExperimentalCoroutinesApi::class) +class SettingsSyncRepoTest : BaseUnitTest() { + private companion object { + const val NOW = 1_795_867_200_000L + const val TOKEN = 4 + const val WAIT_SECS = 10L + val SEED = WalletSeed("abandon about", passphrase = "pass") + val BACKUP = """ + {"version":1,"createdAt":1,"settings":{"primaryDisplay":"FIAT","displayUnit":"CLASSIC", + "selectedCurrency":"EUR","isQuickPayEnabled":true,"quickPayAmount":10,"quickPayDailyLimitMultiplier":3}} + """.trimIndent().toByteArray() + val SETTINGS = PhoneSettings( + PrimaryDisplay.FIAT, + BitcoinDisplayUnit.CLASSIC, + "EUR", + QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), + ) + } + + private val seedStore = FakeSeedStore(SEED) + private val settingsStore = mock() + private val sparkService = mock() + private val walletRepo = mock() + private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 1uL, hasSynced = true)) + private val reads = mutableListOf>() + private var read: suspend () -> ByteArray? = { BACKUP } + private var elapsedMs = 90_000L + private val reader = PhoneBackupReader { seed, key -> + reads += seed to key + read() + } + + private lateinit var sut: SettingsSyncRepo + + @Before + fun setUp() { + whenever(walletRepo.walletState).thenReturn(walletState) + whenever(sparkService.wipeToken()).thenReturn(TOKEN) + whenever(sparkService.isCurrent(TOKEN)).thenReturn(true) + sut = SettingsSyncRepo( + testDispatcher, + seedStore, + reader, + settingsStore, + sparkService, + walletRepo, + { elapsedMs }, + { NOW }, + ) + } + + @Test + fun `the phone's settings backup is read with the wallet's seed and adopted`() = test { + sut.sync().getOrThrow() + + assertEquals(listOf(SEED to "SETTINGS"), reads) + verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a missing backup keeps the watch's values and turns quickpay off`() = test { + read = { null } + + sut.sync().getOrThrow() + + verify(settingsStore).clearQuickPay() + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `an unreadable backup or a newer layout keeps the watch's values and turns quickpay off`() = test { + for (raw in listOf("garbage", """{"version":2,"settings":{"isQuickPayEnabled":true}}""")) { + read = { raw.toByteArray() } + + assertTrue(sut.sync(isForced = true).isSuccess, raw) + } + + verify(settingsStore, times(2)).clearQuickPay() + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a backup that cannot be decrypted turns quickpay off at once`() = test { + read = { throw PhoneBackupUnreadable() } + + assertTrue(sut.sync().isSuccess) + + verify(settingsStore).clearQuickPay() + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `an import right after another reads nothing, unless the wearer asked or a minute passed`() = test { + sut.sync().getOrThrow() + + elapsedMs += SettingsSyncRepo.MIN_READ_GAP.inWholeMilliseconds - 1 + assertTrue(sut.sync().isSuccess) + assertEquals(1, reads.size) + + assertTrue(sut.sync(isForced = true).isSuccess) + assertEquals(2, reads.size) + + elapsedMs += SettingsSyncRepo.MIN_READ_GAP.inWholeMilliseconds + assertTrue(sut.sync().isSuccess) + assertEquals(3, reads.size) + verify(settingsStore, times(3)).applyPhoneSettings(SETTINGS, NOW) + } + + @Test + fun `a missing backup counts as read, a failed read does not, and another wallet's read never does`() = test { + read = { throw IOException("offline") } + assertTrue(sut.sync().isFailure) + read = { null } + assertTrue(sut.sync().isSuccess) + assertTrue(sut.sync().isSuccess) + assertEquals(2, reads.size) + + // A wipe and a restore later the last read was the removed wallet's. + whenever(sparkService.wipeToken()).thenReturn(TOKEN + 2) + whenever(sparkService.isCurrent(TOKEN + 2)).thenReturn(true) + assertTrue(sut.sync().isSuccess) + assertEquals(3, reads.size) + } + + @Test + fun `a second import that waited for the first joins it and reads nothing`() = test { + val gate = CompletableDeferred() + read = { + gate.await() + BACKUP + } + val first = async { sut.sync() } + val second = async { sut.sync() } + + gate.complete(Unit) + + assertTrue(first.await().isSuccess) + assertTrue(second.await().isSuccess) + assertEquals(1, reads.size) + } + + @Test + fun `a read is given up the moment the wallet stops being ready`() = test { + for (status in listOf(WalletStatus.Locked, WalletStatus.Paused, WalletStatus.Offline)) { + walletState.update { it.copy(status = WalletStatus.Ready) } + var isReadEnded = false + read = { + try { + awaitCancellation() + } finally { + isReadEnded = true + } + } + val result = async { sut.sync(isForced = true) } + assertFalse(result.isCompleted) + + walletState.update { it.copy(status = status) } + + assertIs(result.await().exceptionOrNull(), "$status") + assertTrue(isReadEnded, "$status") + } + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a read that fails changes nothing`() = test { + read = { throw IOException("offline") } + + assertIs(sut.sync().exceptionOrNull()) + + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a read that takes too long is given up and changes nothing`() = test { + var isReadEnded = false + read = { + try { + awaitCancellation() + } finally { + isReadEnded = true + } + } + + val result = async { sut.sync() } + testScheduler.advanceTimeBy(SettingsSyncRepo.READ_TIMEOUT.inWholeMilliseconds + 1) + + assertIs(result.await().exceptionOrNull()) + assertTrue(isReadEnded) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a read that blocks its thread holds back neither the import nor its caller`() { + val isReading = CountDownLatch(1) + val release = CountDownLatch(1) + val isReadEnded = CountDownLatch(1) + val blocking = SettingsSyncRepo( + Dispatchers.IO, + seedStore, + { _, _ -> + isReading.countDown() + release.await() + isReadEnded.countDown() + BACKUP + }, + settingsStore, + sparkService, + walletRepo, + { elapsedMs }, + { NOW }, + ) + try { + runBlocking { + val result = async(Dispatchers.Default) { blocking.sync() } + assertTrue(isReading.await(WAIT_SECS, TimeUnit.SECONDS)) + + // The wallet stops being ready: the import answers though the read is stuck. + walletState.update { it.copy(status = WalletStatus.Locked) } + val failure = withTimeout(WAIT_SECS.seconds) { result.await() }.exceptionOrNull() + assertIs(failure) + + // So does a caller that stops waiting, as a payment does after its 5 s. + walletState.update { it.copy(status = WalletStatus.Ready) } + val waited = withTimeout(WAIT_SECS.seconds) { withTimeoutOrNull(50) { blocking.sync(isForced = true) } } + assertNull(waited) + } + } finally { + release.countDown() + } + // The second import was only left waiting, so it lands once its read ends. + assertTrue(isReadEnded.await(WAIT_SECS, TimeUnit.SECONDS)) + runBlocking { verify(settingsStore, timeout(WAIT_SECS * 1_000)).applyPhoneSettings(SETTINGS, NOW) } + } + + @Test + fun `nothing is read unless the wallet is ready`() = test { + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertIs(sut.sync().exceptionOrNull(), "$status") + } + + assertTrue(reads.isEmpty()) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `nothing is read during a wipe or without a seed`() = test { + whenever(sparkService.wipeToken()).thenReturn(null) + assertIs(sut.sync().exceptionOrNull()) + + whenever(sparkService.wipeToken()).thenReturn(TOKEN) + seedStore.seed = null + assertIs(sut.sync().exceptionOrNull()) + + assertTrue(reads.isEmpty()) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `an import that a wipe overtook is taken out again`() = test { + val gate = CompletableDeferred() + read = { + gate.await() + BACKUP + } + val result = async { sut.sync() } + + whenever(sparkService.isCurrent(TOKEN)).thenReturn(false) + gate.complete(Unit) + + assertIs(result.await().exceptionOrNull()) + val order = inOrder(settingsStore) + order.verify(settingsStore).applyPhoneSettings(any(), any()) + order.verify(settingsStore).clearPhoneSettings() + } + + @Test + fun `an import whose caller stopped waiting still lands, and the next call finds it`() = test { + val gate = CompletableDeferred() + read = { + gate.await() + BACKUP + } + + val result = async { sut.sync() } + result.cancel() + verifyNoMoreInteractions(settingsStore) + val next = async { sut.sync() } + gate.complete(Unit) + + assertTrue(next.await().isSuccess) + assertEquals(1, reads.size) + verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) + verifyNoMoreInteractions(settingsStore) + } + + @Test + fun `a caller that goes away after the read still gets the outcome written whole`() = test { + val stored = CompletableDeferred() + whenever(settingsStore.applyPhoneSettings(any(), any())).doSuspendableAnswer { stored.await() } + val result = async { sut.sync() } + + // A wipe overtakes the import while it is stored, and the caller leaves. + whenever(sparkService.isCurrent(TOKEN)).thenReturn(false) + result.cancel() + stored.complete(Unit) + + val order = inOrder(settingsStore) + order.verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) + order.verify(settingsStore).clearPhoneSettings() + } +} diff --git a/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt b/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt new file mode 100644 index 0000000000..21a1d8f160 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt @@ -0,0 +1,67 @@ +package to.bitkit.wear.services + +import org.junit.Test +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The watch must never write to VSS. That is kept by structure, which these tests pin: the reader's interface has + * one call, a read, and the only source file that names the VSS library imports nothing of it that writes. + */ +class PhoneBackupReaderTest { + private companion object { + const val VSS_PACKAGE = "com.synonym.vssclient" + const val READER_FILE = "PhoneBackupReader.kt" + + /** + * Everything of vss-client the watch may name: the calls that derive the store id, sign in, read one object + * and shut down, and the library's error type, which calls nothing. + */ + val ALLOWED_IMPORTS = setOf( + "$VSS_PACKAGE.VssException", + "$VSS_PACKAGE.vssDeriveStoreId", + "$VSS_PACKAGE.vssGet", + "$VSS_PACKAGE.vssNewClientWithLnurlAuth", + "$VSS_PACKAGE.vssShutdownClient", + ) + } + + private val sources: List by lazy { + val module = generateSequence(File("").absoluteFile) { it.parentFile } + .map { if (it.name == "wear") it else File(it, "wear") } + .first { File(it, "src/main/java").isDirectory } + File(module, "src/main").walkTopDown().filter { it.isFile && it.extension in setOf("kt", "java") }.toList() + } + + @Test + fun `the reader can only read`() { + assertEquals(listOf("read"), PhoneBackupReader::class.java.declaredMethods.map { it.name }) + } + + @Test + fun `only the reader's file names the vss library`() { + val naming = sources.filter { VSS_PACKAGE in it.readText() }.map { it.name } + + assertEquals(listOf(READER_FILE), naming) + } + + @Test + fun `the reader imports only the error type and the calls that derive, sign in, read and shut down`() { + val reader = sources.single { it.name == READER_FILE }.readText() + val imports = reader.lines().filter { it.startsWith("import $VSS_PACKAGE") }.map { it.removePrefix("import ") } + + assertEquals(ALLOWED_IMPORTS, imports.toSet()) + // Named only through its imports: no wildcard, no alias and no fully qualified call slips past them. + assertEquals(ALLOWED_IMPORTS.size, Regex(Regex.escape(VSS_PACKAGE)).findAll(reader).count()) + assertTrue(imports.none { it.endsWith("*") || " as " in it }) + } + + @Test + fun `no source of the watch app names a vss call that writes, deletes or lists`() { + val writes = Regex("\\bvss(Store|Delete|Put\\w*|Ldk\\w*|NewLdk\\w*|NewClient|List\\w*)\\b") + val offenders = sources.filter { writes.containsMatchIn(it.readText()) }.map { it.name } + + assertEquals(emptyList(), offenders) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt index 206a2edf85..f4afd14b6a 100644 --- a/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt +++ b/wear/src/test/java/to/bitkit/wear/tile/TileStateTest.kt @@ -1,6 +1,8 @@ package to.bitkit.wear.tile import org.junit.Test +import to.bitkit.wear.models.BitcoinDisplayUnit.CLASSIC +import to.bitkit.wear.models.BitcoinDisplayUnit.MODERN import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus import to.bitkit.wear.ui.screens.home.DisplayAmount @@ -10,7 +12,9 @@ import kotlin.test.assertEquals class TileStateTest { @Test fun `without a wallet the tile only opens the app`() { - assertEquals(TileState.SignedOut, tileState(hasWallet = false, WalletState(WalletStatus.Idle), Locale.US)) + val wallet = WalletState(WalletStatus.Idle) + + assertEquals(TileState.SignedOut, tileState(hasWallet = false, wallet, MODERN, Locale.US)) } @Test @@ -19,21 +23,31 @@ class TileStateTest { assertEquals( TileState.SignedOut, - tileState(hasWallet = true, synced.copy(status = WalletStatus.Missing), Locale.US), + tileState(hasWallet = true, synced.copy(status = WalletStatus.Missing), MODERN, Locale.US), ) assertEquals( TileState.SignedOut, - tileState(hasWallet = true, synced.copy(status = WalletStatus.Removed), Locale.US), + tileState(hasWallet = true, synced.copy(status = WalletStatus.Removed), MODERN, Locale.US), ) } @Test - fun `a synced balance shows in bitcoin`() { + fun `a synced balance shows in bitcoin in the modern unit`() { val wallet = WalletState(WalletStatus.Ready, balanceSats = 125_000uL, hasSynced = true) assertEquals( TileState.Wallet(DisplayAmount("₿", "125 000")), - tileState(hasWallet = true, wallet, Locale.US), + tileState(hasWallet = true, wallet, MODERN, Locale.US), + ) + } + + @Test + fun `a synced balance shows in bitcoin in the classic unit`() { + val wallet = WalletState(WalletStatus.Ready, balanceSats = 125_000uL, hasSynced = true) + + assertEquals( + TileState.Wallet(DisplayAmount("₿", "0.00125000")), + tileState(hasWallet = true, wallet, CLASSIC, Locale.US), ) } @@ -43,9 +57,9 @@ class TileStateTest { val unsynced = WalletState(WalletStatus.Connecting, balanceSats = 0uL, hasSynced = false) val failed = WalletState(WalletStatus.Error, balanceSats = 5_000uL, hasSynced = false) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, notLoaded, Locale.US)) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, unsynced, Locale.US)) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, failed, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, notLoaded, MODERN, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, unsynced, MODERN, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, failed, MODERN, Locale.US)) } @Test @@ -53,14 +67,16 @@ class TileStateTest { val paused = WalletState(WalletStatus.Paused, balanceSats = 1_000uL, hasSynced = true) val offline = paused.copy(status = WalletStatus.Offline) - assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tileState(hasWallet = true, paused, Locale.US)) - assertEquals(TileState.Wallet(DisplayAmount("₿", "1 000")), tileState(hasWallet = true, offline, Locale.US)) + val shown = TileState.Wallet(DisplayAmount("₿", "1 000")) + + assertEquals(shown, tileState(hasWallet = true, paused, MODERN, Locale.US)) + assertEquals(shown, tileState(hasWallet = true, offline, MODERN, Locale.US)) } @Test fun `a locked watch hides the balance`() { val locked = WalletState(WalletStatus.Locked, balanceSats = 1_000uL, hasSynced = true) - assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, locked, Locale.US)) + assertEquals(TileState.Wallet(balance = null), tileState(hasWallet = true, locked, MODERN, Locale.US)) } } diff --git a/wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt b/wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt new file mode 100644 index 0000000000..3ac3ce4f8e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt @@ -0,0 +1,20 @@ +package to.bitkit.wear.ui + +import android.content.Intent +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ReplayedLaunchTest { + @Test + fun `a link opened again from recents is a replay, whatever else its flags say`() { + assertTrue(isReplayedLaunch(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)) + assertTrue(isReplayedLaunch(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY or Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + @Test + fun `a link that arrives now is not a replay`() { + assertFalse(isReplayedLaunch(0)) + assertFalse(isReplayedLaunch(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt index 07137e4e35..b1bdb1dfc7 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityViewModelTest.kt @@ -2,14 +2,18 @@ package to.bitkit.wear.ui.screens.activity import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.update import org.junit.Before import org.junit.Test +import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.WatchPayment import to.bitkit.wear.repositories.PaymentsRepo @@ -25,6 +29,7 @@ import kotlin.test.assertTrue class ActivityViewModelTest : BaseUnitTest() { private val paymentsRepo = mock() private val walletRepo = mock() + private val settingsStore = mock { on { data } doReturn flowOf(WatchSettings()) } private val walletState = MutableStateFlow(WalletState(WalletStatus.Connecting)) private val paymentChanges = MutableSharedFlow() @@ -34,7 +39,7 @@ class ActivityViewModelTest : BaseUnitTest() { whenever(paymentsRepo.paymentChanges).thenReturn(paymentChanges) } - private fun createSut() = ActivityViewModel(paymentsRepo, walletRepo) { NOW } + private fun createSut() = ActivityViewModel(paymentsRepo, walletRepo, settingsStore) { NOW } @Test fun `the list is read once spark is connected`() = test { diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt index 8a5eb0d6e5..5b91c1a21f 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/home/HomeViewModelTest.kt @@ -10,12 +10,15 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.AmbientMonitor import to.bitkit.wear.data.NfcState import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.FxRate import to.bitkit.wear.models.rate import to.bitkit.wear.repositories.CurrencyRepo +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WalletState import to.bitkit.wear.repositories.WalletStatus @@ -24,6 +27,7 @@ import to.bitkit.wear.security.FakeNetworkMonitor import to.bitkit.wear.security.FakeNfcMonitor import to.bitkit.wear.security.SeedStoreError import to.bitkit.wear.test.BaseUnitTest +import java.util.Locale import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -38,6 +42,8 @@ class HomeViewModelTest : BaseUnitTest() { private val nfcMonitor = FakeNfcMonitor() private val networkMonitor = FakeNetworkMonitor() private val foregroundMonitor = FakeForegroundMonitor() + private val settingsSyncRepo = mock() + private val ambientMonitor = AmbientMonitor() private lateinit var sut: HomeViewModel @@ -49,7 +55,17 @@ class HomeViewModelTest : BaseUnitTest() { whenever { walletRepo.start() }.thenReturn(Result.success(Unit)) whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) whenever { currencyRepo.togglePrimaryDisplay() }.thenReturn(Result.success(Unit)) - sut = HomeViewModel(walletRepo, currencyRepo, settingsStore, nfcMonitor, networkMonitor, foregroundMonitor) + whenever { settingsSyncRepo.sync() }.thenReturn(Result.success(Unit)) + sut = HomeViewModel( + walletRepo, + currencyRepo, + settingsStore, + nfcMonitor, + networkMonitor, + foregroundMonitor, + settingsSyncRepo, + ambientMonitor, + ) } override fun onTestEnd() = foregroundMonitor.isForeground.update { false } @@ -65,6 +81,60 @@ class HomeViewModelTest : BaseUnitTest() { verify(currencyRepo, times(2)).refresh() } + @Test + fun `the phone's settings are imported when the wallet is ready, on each return and every five minutes`() = test { + verify(settingsSyncRepo, times(1)).sync() + + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL + 1.seconds) + verify(settingsSyncRepo, times(2)).sync() + + foregroundMonitor.isForeground.update { false } + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + verify(settingsSyncRepo, times(2)).sync() + + foregroundMonitor.isForeground.update { true } + verify(settingsSyncRepo, times(3)).sync() + + walletState.update { it.copy(status = WalletStatus.Paused) } + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + verify(settingsSyncRepo, times(3)).sync() + + walletState.update { it.copy(status = WalletStatus.Ready) } + verify(settingsSyncRepo, times(4)).sync() + } + + @Test + fun `the phone's settings are not imported in ambient mode, and again once the watch wakes`() = test { + ambientMonitor.set(true) + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + verify(settingsSyncRepo, times(1)).sync() + + ambientMonitor.set(false) + verify(settingsSyncRepo, times(2)).sync() + } + + @Test + fun `the phone's settings are not imported before the wallet is ready`() = test { + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + } + testScheduler.advanceTimeBy(HomeViewModel.SETTINGS_SYNC_INTERVAL * 3) + + verify(settingsSyncRepo, times(1)).sync() + } + + @Test + fun `the balance is written in the phone's bitcoin unit`() { + val state = homeUiState( + WalletState(WalletStatus.Ready, 50_000uL, hasSynced = true), + rates = emptyList(), + settings = WatchSettings(displayUnit = BitcoinDisplayUnit.CLASSIC), + locale = Locale.US, + ) + + assertEquals(DisplayAmount("₿", "0.00050000"), state.primaryAmount) + } + @Test fun `rates are fetched every five minutes only while the app is on screen`() = test { testScheduler.advanceTimeBy(HomeViewModel.RATES_REFRESH_INTERVAL + 1.seconds) 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 05b09b5cfb..ebf2d0089c 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 @@ -5,16 +5,20 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.update import org.junit.Before import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.ReceiveError import to.bitkit.wear.models.ReceiveInvoice @@ -34,6 +38,7 @@ import kotlin.time.Duration.Companion.seconds class ReceiveViewModelTest : BaseUnitTest() { private val paymentsRepo = mock() private val walletRepo = mock() + private val settingsStore = mock { on { data } doReturn flowOf(WatchSettings()) } private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 0uL, hasSynced = true)) @Before @@ -43,7 +48,7 @@ class ReceiveViewModelTest : BaseUnitTest() { private val created = mutableListOf() - private fun createSut() = ReceiveViewModel(paymentsRepo, walletRepo) { NOW }.also { created += it } + private fun createSut() = ReceiveViewModel(paymentsRepo, walletRepo, settingsStore) { NOW }.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() } 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 0fa916323a..a45733a614 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 @@ -4,6 +4,7 @@ import androidx.lifecycle.SavedStateHandle import app.cash.turbine.test import breez_sdk_spark.PrepareSendPaymentResponse import com.synonym.bitkitcore.LnurlPayData +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf @@ -13,12 +14,16 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.AmbientMonitor import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.FxRate import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.PreparedSend @@ -30,6 +35,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.FakeForegroundMonitor import to.bitkit.wear.test.BaseUnitTest import to.bitkit.wear.ui.Routes import to.bitkit.wear.ui.screens.home.DisplayAmount @@ -46,21 +52,29 @@ class SendViewModelTest : BaseUnitTest() { private val currencyRepo = mock() private val settingsStore = mock() private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, 100_000uL, hasSynced = true)) + private val foregroundMonitor = FakeForegroundMonitor() + private val ambientMonitor = AmbientMonitor() + private var elapsedMs = 1_000_000L @Before fun setUp() { whenever(walletRepo.walletState).thenReturn(walletState) whenever(currencyRepo.rates).thenReturn(MutableStateFlow(emptyList())) whenever(settingsStore.data).thenReturn(flowOf(WatchSettings())) + whenever { paymentsRepo.skipConfirmation(any(), any()) }.thenReturn(false) } - private fun createSut() = SendViewModel( - SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT)), + private fun createSut( + savedState: SavedStateHandle = SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT)), + ) = SendViewModel( + savedState, paymentsRepo, walletRepo, currencyRepo, settingsStore, - ) + foregroundMonitor, + ambientMonitor, + ) { elapsedMs } @Test fun `the input is read only once the wallet is ready`() = test { @@ -116,17 +130,221 @@ class SendViewModelTest : BaseUnitTest() { } @Test - fun `the quickpay hook sends without the hold`() = test { + fun `quickpay sends without the review or the hold and ends on the same result`() = test { val prepared = prepared() stubInvoice(prepared) - whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(true) - whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + val sent = CompletableDeferred>() + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { sent.await() } + + val sut = createSut() + + assertIs(sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + verify(paymentsRepo, times(1)).skipConfirmation(eq(prepared), any()) + + sent.complete(Result.success(payment(PaymentState.Completed))) + + val done = assertIs(sut.uiState.value.step) + assertEquals(SendResult.Sent, done.result) + verify(paymentsRepo, times(1)).send(prepared) + } + + @Test + fun `quickpay still applies to a link that opened the app and waited a moment for the wallet`() = test { + for (status in listOf(WalletStatus.Idle, WalletStatus.Paused, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Connecting) } + elapsedMs += SendViewModel.QUICKPAY_WINDOW.inWholeMilliseconds + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, "$status") + } + } + + @Test + fun `a link that waited long for the wallet is reviewed and held, never paid under quickpay`() = test { + for (status in listOf(WalletStatus.Error, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + elapsedMs += SendViewModel.QUICKPAY_WINDOW.inWholeMilliseconds + 1 + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, "$status") + assertTrue(sut.uiState.value.isHoldEnabled) + } + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a wallet that turns offline while the link waits for it ends on the offline error, without quickpay`() = + test { + for (status in listOf(WalletStatus.Idle, WalletStatus.Paused, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + assertEquals(SendStep.Loading, sut.uiState.value.step, "$status") + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Offline) } + // The network returns well within the QuickPay window: the dropped request stays dropped. + walletState.update { it.copy(status = WalletStatus.Connecting) } + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertEquals(SendStep.Offline, sut.uiState.value.step, "$status") + assertFalse(sut.uiState.value.isHoldEnabled) + sut.onHoldComplete() + } + verify(paymentsRepo, never()).parse(any()) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a wallet that turns offline while quickpay is decided ends on the offline error and sends nothing`() = + test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { + walletState.update { state -> state.copy(status = WalletStatus.Offline) } + it.getArgument<() -> Boolean>(1)() + } + + val sut = createSut() + + assertEquals(SendStep.Offline, sut.uiState.value.step) + walletState.update { it.copy(status = WalletStatus.Ready) } + assertEquals(SendStep.Offline, sut.uiState.value.step) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a flow rebuilt for a link that already had one is reviewed and held, never paid under quickpay`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } + // The first flow ends on the review, as when the watch dimmed, and the wearer leaves without paying. + ambientMonitor.set(true) + val savedState = SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT)) + assertIs(createSut(savedState).uiState.value.step) + ambientMonitor.set(false) + + // The process is killed and the back stack restored: a new flow on what the first one saved. + val restored = SavedStateHandle(savedState.keys().associateWith { savedState.get(it) }) + val sut = createSut(restored) + + assertIs(sut.uiState.value.step) + assertTrue(sut.uiState.value.isHoldEnabled) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) - createSut() + sut.onHoldComplete() verify(paymentsRepo).send(prepared) } + @Test + fun `a link whose wait crossed a lock, a pause or ambient mode is reviewed and held`() = test { + val interruptions = listOf Unit>>( + "lock" to { + walletState.update { it.copy(status = WalletStatus.Locked) } + walletState.update { it.copy(status = WalletStatus.Connecting) } + }, + "pause" to { + foregroundMonitor.isForeground.update { false } + foregroundMonitor.isForeground.update { true } + }, + "wallet pause" to { + walletState.update { it.copy(status = WalletStatus.Paused) } + walletState.update { it.copy(status = WalletStatus.Connecting) } + }, + "ambient" to { + ambientMonitor.set(true) + ambientMonitor.set(false) + }, + ) + for ((name, interrupt) in interruptions) { + walletState.update { it.copy(status = WalletStatus.Connecting) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + interrupt() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, name) + } + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a link that arrives on a locked watch is reviewed and held`() = test { + walletState.update { it.copy(status = WalletStatus.Locked) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) + + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) + } + + @Test + fun `a wearer who looked away while quickpay was decided is asked to hold`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { + ambientMonitor.set(true) + it.getArgument<() -> Boolean>(1)() + } + + val sut = createSut() + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).send(any()) + } + + @Test + fun `a quickpay send that fails shows the failure like any other`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) + whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.Failed())) + + val sut = createSut() + + assertEquals(SendStep.Failed(SendFailure.Failed), sut.uiState.value.step) + } + + @Test + fun `without quickpay the send waits on review, written in the phone's unit`() = test { + whenever(settingsStore.data) + .thenReturn(flowOf(WatchSettings(displayUnit = BitcoinDisplayUnit.CLASSIC))) + val prepared = prepared(amountSats = 21_000uL) + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(false) + + val sut = createSut() + + val step = assertIs(sut.uiState.value.step) + assertEquals("0.00021000", step.amount.text) + verify(paymentsRepo, never()).send(any()) + } + @Test fun `a request that arrives offline ends on the offline error without being read`() = test { walletState.update { it.copy(status = WalletStatus.Offline) } diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt index cc40e995f0..24645030b9 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt @@ -1,25 +1,80 @@ package to.bitkit.wear.ui.screens.settings +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import org.junit.Before import org.junit.Test +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.SettingsStore +import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.repositories.SettingsSyncRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.services.SparkError import to.bitkit.wear.test.BaseUnitTest +import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class SettingsViewModelTest : BaseUnitTest() { private val walletRepo = mock() + private val settingsSyncRepo = mock() + private val settingsStore = mock() + private val settings = MutableStateFlow(WatchSettings()) private lateinit var sut: SettingsViewModel @Before fun setUp() { - sut = SettingsViewModel(walletRepo) + whenever(settingsStore.data).thenReturn(settings) + sut = SettingsViewModel(walletRepo, settingsSyncRepo, settingsStore) + } + + @Test + fun `the row shows when the phone's settings were last imported`() = test { + assertNull(sut.uiState.value.phoneSyncedAtMs) + + settings.update { it.copy(phoneSyncedAtMs = 1_000L) } + + assertEquals(1_000L, sut.uiState.value.phoneSyncedAtMs) + } + + @Test + fun `a tap on the row imports the phone's settings once at a time`() = test { + val gate = CompletableDeferred>() + whenever { settingsSyncRepo.sync(isForced = true) }.doSuspendableAnswer { gate.await() } + + sut.onSyncClick() + sut.onSyncClick() + + assertTrue(sut.uiState.value.isSyncing) + verify(settingsSyncRepo, times(1)).sync(isForced = true) + + gate.complete(Result.success(Unit)) + + assertFalse(sut.uiState.value.isSyncing) + assertFalse(sut.uiState.value.isSyncFailed) + } + + @Test + fun `a tapped import that fails shows the failure until the next tap`() = test { + whenever { settingsSyncRepo.sync(isForced = true) }.thenReturn(Result.failure(SparkError.WipeInProgress())) + + sut.onSyncClick() + + assertTrue(sut.uiState.value.isSyncFailed) + assertFalse(sut.uiState.value.isSyncing) + + whenever { settingsSyncRepo.sync(isForced = true) }.thenReturn(Result.success(Unit)) + sut.onSyncClick() + + assertFalse(sut.uiState.value.isSyncFailed) } @Test diff --git a/wear/src/test/resources/phone-backup-contract.json b/wear/src/test/resources/phone-backup-contract.json new file mode 100644 index 0000000000..e7d438d82d --- /dev/null +++ b/wear/src/test/resources/phone-backup-contract.json @@ -0,0 +1,31 @@ +{ + "settingsKey": "SETTINGS", + "settingsBackup": { + "version": 1, + "settings": { + "primaryDisplay": "FIAT", + "displayUnit": "CLASSIC", + "selectedCurrency": "EUR", + "isQuickPayEnabled": true, + "quickPayAmount": 10, + "quickPayDailyLimitMultiplier": 3 + } + }, + "networks": { + "BITCOIN": { + "storeIdPrefix": "bitkit_v1_bitcoin", + "vssServerUrl": "https://api.bitkit.to/vss_rs_auth", + "lnurlAuthServerUrl": "https://bitkit.to/lnurl_auth/auth" + }, + "TESTNET": { + "storeIdPrefix": "bitkit_v1_testnet", + "vssServerUrl": "https://bitkit.stag0.blocktank.to/vss_rs_auth", + "lnurlAuthServerUrl": "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" + }, + "REGTEST": { + "storeIdPrefix": "bitkit_v1_regtest", + "vssServerUrl": "https://bitkit.stag0.blocktank.to/vss_rs_auth", + "lnurlAuthServerUrl": "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" + } + } +}