From fe8a6887fa91dc8ab3728aa86ec094f8490e2d8f Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 04:51:01 -0300 Subject: [PATCH 01/15] feat: import the phone's settings and quickpay on the watch Co-Authored-By: Claude Fable 5.2 --- wear/build.gradle.kts | 2 + .../to/bitkit/wear/data/QuickPaySpendStore.kt | 43 +++++ .../java/to/bitkit/wear/data/SettingsStore.kt | 87 ++++++++- .../java/to/bitkit/wear/di/SecurityModule.kt | 12 ++ wear/src/main/java/to/bitkit/wear/env/Env.kt | 17 ++ .../java/to/bitkit/wear/models/Currency.kt | 21 ++ .../java/to/bitkit/wear/models/Payments.kt | 5 + .../to/bitkit/wear/models/PhoneSettings.kt | 115 +++++++++++ .../bitkit/wear/repositories/CurrencyRepo.kt | 10 + .../bitkit/wear/repositories/PaymentsRepo.kt | 34 +++- .../bitkit/wear/repositories/QuickPayRepo.kt | 98 ++++++++++ .../wear/repositories/SettingsSyncRepo.kt | 116 +++++++++++ .../bitkit/wear/services/PhoneBackupReader.kt | 50 +++++ .../screens/activity/ActivityDetailScreen.kt | 10 +- .../ui/screens/activity/ActivityScreen.kt | 9 +- .../ui/screens/activity/ActivityViewModel.kt | 13 +- .../wear/ui/screens/home/HomeViewModel.kt | 35 +++- .../ui/screens/receive/ReceiveViewModel.kt | 11 +- .../wear/ui/screens/send/SendViewModel.kt | 14 +- .../ui/screens/settings/SettingsScreen.kt | 43 ++++- .../ui/screens/settings/SettingsViewModel.kt | 27 +++ wear/src/main/res/drawable/ic_sync.xml | 11 ++ wear/src/main/res/values-ar/strings.xml | 1 + wear/src/main/res/values-b+es+419/strings.xml | 1 + wear/src/main/res/values-ca/strings.xml | 1 + wear/src/main/res/values-cs/strings.xml | 1 + wear/src/main/res/values-de/strings.xml | 1 + wear/src/main/res/values-el/strings.xml | 1 + wear/src/main/res/values-es-rES/strings.xml | 1 + wear/src/main/res/values-es/strings.xml | 1 + wear/src/main/res/values-fr/strings.xml | 1 + wear/src/main/res/values-it/strings.xml | 1 + wear/src/main/res/values-nl/strings.xml | 1 + wear/src/main/res/values-pl/strings.xml | 1 + wear/src/main/res/values-pt-rBR/strings.xml | 1 + wear/src/main/res/values-pt/strings.xml | 1 + wear/src/main/res/values-ru/strings.xml | 1 + wear/src/main/res/values/strings.xml | 1 + .../wear/data/QuickPaySpendStoreTest.kt | 124 ++++++++++++ .../to/bitkit/wear/data/SettingsStoreTest.kt | 103 ++++++++++ .../to/bitkit/wear/models/CurrencyTest.kt | 8 + .../wear/models/PhoneSettingsParserTest.kt | 146 ++++++++++++++ .../wear/repositories/PaymentsRepoTest.kt | 84 +++++++- .../wear/repositories/QuickPayRepoTest.kt | 179 +++++++++++++++++ .../wear/repositories/SettingsSyncRepoTest.kt | 180 ++++++++++++++++++ .../wear/services/PhoneBackupReaderTest.kt | 63 ++++++ .../screens/activity/ActivityViewModelTest.kt | 7 +- .../wear/ui/screens/home/HomeViewModelTest.kt | 59 +++++- .../screens/receive/ReceiveViewModelTest.kt | 7 +- .../wear/ui/screens/send/SendViewModelTest.kt | 48 ++++- .../screens/settings/SettingsViewModelTest.kt | 41 +++- 51 files changed, 1810 insertions(+), 38 deletions(-) create mode 100644 wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt create mode 100644 wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt create mode 100644 wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt create mode 100644 wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt create mode 100644 wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt create mode 100644 wear/src/main/res/drawable/ic_sync.xml create mode 100644 wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt create mode 100644 wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt 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/QuickPaySpendStore.kt b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt new file mode 100644 index 0000000000..ed986df92b --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt @@ -0,0 +1,43 @@ +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 whether + * it was added. A day earlier than the one last counted does not start a new count, so setting the watch's date + * back frees nothing. + */ + suspend fun reserve(dayKey: String, cents: Long, capCents: Long): Boolean +} + +/** [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): Boolean { + if (cents <= 0 || capCents <= 0) return false + var isReserved = false + dataStore.edit { prefs -> + val countedDay = prefs[this.dayKey] + val isNewDay = countedDay == null || dayKey > countedDay + val spent = if (isNewDay) 0L else prefs[centsKey] ?: 0L + if (spent < 0 || cents > capCents - spent) return@edit + prefs[this.dayKey] = if (isNewDay) dayKey else requireNotNull(countedDay) + prefs[centsKey] = spent + cents + isReserved = true + } + return isReserved + } +} 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..f63e82792d 100644 --- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt +++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt @@ -20,7 +20,9 @@ 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 +38,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 +88,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" 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..e627dee737 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,23 @@ internal object Env { WalletNetwork.TESTNET -> null } + /** The namespace of this network's backups on VSS, the phone's `Env.vssStoreIdPrefix`. */ + val vssStoreIdPrefix: String get() = "bitkit_v1_${network.name.lowercase()}" + + /** The phone's backup server. The watch only ever reads from it. */ + val vssServerUrl: String + get() = 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. */ + val lnurlAuthServerUrl: String + get() = 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..7a14b0a2c1 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,11 @@ 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 this pays a BOLT11 invoice that carries its amount, the only kind of request QuickPay covers. An + * amount the wearer typed is never fixed, and neither is any LNURL or 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/CurrencyRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt index 254484d59d..f22c85b172 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt @@ -15,6 +15,9 @@ import to.bitkit.wear.models.FxRate import to.bitkit.wear.utils.Logger import javax.inject.Inject import javax.inject.Singleton +import kotlin.time.Duration +import kotlin.time.TimeMark +import kotlin.time.TimeSource @Singleton class CurrencyRepo @Inject constructor( @@ -29,10 +32,17 @@ class CurrencyRepo @Inject constructor( private val _rates = MutableStateFlow>(emptyList()) val rates: StateFlow> = _rates.asStateFlow() + @Volatile + private var ratesFetched: TimeMark? = null + + /** How long ago [rates] were fetched, or null when they never were. */ + fun ratesAge(): Duration? = ratesFetched?.elapsedNow() + suspend fun refresh(): Result = withContext(ioDispatcher) { runSuspendCatching { val tickers = ratesHttpClient.fetchLatestRates().tickers _rates.update { tickers } + ratesFetched = TimeSource.Monotonic.markNow() } } 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..59c5c97936 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -67,6 +67,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" @@ -139,11 +140,25 @@ class PaymentsRepo @Inject constructor( val paymentChanges: Flow get() = sparkService.events.map { } /** - * 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). 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; + * - it pays a BOLT11 invoice that carries its amount: an amount the wearer typed is always reviewed, since the + * review is the one place that shows what was typed, its fee and its payee, and so is every LNURL, Lightning + * address and Spark address payment; + * - [QuickPayRepo.reserve] takes the payment's cost, fee included, under the phone's QuickPay settings. + * + * A yes counts the payment against today's QuickPay limit, so ask once per send and only when about to send. + * 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): Boolean = withContext(ioDispatcher) { + if (!isReady() || sparkService.isWiping) return@withContext false + if (!prepared.isAmountFixed) return@withContext false + val isAllowed = quickPayRepo.reserve(prepared.totalSats) + // The wallet may have locked, paused or been wiped while the limit was read. + isAllowed && isReady() && !sparkService.isWiping + } /** * Creates an amountless BOLT11 invoice paid into the Spark balance, valid for [INVOICE_EXPIRY_SECS], and @@ -272,7 +287,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) @@ -325,6 +347,7 @@ class PaymentsRepo @Inject constructor( payee: String?, exactMsats: ULong? = null, sparkPayee: String? = null, + isAmountFixed: Boolean = false, ): PreparedSend { ensureNotOwn(paymentRequest) val response = runSuspendCatching { @@ -355,6 +378,7 @@ class PaymentsRepo @Inject constructor( expiresAtSecs = invoice?.expiresAt, sparkPayee = sparkPayee.takeIf { invoice == null }, transferKey = UUID.randomUUID().toString(), + isAmountFixed = isAmountFixed, ) } 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..06dc79e7e8 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -0,0 +1,98 @@ +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 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.USD +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.hours +import kotlin.time.Duration.Companion.minutes + +/** + * Decides whether a payment goes out under the phone's QuickPay settings, which the watch imports and never sets. + * Everything that is missing, stale 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 old the last import of the phone's settings may be. A watch that could not read them for longer asks + * for the hold again, so QuickPay turned off on the phone stops on the watch within this time. + */ + val MAX_SETTINGS_AGE = 15.minutes + + /** How old the exchange rates may be for the limit, which is in dollars, to be checked against them. */ + val MAX_RATES_AGE = 1.hours + } + + @Inject + constructor( + @IoDispatcher ioDispatcher: CoroutineDispatcher, + settingsStore: SettingsStore, + currencyRepo: CurrencyRepo, + spendStore: QuickPaySpendStore, + ) : this(ioDispatcher, settingsStore, currencyRepo, spendStore, System::currentTimeMillis, ZoneId::systemDefault) + + private val mutex = Mutex() + + /** + * Whether a payment that costs [totalSats], its fee included, may skip the hold to pay, and if so counts it + * against today's limit. It may when QuickPay was imported from the phone within [MAX_SETTINGS_AGE] and is on, + * a dollar rate no older than [MAX_RATES_AGE] values the payment at no more than the phone's QuickPay amount, and + * today's QuickPay payments from this watch stay within the phone's daily limit with it. A yes is counted + * whether or not the payment then succeeds. Any failure to read or count answers no. + */ + suspend fun reserve(totalSats: ULong): Boolean = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { reserveLocked(totalSats) } } + .onFailure { Logger.warn("Failed to check QuickPay", it, context = TAG) } + .getOrDefault(false) + } + + private suspend fun reserveLocked(totalSats: ULong): Boolean { + val settings = settingsStore.data.first() + val quickPay = settings.quickPay?.takeIf { it.isEnabled } ?: return false + val now = nowMs() + val settingsAge = now - (settings.phoneSyncedAtMs ?: return false) + if (settingsAge < 0 || settingsAge > MAX_SETTINGS_AGE.inWholeMilliseconds) return false + val ratesAge = currencyRepo.ratesAge() ?: return false + if (ratesAge > MAX_RATES_AGE) return false + val rate = currencyRepo.rates.value.rateFor(USD)?.lastPrice?.toBigDecimalOrNull() ?: return false + val cents = usdCents(totalSats, rate) ?: return false + if (cents > quickPay.thresholdCents) return false + val dayKey = Instant.ofEpochMilli(now).atZone(zone()).toLocalDate().toString() + return spendStore.reserve(dayKey, cents, quickPay.dailyCapCents) + } + + /** [sats] at [usdPerBtc] in US cents, rounded up so a payment never counts for less than it is worth. */ + private fun usdCents(sats: ULong, usdPerBtc: BigDecimal): Long? { + if (sats == 0uL || sats > Long.MAX_VALUE.toULong() || usdPerBtc.signum() <= 0) return null + val cents = BigDecimal.valueOf(sats.toLong()) + .multiply(usdPerBtc) + .movePointLeft(BTC_SCALE - CENTS_SCALE) + .setScale(0, RoundingMode.CEILING) + return runCatching { cents.longValueExact() }.getOrNull() + } +} 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..3491343f02 --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt @@ -0,0 +1,116 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +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.services.PhoneBackupReader +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.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 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 signing in to VSS and reading the backup may take. */ + val READ_TIMEOUT = 30.seconds + } + + @Inject + constructor( + @IoDispatcher ioDispatcher: CoroutineDispatcher, + seedStore: SeedStore, + backupReader: PhoneBackupReader, + settingsStore: SettingsStore, + sparkService: WatchSparkService, + walletRepo: WalletRepo, + ) : this( + ioDispatcher, + seedStore, + backupReader, + settingsStore, + sparkService, + walletRepo, + System::currentTimeMillis, + ) + + private val mutex = Mutex() + + /** + * Reads the phone's settings backup and adopts it, for a wallet that is ready. A backup that is missing, cannot + * be 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 then stops by itself once the last import is too old + * ([QuickPayRepo.MAX_SETTINGS_AGE]). An import that a wallet wipe overtook is taken out again, so nothing of a + * removed wallet's settings stays. + */ + suspend fun sync(): Result = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { syncLocked() } } + .onFailure { Logger.warn("Failed to import the phone's settings", it, context = TAG) } + } + + private suspend fun syncLocked() { + val wipeToken = sparkService.wipeToken() ?: throw SparkError.WipeInProgress() + if (walletRepo.walletState.value.status != WalletStatus.Ready) throw SettingsSyncError.NotReady() + val seed = seedStore.load().getOrThrow() + val backup = withTimeoutOrNull(READ_TIMEOUT) { Result.success(backupReader.read(seed, SETTINGS_KEY)) } + ?: throw SettingsSyncError.Timeout() + // From here the outcome is written whole, also when the caller goes away. + withContext(NonCancellable) { + val bytes = backup.getOrThrow() + val parsed = bytes?.let { runCatching { PhoneSettingsParser.parse(it) } } + when { + parsed == null -> { + Logger.info("Found no settings backup of the phone", context = TAG) + settingsStore.clearQuickPay() + } + parsed.isFailure -> { + Logger.warn("Failed to read the phone's settings backup", parsed.exceptionOrNull(), context = TAG) + settingsStore.clearQuickPay() + } + else -> { + settingsStore.applyPhoneSettings(parsed.getOrThrow(), nowMs()) + Logger.info("Imported the phone's settings", context = TAG) + } + } + if (!sparkService.isCurrent(wipeToken)) { + settingsStore.clearPhoneSettings() + throw SparkError.WipeInProgress() + } + } + } +} + +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..afcd96e16f --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt @@ -0,0 +1,50 @@ +package to.bitkit.wear.services + +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.security.WalletSeed +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. */ + suspend fun read(seed: WalletSeed, key: String): ByteArray? +} + +/** + * [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 imported above; `PhoneBackupReaderTest` checks both. 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. + */ +@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, + ) + vssGet(key)?.value + } finally { + withContext(NonCancellable) { runCatching { vssShutdownClient() } } + } + } +} 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..ba954f9883 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 = 1) }, 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..c45dfff195 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 @@ -22,13 +22,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 +44,8 @@ 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, so at every start and return, and every [SETTINGS_SYNC_INTERVAL] from then. */ @HiltViewModel class HomeViewModel @Inject constructor( @@ -52,6 +55,7 @@ class HomeViewModel @Inject constructor( nfcMonitor: NfcMonitor, networkMonitor: NetworkMonitor, foregroundMonitor: ForegroundMonitor, + private val settingsSyncRepo: SettingsSyncRepo, ) : ViewModel() { companion object { private const val TAG = "HomeViewModel" @@ -61,6 +65,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 on screen. */ + val SETTINGS_SYNC_INTERVAL = 5.minutes } val uiState: StateFlow = combine( @@ -90,6 +97,19 @@ class HomeViewModel @Inject constructor( .drop(1) .collect { isReady -> if (isReady) fetchRates() } } + viewModelScope.launch { + combine( + foregroundMonitor.isForeground, + walletRepo.walletState.map { it.status == WalletStatus.Ready }, + ) { isForeground, isReady -> isForeground && isReady } + .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 +153,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 +170,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/SendViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt index fdc6a2080a..0d9a7b4ca6 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 @@ -19,6 +19,8 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch 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.models.PaymentState import to.bitkit.wear.models.PreparedSend import to.bitkit.wear.models.SendError @@ -38,7 +40,8 @@ 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. */ @@ -79,6 +82,7 @@ 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 @@ -170,7 +174,9 @@ class SendViewModel @Inject constructor( } if (_uiState.value.step is SendStep.Offline) return prepared = result + unit = runSuspendCatching { settingsStore.data.first().displayUnit }.getOrDefault(BitcoinDisplayUnit.MODERN) if (paymentsRepo.skipConfirmation(result)) { + Logger.info("Skipped the hold to pay under QuickPay", context = TAG) send(result) return } @@ -182,9 +188,9 @@ class SendViewModel @Inject constructor( 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 +229,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..bf7defebc8 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 java.time.Instant @Composable fun SettingsScreen( @@ -41,6 +43,7 @@ fun SettingsScreen( Content( uiState = uiState, onAboutClick = onAboutClick, + onSyncClick = viewModel::onSyncClick, onRemoveClick = viewModel::onRemoveClick, onRemoveConfirm = viewModel::onRemoveConfirm, onRemoveDismiss = viewModel::onRemoveDismiss, @@ -52,6 +55,7 @@ fun SettingsScreen( private fun Content( uiState: SettingsUiState, onAboutClick: () -> Unit, + onSyncClick: () -> Unit, onRemoveClick: () -> Unit, onRemoveConfirm: () -> Unit, onRemoveDismiss: () -> Unit, @@ -79,6 +83,28 @@ 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), maxLines = 1) }, + secondaryLabel = uiState.phoneSyncedAtMs?.let { syncedAtMs -> + { + Text( + text = syncedAgo(syncedAtMs), + maxLines = 1, + modifier = Modifier.testTag("WatchSettingsSyncTime") + ) + } + }, + transformation = SurfaceTransformation(spec), + modifier = Modifier + .fillMaxWidth() + .transformedHeight(this, spec) + .testTag("WatchSettingsSync") + ) + } item { FilledTonalButton( onClick = onRemoveClick, @@ -111,7 +137,7 @@ private fun Content( } } } - if (uiState.isRemoving) BezelLoading() + if (uiState.isRemoving || uiState.isSyncing) BezelLoading() } AlertDialog( visible = uiState.isRemoveDialogVisible, @@ -133,6 +159,17 @@ private fun Content( ) } +/** How long ago the phone's settings were imported; a time ahead of the watch's clock counts as now. */ +private fun syncedAgo(syncedAtMs: Long): String { + val now = Instant.now().toEpochMilli() + return DateUtils.getRelativeTimeSpanString( + syncedAtMs.coerceAtMost(now), + now, + DateUtils.MINUTE_IN_MILLIS, + DateUtils.FORMAT_ABBREV_RELATIVE, + ).toString() +} + @Composable private fun RowIcon( @DrawableRes id: Int, @@ -146,8 +183,9 @@ private fun RowIcon( private fun Preview() { WearPreview { Content( - uiState = SettingsUiState(), + uiState = SettingsUiState(phoneSyncedAtMs = 0), onAboutClick = {}, + onSyncClick = {}, onRemoveClick = {}, onRemoveConfirm = {}, onRemoveDismiss = {}, @@ -162,6 +200,7 @@ private fun PreviewRemoveConfirm() { Content( uiState = SettingsUiState(isRemoveDialogVisible = true), 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..a93ebfc66e 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,42 @@ 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. */ + fun onSyncClick() { + if (_uiState.value.isSyncing) return + _uiState.update { it.copy(isSyncing = true) } + viewModelScope.launch { + settingsSyncRepo.sync() + _uiState.update { it.copy(isSyncing = false) } + } + } + fun onRemoveClick() { _uiState.update { it.copy(isRemoveDialogVisible = true, isRemoveFailed = false) } } @@ -46,4 +70,7 @@ data class SettingsUiState( val isRemoveDialogVisible: Boolean = false, val isRemoving: Boolean = false, val isRemoveFailed: Boolean = false, + val isSyncing: 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..5816f4e760 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -68,6 +68,7 @@ تم الإرسال تحقق من النشاط في انتظار الشبكة + إعدادات الهاتف إزالة المحفظة إزالة المحفظة؟ تعذّرت إزالة المحفظة 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..f9629e62c8 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,7 @@ Enviado Revisa la actividad Esperando la red + Ajustes del teléfono 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..de41b266bd 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -65,6 +65,7 @@ Enviat Revisa l\'activitat Esperant la xarxa + Configuracions del telèfon 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..ab739285ed 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -66,6 +66,7 @@ Odesláno Zkontrolujte aktivitu Čekání na síť + Nastavení telefonu 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..94b54c8dc8 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -64,6 +64,7 @@ Gesendet Aktivität prüfen Warte auf Netzwerk + Telefon-Einstellungen 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..c864ecada6 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -64,6 +64,7 @@ Στάλθηκε Δες τη δραστηριότητα Αναμονή για δίκτυο + Ρυθμίσεις τηλεφώνου Αφαίρεση πορτοφολιού Αφαίρεση πορτοφολιού; Αδυναμία αφαίρεσης πορτοφολιού diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index d5d8892c48..ad42c21745 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -65,6 +65,7 @@ Enviado Revisa la actividad Esperando a la red + Ajustes del teléfono 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..ad42c21745 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -65,6 +65,7 @@ Enviado Revisa la actividad Esperando a la red + Ajustes del teléfono 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..611c799eb1 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -65,6 +65,7 @@ Envoyé Voir l\'activité En attente du réseau + Paramètres du téléphone 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..41e7bc0ad6 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -65,6 +65,7 @@ Inviato Controlla l\'attività In attesa della rete + Impostazioni telefono 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..65d18b2dfd 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -64,6 +64,7 @@ Verzonden Bekijk activiteit Wachten op netwerk + Telefooninstellingen 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..fb9cb35e88 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -66,6 +66,7 @@ Wysłano Sprawdź aktywność Czekam na sieć + Ustawienia telefonu 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..a1a21bf1ac 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -65,6 +65,7 @@ Enviado Veja a atividade Aguardando a rede + Ajustes do celular 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..fa29a9787f 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -65,6 +65,7 @@ Enviado Veja a atividade À espera da rede + Ajustes do telemóvel 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..7b859246a5 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -66,6 +66,7 @@ Отправлено Проверьте активность Ожидание сети + Настройки телефона Удалить кошелёк Удалить кошелёк? Не удалось удалить кошелёк diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index b42d4c16ae..d23c0050dc 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -64,6 +64,7 @@ Sent Check activity Waiting for network + Phone settings 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..cf9459d7c1 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt @@ -0,0 +1,124 @@ +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.assertFalse +import kotlin.test.assertTrue + +/** 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): Boolean { + failure?.let { throw it } + if (cents <= 0 || capCents <= 0) return false + val isNewDay = day.let { it == null || dayKey > it } + val spent = if (isNewDay) 0L else spentCents + if (cents > capCents - spent) return false + if (isNewDay) day = dayKey + spentCents = spent + cents + return true + } +} + +/** 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 + assertTrue(sut.reserve(TODAY, cents = 400, capCents = 1_000)) + assertTrue(sut.reserve(TODAY, cents = 500, capCents = 1_000)) + close() + val next = open().first + + assertFalse(next.reserve(TODAY, cents = 101, capCents = 1_000)) + assertTrue(next.reserve(TODAY, cents = 100, capCents = 1_000)) + assertFalse(next.reserve(TODAY, cents = 1, capCents = 1_000)) + close() + } + + @Test + fun `a refused payment counts for nothing`() = test { + val sut = open().first + + assertFalse(sut.reserve(TODAY, cents = 1_001, capCents = 1_000)) + + assertTrue(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 + assertTrue(sut.reserve(TOMORROW, cents = 1_000, capCents = 1_000)) + + assertFalse(sut.reserve(TODAY, cents = 1, capCents = 1_000)) + assertFalse(sut.reserve(TOMORROW, cents = 1, capCents = 1_000)) + + assertTrue(sut.reserve("2026-11-30", cents = 1_000, capCents = 1_000)) + close() + } + + @Test + fun `a lowered cap counts what was already spent`() = test { + val sut = open().first + assertTrue(sut.reserve(TODAY, cents = 800, capCents = 1_000)) + + assertFalse(sut.reserve(TODAY, cents = 1, capCents = 500)) + close() + } + + @Test + fun `nothing and less than nothing are refused`() = test { + val sut = open().first + + assertFalse(sut.reserve(TODAY, cents = 0, capCents = 1_000)) + assertFalse(sut.reserve(TODAY, cents = -5, capCents = 1_000)) + assertFalse(sut.reserve(TODAY, cents = 1, capCents = 0)) + assertFalse(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() + assertTrue(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + + settings.finishWipe() + + assertTrue(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/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..90099aff18 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -29,6 +29,7 @@ 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.FakeOwnInvoiceStore @@ -79,6 +80,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 +103,7 @@ class PaymentsRepoTest : BaseUnitTest() { WalletSelfSendGuard(sparkService, ownInvoices), ownInvoices, uncertainSends, + quickPayRepo, ) } @@ -114,6 +117,7 @@ class PaymentsRepoTest : BaseUnitTest() { WalletSelfSendGuard(sparkService, ownInvoices), ownInvoices, uncertainSends, + quickPayRepo, ) } @@ -538,10 +542,88 @@ class PaymentsRepoTest : BaseUnitTest() { } @Test - fun `quickpay never skips the confirmation yet`() = test { + fun `quickpay skips the hold for an invoice with an amount, at its cost with the fee`() = test { + whenever(quickPayRepo.reserve(500uL + FEE)).thenReturn(true) + + assertTrue(sut.skipConfirmation(preparedSend())) + + verify(quickPayRepo, times(1)).reserve(any()) + } + + @Test + fun `quickpay holds when the limits say no`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(false) + assertFalse(sut.skipConfirmation(preparedSend())) } + @Test + fun `quickpay never skips the hold for an amount the wearer typed`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(true) + val amountless = sut.prepare(SendRequest.Invoice(BOLT11, null, null), amountSats = 500uL).getOrThrow() + + assertFalse(sut.skipConfirmation(amountless)) + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold for a spark address or an lnurl payment`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(true) + 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() + val fixed = SendRequest.Lnurl(lnurl(), minSats = 15uL, maxSats = 15uL, payee = null) + 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)) + val lnurl = sut.prepare(fixed).getOrThrow() + + assertFalse(sut.skipConfirmation(transfer)) + assertFalse(sut.skipConfirmation(lnurl)) + + verify(quickPayRepo, never()).reserve(any()) + } + + @Test + fun `quickpay never skips the hold unless the wallet is ready`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(true) + val prepared = preparedSend() + for (status in WalletStatus.entries - WalletStatus.Ready) { + walletState.update { it.copy(status = status) } + + assertFalse(sut.skipConfirmation(prepared), "$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)) + verify(quickPayRepo, never()).reserve(any()) + + whenever(sparkService.isWiping).thenReturn(false) + whenever(quickPayRepo.reserve(any())).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Locked) } + true + } + assertFalse(sut.skipConfirmation(prepared)) + } + + @Test + fun `a request the checks refuse never reaches quickpay`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(true) + ownInvoices.add(PAYMENT_HASH, SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY) + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + + verify(quickPayRepo, never()).reserve(any()) + } + // endregion // region send 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..83dc4b447e --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -0,0 +1,179 @@ +package to.bitkit.wear.repositories + +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.mock +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.assertTrue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds +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. */ +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 val settings = MutableStateFlow(WatchSettings(quickPay = LIMITS, phoneSyncedAtMs = NOW)) + private val rates = MutableStateFlow(listOf(rate("100000"), rate("90000", quote = "EUR"))) + private var now = NOW + private var ratesAge: Duration? = 1.minutes + + private lateinit var sut: QuickPayRepo + + @Before + fun setUp() { + whenever(settingsStore.data).thenReturn(settings) + whenever(currencyRepo.rates).thenReturn(rates) + whenever(currencyRepo.ratesAge()).thenAnswer { ratesAge } + sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, { now }, { ZoneId.of("UTC") }) + } + + @Test + fun `a payment of exactly the phone's amount skips the hold and one sat more does not`() = test { + assertFalse(sut.reserve(FIVE_DOLLARS + 1uL)) + assertEquals(0L, spend.spentCents) + + assertTrue(sut.reserve(FIVE_DOLLARS)) + assertEquals(500L, spend.spentCents) + } + + @Test + fun `the smallest payment skips the hold and counts as a whole cent`() = test { + assertTrue(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() } + + assertFalse(sut.reserve(1uL)) + assertFalse(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)) } + + assertFalse(sut.reserve(1uL)) + } + + @Test + fun `limits without the time of their import skip nothing`() = test { + settings.update { it.copy(phoneSyncedAtMs = null) } + + assertFalse(sut.reserve(1uL)) + } + + @Test + fun `an import older than fifteen minutes, or from the future, skips nothing`() = test { + now = NOW + QuickPayRepo.MAX_SETTINGS_AGE.inWholeMilliseconds + assertTrue(sut.reserve(1uL)) + + now += 1 + assertFalse(sut.reserve(1uL)) + + now = NOW - 1 + assertFalse(sut.reserve(1uL)) + } + + @Test + fun `without a fresh dollar rate nothing skips the hold`() = test { + ratesAge = null + assertFalse(sut.reserve(1uL)) + + ratesAge = QuickPayRepo.MAX_RATES_AGE + 1.milliseconds + assertFalse(sut.reserve(1uL)) + + ratesAge = QuickPayRepo.MAX_RATES_AGE + rates.update { listOf(rate("90000", quote = "EUR")) } + assertFalse(sut.reserve(1uL)) + + for (price in listOf("n/a", "0", "-100000", "")) { + rates.update { listOf(rate(price)) } + assertFalse(sut.reserve(1uL), price) + } + assertEquals(0L, spend.spentCents) + + rates.update { listOf(rate("100000")) } + assertTrue(sut.reserve(1uL)) + } + + @Test + fun `the limit follows the rate, not the sats`() = test { + rates.update { listOf(rate("200000")) } + + assertFalse(sut.reserve(2_501uL)) + assertTrue(sut.reserve(2_500uL)) + } + + @Test + fun `no amount and an absurd amount skip nothing`() = test { + assertFalse(sut.reserve(0uL)) + assertFalse(sut.reserve(ULong.MAX_VALUE)) + assertFalse(sut.reserve(Long.MAX_VALUE.toULong())) + } + + @Test + fun `the day's payments stop at the phone's daily limit`() = test { + repeat(3) { assertTrue(sut.reserve(FIVE_DOLLARS), "payment $it") } + + assertFalse(sut.reserve(1uL)) + assertEquals(1_500L, spend.spentCents) + } + + @Test + fun `a payment that would pass the daily limit is refused whole`() = test { + assertTrue(sut.reserve(FIVE_DOLLARS)) + assertTrue(sut.reserve(FIVE_DOLLARS)) + assertTrue(sut.reserve(4_000uL)) + + assertFalse(sut.reserve(1_001uL)) + assertTrue(sut.reserve(1_000uL)) + } + + @Test + fun `the next day starts a new count, read in the watch's time zone`() = test { + repeat(3) { sut.reserve(FIVE_DOLLARS) } + assertFalse(sut.reserve(1uL)) + + now = NOW + 12.hours.inWholeMilliseconds + settings.update { it.copy(phoneSyncedAtMs = now) } + + assertTrue(sut.reserve(FIVE_DOLLARS)) + assertEquals("2026-11-29", spend.day) + } + + @Test + fun `settings or a count that cannot be read skip nothing`() = test { + spend.failure = IOException("disk") + assertFalse(sut.reserve(1uL)) + + spend.failure = null + whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) + assertFalse(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..264e141c40 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt @@ -0,0 +1,180 @@ +package to.bitkit.wear.repositories + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +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.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.SparkError +import to.bitkit.wear.services.WatchSparkService +import to.bitkit.wear.test.BaseUnitTest +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class SettingsSyncRepoTest : BaseUnitTest() { + private companion object { + const val NOW = 1_795_867_200_000L + const val TOKEN = 4 + 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 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) { 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().isSuccess, raw) + } + + verify(settingsStore, times(2)).clearQuickPay() + 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 { + read = { awaitCancellation() } + + val result = async { sut.sync() } + testScheduler.advanceTimeBy(SettingsSyncRepo.READ_TIMEOUT.inWholeMilliseconds + 1) + + assertIs(result.await().exceptionOrNull()) + verifyNoMoreInteractions(settingsStore) + } + + @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 `a caller that goes away mid-read writes nothing`() = test { + read = { awaitCancellation() } + + val result = async { sut.sync() } + result.cancel() + + verify(settingsStore, never()).applyPhoneSettings(any(), any()) + verifyNoMoreInteractions(settingsStore) + } +} 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..252fe3dfba --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt @@ -0,0 +1,63 @@ +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 call: derive the store id, sign in, read one object, shut down. */ + val ALLOWED_IMPORTS = setOf( + "$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 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/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..3eb2eb2bb9 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 @@ -13,9 +13,11 @@ import org.mockito.kotlin.whenever 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 +26,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 +41,7 @@ class HomeViewModelTest : BaseUnitTest() { private val nfcMonitor = FakeNfcMonitor() private val networkMonitor = FakeNetworkMonitor() private val foregroundMonitor = FakeForegroundMonitor() + private val settingsSyncRepo = mock() private lateinit var sut: HomeViewModel @@ -49,7 +53,16 @@ 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, + ) } override fun onTestEnd() = foregroundMonitor.isForeground.update { false } @@ -65,6 +78,50 @@ 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 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..0a3cc104ca 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 @@ -15,10 +16,12 @@ import org.mockito.kotlin.anyOrNull 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.BitcoinDisplayUnit import to.bitkit.wear.models.FxRate import to.bitkit.wear.models.PaymentState import to.bitkit.wear.models.PreparedSend @@ -52,6 +55,7 @@ class SendViewModelTest : BaseUnitTest() { whenever(walletRepo.walletState).thenReturn(walletState) whenever(currencyRepo.rates).thenReturn(MutableStateFlow(emptyList())) whenever(settingsStore.data).thenReturn(flowOf(WatchSettings())) + whenever { paymentsRepo.skipConfirmation(any()) }.thenReturn(false) } private fun createSut() = SendViewModel( @@ -116,15 +120,51 @@ 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) + val sent = CompletableDeferred>() whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(true) - whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) + whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { sent.await() } - createSut() + val sut = createSut() - verify(paymentsRepo).send(prepared) + assertIs(sut.uiState.value.step) + assertFalse(sut.uiState.value.isHoldEnabled) + verify(paymentsRepo, times(1)).skipConfirmation(prepared) + + 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 `a quickpay send that fails shows the failure like any other`() = test { + val prepared = prepared() + stubInvoice(prepared) + whenever(paymentsRepo.skipConfirmation(prepared)).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(prepared)).thenReturn(false) + + val sut = createSut() + + val step = assertIs(sut.uiState.value.step) + assertEquals("0.00021000", step.amount.text) + verify(paymentsRepo, never()).send(any()) } @Test 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..4bbf266f4d 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,64 @@ 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() }.doSuspendableAnswer { gate.await() } + + sut.onSyncClick() + sut.onSyncClick() + + assertTrue(sut.uiState.value.isSyncing) + verify(settingsSyncRepo, times(1)).sync() + + gate.complete(Result.failure(SparkError.WipeInProgress())) + + assertFalse(sut.uiState.value.isSyncing) } @Test From 3c48e1210e469be746ff0ee29f0574e020e26e07 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 04:51:02 -0300 Subject: [PATCH 02/15] docs: add wear settings sync and quickpay docs and journeys Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 130 ++++++++++++++++++-- journeys/README.md | 1 + journeys/wear/README.md | 52 ++++++++ journeys/wear/quickpay-off-holds.xml | 26 ++++ journeys/wear/quickpay-over-limit-holds.xml | 24 ++++ journeys/wear/quickpay-skips-hold.xml | 28 +++++ journeys/wear/settings-import-units.xml | 29 +++++ 7 files changed, 279 insertions(+), 11 deletions(-) create mode 100644 journeys/wear/quickpay-off-holds.xml create mode 100644 journeys/wear/quickpay-over-limit-holds.xml create mode 100644 journeys/wear/quickpay-skips-hold.xml create mode 100644 journeys/wear/settings-import-units.xml diff --git a/docs/wear.md b/docs/wear.md index 47f85a1919..cfbb9c0142 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,21 @@ 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). - `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 @@ -218,7 +223,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: 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 @@ -243,9 +249,12 @@ On-screen copy stays short: a title or one line of at most about six words per s 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), and a tap imports them now under the loading + ring. 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, @@ -329,8 +338,103 @@ 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). 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. +- It pays a BOLT11 invoice that carries its amount. An amount the wearer typed always gets the review and the hold: + the review is the one place that shows what was typed, its fee and its payee. An LNURL, a Lightning address and + a Spark address always get them too, also when the service fixes the amount. +- The phone's settings were imported at most 15 minutes ago, and QuickPay is on in them. With the app on screen + they are imported every 5 minutes, so this only bites when the import stopped working; it also means QuickPay + turned off on the phone stops on the watch within 15 minutes at most, and sooner when the phone's backup has + uploaded: by the next import. +- A dollar rate fetched at most an hour ago values the payment's cost, the amount plus the fee, at no more than the + phone's QuickPay amount. The cost is rounded up to the cent. The phone compares the amount without the fee; the + watch counts the fee, which is the stricter reading. +- Today's QuickPay payments from this watch, with this one, stay within the daily limit. + +Anything missing, stale or unreadable answers no, and the wearer holds to pay as without QuickPay: no import yet, a +backup the phone never wrote, an unreadable or newer backup, QuickPay values outside what the phone's sliders offer +(1 to 50 dollars, 1× to 50×), no rates, a settings file 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, and stays counted when it then fails: + 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: 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 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. +- **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. `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 across a lock, a pause or a wipe. +- **When.** While Home is open, each time the wallet is ready with the app on screen, so at every start and every + return to the app, and every 5 minutes from then; and on a tap on the Phone settings row. Never in the + background, and never for a wallet that is not connected and synced. 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, is not the envelope, or has a `version` above 1 keeps the display values and turns QuickPay off. + 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; QuickPay then stops by itself once the last import is 15 minutes old. + Failures are logged and never shown or thrown. +- **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 +670,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 QuickPay should also cover a fixed-amount LNURL, and 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..fcac4cccd7 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 recovery phrase 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..46a96c5dbe 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -125,6 +125,20 @@ 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 | +| `settings-import-units.xml` | hosted, and a phone that wrote its settings | yes, any balance above 0 | +| `quickpay-skips-hold.xml` | local, and a phone that wrote its settings | yes, 2 000 sats | +| `quickpay-over-limit-holds.xml` | local, and a phone that wrote its settings | yes, 12 000 sats | +| `quickpay-off-holds.xml` | local, and a phone that wrote its settings, after `quickpay-skips-hold.xml` | yes, 2 000 sats | + +The four 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). + +The daily QuickPay limit, an amount the wearer typed, a missing, unreadable or newer backup, and settings older than +15 minutes have no journey: they depend on the exchange rate of the day, an amountless invoice the local stack does +not make, or a backup only a broken phone would write. `QuickPayRepoTest.kt`, `PaymentsRepoTest.kt`, +`SettingsSyncRepoTest.kt` and `PhoneSettingsParserTest.kt` cover them. 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 @@ -213,6 +227,44 @@ 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. +### 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. Restore the wallet the watch uses in the phone app, or create a new wallet there and note its 12 words from + Settings › Security › Back up your wallet (`BackupWallet`), to restore on the watch. The recovery phrase and passphrase must be the same on + both, 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`). + - 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, every 5 minutes, and at + once on a tap on `WatchSettingsSync` on the Settings page. 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 +change without notice, and QuickPay may be on or off in it. For the QuickPay journeys use a private phrase: a new +wallet created in the phone app. On the local `./spark` stack `receive-paid.xml` funds it on the watch. + +**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..46f702ecc1 --- /dev/null +++ b/journeys/wear/quickpay-off-holds.xml @@ -0,0 +1,26 @@ + + + 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. Then, on the phone with the same recovery phrase, turn QuickPay + off, 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" + Wait 5 s and verify "WatchSendSent" is not listed: 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-over-limit-holds.xml b/journeys/wear/quickpay-over-limit-holds.xml new file mode 100644 index 0000000000..36be699b96 --- /dev/null +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -0,0 +1,24 @@ + + + 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: as quickpay-skips-hold.xml: Phone settings on VSS with QuickPay on at $1 and 5×, see + journeys/wear/README.md › Phone settings on VSS; Restored wallet on the watch with the same recovery phrase on the + local ./spark stack with at least 12 000 sats, the app open on the Balance page and the loading ring stopped. + 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) + Verify "WatchSettingsSyncTime" reads a time of at most 5 minutes ago; if it does not, tap "WatchSettingsSync" and wait 10 s + Swipe right three times to the Balance page and wait until "WatchHomeBalanceSecondary" reads a fiat value, for up to 1 minute + 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 "WatchSendAmount" reads "10 000" + Wait 5 s and verify "WatchSendHold" is still listed and "WatchSendSent" is not: nothing was paid + Hold "WatchSendHold" for 2 s as in README › Holding to pay + Wait up to 15 s until "WatchSendSent" is listed + Verify "WatchSendResultAmount" reads "10 000" + + diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml new file mode 100644 index 0000000000..8b62b04cc2 --- /dev/null +++ b/journeys/wear/quickpay-skips-hold.xml @@ -0,0 +1,28 @@ + + + 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: Phone settings on VSS, see journeys/wear/README.md › Phone settings on VSS, with QuickPay on at $1 + and the daily limit at 5× on the phone, and the phone app closed. Then Restored wallet on the watch with the same + recovery phrase on the local ./spark stack with at least 2 000 sats (run receive-paid.xml first), see README › + Local ./spark stack, with the app open on the Balance page and the loading ring stopped. 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) + Verify "WatchSettingsSyncTime" reads a time of at most 5 minutes ago; if it does not, tap "WatchSettingsSync" and wait 10 s + Swipe right three times to the Balance page and wait until "WatchHomeBalanceSecondary" reads a fiat value, for up to 1 minute: QuickPay needs the rates + 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` + 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 4 s + Verify the Balance page: "WatchHomeBalance" is listed + Verify "WatchSendHold" is not listed + + diff --git a/journeys/wear/settings-import-units.xml b/journeys/wear/settings-import-units.xml new file mode 100644 index 0000000000..5872ddfce2 --- /dev/null +++ b/journeys/wear/settings-import-units.xml @@ -0,0 +1,29 @@ + + + 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: Phone settings on VSS, see journeys/wear/README.md › Phone settings on VSS, with Default Unit set to + the currency, Denomination set to Classic and Local Currency set to EUR on the phone, and the phone app closed. + Then Restored wallet on the watch with the same recovery phrase, see README › Restored wallet, with a balance above + 0. Backend: hosted regtest. + + + 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" + Swipe right three times to the Balance page + Tap "WatchHomeBalanceToggle" + Verify "WatchHomeBalanceSymbol" reads "₿" and "WatchHomeBalance" reads the balance with eight decimals + Restart the app (README › Restart) + Wait 30 s after "WatchHomeBalance" is listed, so the import ran + Verify "WatchHomeBalanceSymbol" still reads "₿": the wearer's swap lasts while the phone's setting stays the same + + From 6c44e2fa9945cb9cc881750e00686e762cfac61c Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 05:27:49 -0300 Subject: [PATCH 03/15] fix: keep quickpay to attended sends, wait for the import, harden the settings import Co-Authored-By: Claude Fable 5.2 --- .../bitkit/models/WatchBackupContractTest.kt | 87 +++++++++++++ .../to/bitkit/wear/data/AmbientMonitor.kt | 20 +++ .../java/to/bitkit/wear/data/ElapsedClock.kt | 9 ++ .../java/to/bitkit/wear/di/SecurityModule.kt | 6 + wear/src/main/java/to/bitkit/wear/env/Env.kt | 26 ++-- .../bitkit/wear/repositories/CurrencyRepo.kt | 13 +- .../bitkit/wear/repositories/PaymentsRepo.kt | 11 +- .../bitkit/wear/repositories/QuickPayRepo.kt | 47 ++++++- .../wear/repositories/SettingsSyncRepo.kt | 76 ++++++++--- .../bitkit/wear/services/PhoneBackupReader.kt | 29 ++++- .../java/to/bitkit/wear/ui/MainActivity.kt | 9 ++ .../ui/screens/activity/ActivityScreen.kt | 2 +- .../wear/ui/screens/home/HomeViewModel.kt | 10 +- .../wear/ui/screens/send/SendViewModel.kt | 60 ++++++++- .../ui/screens/settings/SettingsScreen.kt | 45 +++++-- .../ui/screens/settings/SettingsViewModel.kt | 10 +- wear/src/main/res/values-ar/strings.xml | 1 + wear/src/main/res/values-b+es+419/strings.xml | 1 + wear/src/main/res/values-ca/strings.xml | 3 +- wear/src/main/res/values-cs/strings.xml | 1 + wear/src/main/res/values-de/strings.xml | 1 + wear/src/main/res/values-el/strings.xml | 1 + wear/src/main/res/values-es-rES/strings.xml | 1 + wear/src/main/res/values-es/strings.xml | 1 + wear/src/main/res/values-fr/strings.xml | 1 + wear/src/main/res/values-it/strings.xml | 1 + wear/src/main/res/values-nl/strings.xml | 1 + wear/src/main/res/values-pl/strings.xml | 1 + wear/src/main/res/values-pt-rBR/strings.xml | 1 + wear/src/main/res/values-pt/strings.xml | 1 + wear/src/main/res/values-ru/strings.xml | 1 + wear/src/main/res/values/strings.xml | 1 + .../wear/models/PhoneBackupContractTest.kt | 58 +++++++++ .../wear/repositories/CurrencyRepoTest.kt | 32 ++++- .../wear/repositories/PaymentsRepoTest.kt | 23 ++++ .../wear/repositories/QuickPayRepoTest.kt | 123 +++++++++++++++++- .../wear/repositories/SettingsSyncRepoTest.kt | 116 ++++++++++++++++- .../wear/services/PhoneBackupReaderTest.kt | 8 +- .../wear/ui/screens/home/HomeViewModelTest.kt | 13 ++ .../wear/ui/screens/send/SendViewModelTest.kt | 108 ++++++++++++++- .../screens/settings/SettingsViewModelTest.kt | 22 +++- .../test/resources/phone-backup-contract.json | 31 +++++ 42 files changed, 930 insertions(+), 82 deletions(-) create mode 100644 app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt create mode 100644 wear/src/main/java/to/bitkit/wear/data/AmbientMonitor.kt create mode 100644 wear/src/main/java/to/bitkit/wear/data/ElapsedClock.kt create mode 100644 wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt create mode 100644 wear/src/test/resources/phone-backup-contract.json 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/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/di/SecurityModule.kt b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt index f63e82792d..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,6 +16,7 @@ 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 @@ -115,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 e627dee737..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,22 +47,24 @@ internal object Env { WalletNetwork.TESTNET -> null } - /** The namespace of this network's backups on VSS, the phone's `Env.vssStoreIdPrefix`. */ - val vssStoreIdPrefix: String get() = "bitkit_v1_${network.name.lowercase()}" + /** + * 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. */ - val vssServerUrl: String - get() = when (network) { - WalletNetwork.BITCOIN -> "https://api.bitkit.to/vss_rs_auth" - else -> "https://bitkit.stag0.blocktank.to/vss_rs_auth" - } + 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. */ - val lnurlAuthServerUrl: String - get() = when (network) { - WalletNetwork.BITCOIN -> "https://bitkit.to/lnurl_auth/auth" - else -> "https://bitkit.stag0.blocktank.to/lnurl_auth/auth" - } + 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) { diff --git a/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt index f22c85b172..ac72432f9a 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext +import to.bitkit.wear.data.ElapsedClock import to.bitkit.wear.data.RatesHttpClient import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.di.IoDispatcher @@ -16,14 +17,14 @@ import to.bitkit.wear.utils.Logger import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration -import kotlin.time.TimeMark -import kotlin.time.TimeSource +import kotlin.time.Duration.Companion.milliseconds @Singleton class CurrencyRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, private val ratesHttpClient: RatesHttpClient, private val settingsStore: SettingsStore, + private val clock: ElapsedClock, ) { companion object { private const val TAG = "CurrencyRepo" @@ -33,16 +34,16 @@ class CurrencyRepo @Inject constructor( val rates: StateFlow> = _rates.asStateFlow() @Volatile - private var ratesFetched: TimeMark? = null + private var ratesFetchedAtMs: Long? = null - /** How long ago [rates] were fetched, or null when they never were. */ - fun ratesAge(): Duration? = ratesFetched?.elapsedNow() + /** How long ago [rates] were fetched, the time the watch slept included, or null when they never were. */ + fun ratesAge(): Duration? = ratesFetchedAtMs?.let { (clock.nowMs() - it).milliseconds } suspend fun refresh(): Result = withContext(ioDispatcher) { runSuspendCatching { val tickers = ratesHttpClient.fetchLatestRates().tickers _rates.update { tickers } - ratesFetched = TimeSource.Monotonic.markNow() + ratesFetchedAtMs = clock.nowMs() } } 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 59c5c97936..bff3808cb4 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -147,16 +147,19 @@ class PaymentsRepo @Inject constructor( * - it pays a BOLT11 invoice that carries its amount: an amount the wearer typed is always reviewed, since the * review is the one place that shows what was typed, its fee and its payee, and so is every LNURL, Lightning * address and Spark address payment; - * - [QuickPayRepo.reserve] takes the payment's cost, fee included, under the phone's QuickPay settings. + * - [QuickPayRepo.reserve] takes the payment's cost, fee included, under the phone's QuickPay settings, after + * [QuickPayRepo.awaitInputs] gave an import and rates that are on their way a moment to arrive. * - * A yes counts the payment against today's QuickPay limit, so ask once per send and only when about to send. - * Anything that cannot be told answers no, and the wearer holds to pay. + * 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. Anything that cannot be told answers no, and + * the wearer holds to pay. */ suspend fun skipConfirmation(prepared: PreparedSend): Boolean = withContext(ioDispatcher) { if (!isReady() || sparkService.isWiping) return@withContext false if (!prepared.isAmountFixed) return@withContext false + quickPayRepo.awaitInputs() val isAllowed = quickPayRepo.reserve(prepared.totalSats) - // The wallet may have locked, paused or been wiped while the limit was read. + // The wallet may have locked, paused or been wiped while the limit was awaited and read. isAllowed && isReady() && !sparkService.isWiping } diff --git a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt index 06dc79e7e8..411a0af35d 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -1,10 +1,13 @@ package to.bitkit.wear.repositories import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch 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 @@ -20,6 +23,7 @@ import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes +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. @@ -31,6 +35,7 @@ class QuickPayRepo internal constructor( private val settingsStore: SettingsStore, private val currencyRepo: CurrencyRepo, private val spendStore: QuickPaySpendStore, + private val settingsSyncRepo: SettingsSyncRepo, private val nowMs: () -> Long, private val zone: () -> ZoneId, ) { @@ -46,6 +51,9 @@ class QuickPayRepo internal constructor( /** How old the exchange rates may be for the limit, which is in dollars, to be checked against them. */ val MAX_RATES_AGE = 1.hours + + /** How long [awaitInputs] holds a payment back for a new import and new rates before it goes on without. */ + val INPUTS_TIMEOUT = 5.seconds } @Inject @@ -54,10 +62,44 @@ class QuickPayRepo internal constructor( settingsStore: SettingsStore, currencyRepo: CurrencyRepo, spendStore: QuickPaySpendStore, - ) : this(ioDispatcher, settingsStore, currencyRepo, spendStore, System::currentTimeMillis, ZoneId::systemDefault) + settingsSyncRepo: SettingsSyncRepo, + ) : this( + ioDispatcher, + settingsStore, + currencyRepo, + spendStore, + settingsSyncRepo, + System::currentTimeMillis, + ZoneId::systemDefault, + ) private val mutex = Mutex() + /** + * Brings what [reserve] reads up to date before it is asked, for a payment that arrives as the app starts or + * returns: the import and the rates are then on their way but not in yet. When the last import has QuickPay on + * and is older than [MAX_SETTINGS_AGE], it waits for an import, joining one that runs; when the rates are missing + * or older than [MAX_RATES_AGE], it fetches them. Both together take at most [INPUTS_TIMEOUT]. It decides + * nothing: whatever is still missing or old afterwards makes [reserve] answer no. A watch whose last import has + * QuickPay off, or that has none, never waits here. + */ + suspend fun awaitInputs(): Unit = withContext(ioDispatcher) { + runSuspendCatching { + val settings = settingsStore.data.first() + if (settings.quickPay?.isEnabled != true) return@runSuspendCatching + val isImportFresh = settings.phoneSyncedAtMs?.let { isFresh(nowMs() - it) } == true + val areRatesFresh = currencyRepo.ratesAge()?.let { it <= MAX_RATES_AGE } == true + withTimeoutOrNull(INPUTS_TIMEOUT) { + coroutineScope { + if (!isImportFresh) launch { settingsSyncRepo.sync() } + if (!areRatesFresh) launch { currencyRepo.refresh() } + } + } + }.onFailure { Logger.warn("Failed to refresh what QuickPay reads", it, context = TAG) } + } + + private fun isFresh(settingsAgeMs: Long): Boolean = settingsAgeMs in 0..MAX_SETTINGS_AGE.inWholeMilliseconds + /** * Whether a payment that costs [totalSats], its fee included, may skip the hold to pay, and if so counts it * against today's limit. It may when QuickPay was imported from the phone within [MAX_SETTINGS_AGE] and is on, @@ -75,8 +117,7 @@ class QuickPayRepo internal constructor( val settings = settingsStore.data.first() val quickPay = settings.quickPay?.takeIf { it.isEnabled } ?: return false val now = nowMs() - val settingsAge = now - (settings.phoneSyncedAtMs ?: return false) - if (settingsAge < 0 || settingsAge > MAX_SETTINGS_AGE.inWholeMilliseconds) return false + if (!isFresh(now - (settings.phoneSyncedAtMs ?: return false))) return false val ratesAge = currencyRepo.ratesAge() ?: return false if (ratesAge > MAX_RATES_AGE) return false val rate = currencyRepo.rates.value.rateFor(USD)?.lastPrice?.toBigDecimalOrNull() ?: return false diff --git a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt index 3491343f02..85a57a4b26 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt @@ -2,22 +2,29 @@ package to.bitkit.wear.repositories import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.NonCancellable +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.withContext 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 /** @@ -33,6 +40,7 @@ class SettingsSyncRepo internal constructor( private val settingsStore: SettingsStore, private val sparkService: WatchSparkService, private val walletRepo: WalletRepo, + private val clock: ElapsedClock, private val nowMs: () -> Long, ) { companion object { @@ -43,6 +51,12 @@ class SettingsSyncRepo internal constructor( /** How long signing in to VSS and reading the backup may take. */ 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 @@ -53,6 +67,7 @@ class SettingsSyncRepo internal constructor( settingsStore: SettingsStore, sparkService: WatchSparkService, walletRepo: WalletRepo, + clock: ElapsedClock, ) : this( ioDispatcher, seedStore, @@ -60,53 +75,82 @@ class SettingsSyncRepo internal constructor( settingsStore, sparkService, walletRepo, + clock, System::currentTimeMillis, ) 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 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 then stops by itself once the last import is too old - * ([QuickPayRepo.MAX_SETTINGS_AGE]). An import that a wallet wipe overtook is taken out again, so nothing of a - * removed wallet's settings stays. + * 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 then stops by itself once the last import is too + * old ([QuickPayRepo.MAX_SETTINGS_AGE]). The read is given up as soon as the wallet stops being ready, as on a + * lock or a pause, so nothing derived from the seed outlives either. An import that a wallet wipe overtook is + * taken out again, so nothing of a removed wallet's settings stays. + * + * 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(): Result = withContext(ioDispatcher) { - runSuspendCatching { mutex.withLock { syncLocked() } } + suspend fun sync(isForced: Boolean = false): Result = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { syncLocked(isForced) } } .onFailure { Logger.warn("Failed to import the phone's settings", it, context = TAG) } } - private suspend fun syncLocked() { + 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) { Result.success(backupReader.read(seed, SETTINGS_KEY)) } - ?: throw SettingsSyncError.Timeout() + val backup = withTimeoutOrNull(READ_TIMEOUT) { readWhileReady(seed) } ?: throw SettingsSyncError.Timeout() // From here the outcome is written whole, also when the caller goes away. withContext(NonCancellable) { - val bytes = backup.getOrThrow() - val parsed = bytes?.let { runCatching { PhoneSettingsParser.parse(it) } } + 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 == null -> { - Logger.info("Found no settings backup of the phone", context = TAG) - settingsStore.clearQuickPay() - } 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(parsed.getOrThrow(), nowMs()) + 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. Either way the reader has shut its client down when this returns. + */ + private suspend fun readWhileReady(seed: WalletSeed): Result = channelFlow { + launch { send(runSuspendCatching { backupReader.read(seed, SETTINGS_KEY) }) } + launch { + walletRepo.walletState.first { it.status != WalletStatus.Ready } + send(Result.failure(SettingsSyncError.NotReady())) + } + }.first() } sealed class SettingsSyncError(message: String) : AppError(message) { diff --git a/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt index afcd96e16f..41c9355217 100644 --- a/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt +++ b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt @@ -1,5 +1,6 @@ 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 @@ -9,7 +10,9 @@ 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 @@ -18,14 +21,22 @@ import javax.inject.Singleton * 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. */ + /** + * 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 imported above; `PhoneBackupReaderTest` checks both. The library keeps one client for the + * 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. */ @@ -36,15 +47,19 @@ class VssPhoneBackupReader @Inject constructor() : PhoneBackupReader { override suspend fun read(seed: WalletSeed, key: String): ByteArray? = mutex.withLock { try { vssNewClientWithLnurlAuth( - baseUrl = Env.vssServerUrl, - storeId = vssDeriveStoreId(Env.vssStoreIdPrefix, seed.mnemonic, seed.passphrase), + baseUrl = Env.vssServerUrl(), + storeId = vssDeriveStoreId(Env.vssStoreIdPrefix(), seed.mnemonic, seed.passphrase), mnemonic = seed.mnemonic, passphrase = seed.passphrase, - lnurlAuthServerUrl = Env.lnurlAuthServerUrl, + lnurlAuthServerUrl = Env.lnurlAuthServerUrl(), ) - vssGet(key)?.value + try { + vssGet(key)?.value + } catch (_: VssException.GetException) { + throw PhoneBackupUnreadable() + } } finally { - withContext(NonCancellable) { runCatching { vssShutdownClient() } } + withContext(NonCancellable) { runSuspendCatching { vssShutdownClient() } } } } } 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..40929d7866 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. */ @@ -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/ActivityScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/activity/ActivityScreen.kt index ba954f9883..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 @@ -131,7 +131,7 @@ private fun List( FilledTonalButton( onClick = { onPaymentClick(payment.id) }, icon = { DirectionIcon(payment = payment) }, - label = { Text(text = payment.amountText(uiState.unit), maxLines = 1) }, + label = { Text(text = payment.amountText(uiState.unit), maxLines = 2) }, secondaryLabel = { Text(text = relativeTime(payment.timestampSecs.toLong(), uiState.nowSecs), maxLines = 1) }, 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 c45dfff195..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 @@ -45,7 +46,8 @@ 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. It imports the phone's settings each time the wallet - * is ready with the app on screen, so at every start and return, and every [SETTINGS_SYNC_INTERVAL] from then. + * 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( @@ -56,6 +58,7 @@ class HomeViewModel @Inject constructor( networkMonitor: NetworkMonitor, foregroundMonitor: ForegroundMonitor, private val settingsSyncRepo: SettingsSyncRepo, + ambientMonitor: AmbientMonitor, ) : ViewModel() { companion object { private const val TAG = "HomeViewModel" @@ -66,7 +69,7 @@ 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 on screen. */ + /** 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 } @@ -101,7 +104,8 @@ class HomeViewModel @Inject constructor( combine( foregroundMonitor.isForeground, walletRepo.walletState.map { it.status == WalletStatus.Ready }, - ) { isForeground, isReady -> isForeground && isReady } + ambientMonitor.isAmbient, + ) { isForeground, isReady, isAmbient -> isForeground && isReady && !isAmbient } .distinctUntilChanged() .collectLatest { canSync -> while (canSync) { 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 0d9a7b4ca6..2d5160cff2 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,11 +13,15 @@ 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 @@ -44,6 +48,11 @@ import kotlin.time.Duration.Companion.seconds * 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 without a network, 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. */ @HiltViewModel class SendViewModel @Inject constructor( @@ -52,6 +61,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" @@ -70,6 +82,12 @@ 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 } private val input: String = savedStateHandle.get(Routes.SEND_INPUT).orEmpty() @@ -87,8 +105,29 @@ class SendViewModel @Inject constructor( /** 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. */ + private var wasAway = false + + /** Whether the wallet was seen out of [WalletStatus.Paused], which it may be in only while the app returns. */ + private var hasLeftPause = false + init { 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) } @@ -175,7 +214,9 @@ class SendViewModel @Inject constructor( if (_uiState.value.step is SendStep.Offline) return prepared = result unit = runSuspendCatching { settingsStore.data.first().displayUnit }.getOrDefault(BitcoinDisplayUnit.MODERN) - if (paymentsRepo.skipConfirmation(result)) { + // 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. + if (isQuickPayOpen() && paymentsRepo.skipConfirmation(result) && isAttended()) { Logger.info("Skipped the hold to pay under QuickPay", context = TAG) send(result) return @@ -183,6 +224,23 @@ class SendViewModel @Inject constructor( show(review(result, request)) } + /** Whether QuickPay may be asked for a send priced now: see the class. */ + private fun isQuickPayOpen(): Boolean = + isAttended() && clock.nowMs() - arrivedAtMs in 0..QUICKPAY_WINDOW.inWholeMilliseconds + + /** + * 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() 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 bf7defebc8..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 @@ -31,7 +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 java.time.Instant +import to.bitkit.wear.ui.screens.activity.rememberNowSecs @Composable fun SettingsScreen( @@ -40,8 +40,11 @@ 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, @@ -54,6 +57,7 @@ fun SettingsScreen( @Composable private fun Content( uiState: SettingsUiState, + nowMs: Long, onAboutClick: () -> Unit, onSyncClick: () -> Unit, onRemoveClick: () -> Unit, @@ -88,11 +92,11 @@ private fun Content( onClick = onSyncClick, enabled = !uiState.isSyncing && !uiState.isRemoving, icon = { RowIcon(R.drawable.ic_sync) }, - label = { Text(stringResource(R.string.settings__phone_settings), maxLines = 1) }, + label = { Text(stringResource(R.string.settings__phone_settings)) }, secondaryLabel = uiState.phoneSyncedAtMs?.let { syncedAtMs -> { Text( - text = syncedAgo(syncedAtMs), + text = syncedAgo(syncedAtMs, nowMs), maxLines = 1, modifier = Modifier.testTag("WatchSettingsSyncTime") ) @@ -105,6 +109,20 @@ private fun Content( .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, @@ -159,16 +177,13 @@ private fun Content( ) } -/** How long ago the phone's settings were imported; a time ahead of the watch's clock counts as now. */ -private fun syncedAgo(syncedAtMs: Long): String { - val now = Instant.now().toEpochMilli() - return DateUtils.getRelativeTimeSpanString( - syncedAtMs.coerceAtMost(now), - now, - DateUtils.MINUTE_IN_MILLIS, - DateUtils.FORMAT_ABBREV_RELATIVE, - ).toString() -} +/** 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( @@ -183,7 +198,8 @@ private fun RowIcon( private fun Preview() { WearPreview { Content( - uiState = SettingsUiState(phoneSyncedAtMs = 0), + uiState = SettingsUiState(phoneSyncedAtMs = 0, isSyncFailed = true), + nowMs = 120_000, onAboutClick = {}, onSyncClick = {}, onRemoveClick = {}, @@ -199,6 +215,7 @@ private fun PreviewRemoveConfirm() { WearPreview { Content( uiState = SettingsUiState(isRemoveDialogVisible = true), + nowMs = 0, onAboutClick = {}, onSyncClick = {}, onRemoveClick = {}, 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 a93ebfc66e..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 @@ -33,12 +33,15 @@ class SettingsViewModel @Inject constructor( } } - /** Imports the phone's settings now, from the row that shows when they were last imported. */ + /** + * 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) } + _uiState.update { it.copy(isSyncing = true, isSyncFailed = false) } viewModelScope.launch { - settingsSyncRepo.sync() + settingsSyncRepo.sync(isForced = true).onFailure { _uiState.update { it.copy(isSyncFailed = true) } } _uiState.update { it.copy(isSyncing = false) } } } @@ -71,6 +74,7 @@ data class SettingsUiState( 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/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml index 5816f4e760..6a019b9691 100644 --- a/wear/src/main/res/values-ar/strings.xml +++ b/wear/src/main/res/values-ar/strings.xml @@ -69,6 +69,7 @@ تحقق من النشاط في انتظار الشبكة إعدادات الهاتف + تعذّر الاستيراد إزالة المحفظة إزالة المحفظة؟ تعذّرت إزالة المحفظة 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 f9629e62c8..6c6cf80683 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -66,6 +66,7 @@ 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 de41b266bd..752d58a710 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -65,7 +65,8 @@ Enviat Revisa l\'activitat Esperant la xarxa - Configuracions del telèfon + 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 ab739285ed..db62d4b208 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -67,6 +67,7 @@ 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 94b54c8dc8..c127f5e8d1 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -65,6 +65,7 @@ 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 c864ecada6..2ff5822172 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -65,6 +65,7 @@ Δες τη δραστηριότητα Αναμονή για δίκτυο Ρυθμίσεις τηλεφώνου + Αδυναμία εισαγωγής Αφαίρεση πορτοφολιού Αφαίρεση πορτοφολιού; Αδυναμία αφαίρεσης πορτοφολιού diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index ad42c21745..ab02c5e19b 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -66,6 +66,7 @@ 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 ad42c21745..ab02c5e19b 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -66,6 +66,7 @@ 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 611c799eb1..3302738046 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -66,6 +66,7 @@ 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 41e7bc0ad6..daee4e3424 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -66,6 +66,7 @@ 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 65d18b2dfd..79a1d475ed 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -65,6 +65,7 @@ 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 fb9cb35e88..3ce8962352 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -67,6 +67,7 @@ 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 a1a21bf1ac..9496751b26 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -66,6 +66,7 @@ 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 fa29a9787f..c2c80f951c 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -66,6 +66,7 @@ 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 7b859246a5..c916fe53d7 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -67,6 +67,7 @@ Проверьте активность Ожидание сети Настройки телефона + Не удалось импортировать Удалить кошелёк Удалить кошелёк? Не удалось удалить кошелёк diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index d23c0050dc..380d38685d 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -65,6 +65,7 @@ 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/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/repositories/CurrencyRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt index 470a6d5b37..b61fc95e93 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt @@ -9,15 +9,45 @@ import org.mockito.kotlin.whenever import to.bitkit.wear.data.RatesHttpClient import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings +import to.bitkit.wear.models.FxRateResponse import to.bitkit.wear.models.PrimaryDisplay +import to.bitkit.wear.models.rate import to.bitkit.wear.security.SeedStoreError import to.bitkit.wear.test.BaseUnitTest +import java.io.IOException +import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours class CurrencyRepoTest : BaseUnitTest() { private val settingsStore = mock() - private val sut by lazy { CurrencyRepo(testDispatcher, mock(), settingsStore) } + private val ratesHttpClient = mock() + private var elapsedMs = 5_000L + private val sut by lazy { CurrencyRepo(testDispatcher, ratesHttpClient, settingsStore) { elapsedMs } } + + @Test + fun `the rates' age counts from their fetch on the clock that runs through sleep`() = test { + whenever(ratesHttpClient.fetchLatestRates()).thenReturn(FxRateResponse(listOf(rate("100000")))) + assertNull(sut.ratesAge()) + + assertTrue(sut.refresh().isSuccess) + assertEquals(Duration.ZERO, sut.ratesAge()) + + elapsedMs += 3.hours.inWholeMilliseconds + assertEquals(3.hours, sut.ratesAge()) + } + + @Test + fun `a fetch that fails leaves the rates' age as it was`() = test { + whenever(ratesHttpClient.fetchLatestRates()).thenAnswer { throw IOException("offline") } + + assertTrue(sut.refresh().isFailure) + + assertNull(sut.ratesAge()) + } @Test fun `switching the unit stores fiat first when bitcoin was first, and back`() = test { 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 90099aff18..d07c91d1a1 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -27,6 +27,7 @@ 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 @@ -550,6 +551,27 @@ class PaymentsRepoTest : BaseUnitTest() { verify(quickPayRepo, times(1)).reserve(any()) } + @Test + fun `quickpay waits for a running import and the rates before it reads the limits`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(true) + + sut.skipConfirmation(preparedSend()) + + val order = inOrder(quickPayRepo) + order.verify(quickPayRepo).awaitInputs() + order.verify(quickPayRepo).reserve(any()) + } + + @Test + fun `quickpay holds when the wallet stopped being ready while it waited for the import`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(true) + whenever(quickPayRepo.awaitInputs()).doSuspendableAnswer { + walletState.update { it.copy(status = WalletStatus.Paused) } + } + + assertFalse(sut.skipConfirmation(preparedSend())) + } + @Test fun `quickpay holds when the limits say no`() = test { whenever(quickPayRepo.reserve(any())).thenReturn(false) @@ -564,6 +586,7 @@ class PaymentsRepoTest : BaseUnitTest() { assertFalse(sut.skipConfirmation(amountless)) + verify(quickPayRepo, never()).awaitInputs() verify(quickPayRepo, never()).reserve(any()) } diff --git a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt index 83dc4b447e..9281e72b68 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -1,11 +1,20 @@ package to.bitkit.wear.repositories +import kotlinx.coroutines.CompletableDeferred +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.any +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 @@ -24,6 +33,7 @@ import kotlin.time.Duration.Companion.milliseconds 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 */ @@ -35,6 +45,8 @@ class QuickPayRepoTest : BaseUnitTest() { private val settingsStore = mock() private val currencyRepo = mock() private val spend = FakeQuickPaySpendStore() + private val settingsSyncRepo = mock() + 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 @@ -47,7 +59,95 @@ class QuickPayRepoTest : BaseUnitTest() { whenever(settingsStore.data).thenReturn(settings) whenever(currencyRepo.rates).thenReturn(rates) whenever(currencyRepo.ratesAge()).thenAnswer { ratesAge } - sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, { now }, { ZoneId.of("UTC") }) + whenever { settingsSyncRepo.sync() }.thenReturn(Result.success(Unit)) + whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) + sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, settingsSyncRepo, { now }, { zone }) + } + + private fun makeImportStale() { + now = NOW + QuickPayRepo.MAX_SETTINGS_AGE.inWholeMilliseconds + 1 + } + + @Test + fun `an import still under way when the payment is priced is waited for, and then decides`() = test { + makeImportStale() + val imported = CompletableDeferred() + whenever(settingsSyncRepo.sync()).doSuspendableAnswer { + imported.await() + settings.update { it.copy(phoneSyncedAtMs = now) } + Result.success(Unit) + } + assertFalse(sut.reserve(1uL)) + + val waiting = async { sut.awaitInputs() } + assertFalse(waiting.isCompleted) + + imported.complete(Unit) + waiting.await() + + assertTrue(sut.reserve(FIVE_DOLLARS)) + verify(currencyRepo, never()).refresh() + } + + @Test + fun `missing or old rates are fetched before the payment is decided`() = test { + whenever(currencyRepo.refresh()).doSuspendableAnswer { + ratesAge = Duration.ZERO + Result.success(Unit) + } + for (age in listOf(null, QuickPayRepo.MAX_RATES_AGE + 1.milliseconds)) { + ratesAge = age + + sut.awaitInputs() + + assertTrue(sut.reserve(1uL), "$age") + } + verify(currencyRepo, times(2)).refresh() + verify(settingsSyncRepo, never()).sync(any()) + } + + @Test + fun `the wait for an import and rates ends after five seconds and the payment then holds`() = test { + makeImportStale() + ratesAge = null + whenever(settingsSyncRepo.sync()).doSuspendableAnswer { awaitCancellation() } + whenever(currencyRepo.refresh()).doSuspendableAnswer { awaitCancellation() } + + val waiting = async { sut.awaitInputs() } + testScheduler.advanceTimeBy(QuickPayRepo.INPUTS_TIMEOUT.inWholeMilliseconds - 1) + assertFalse(waiting.isCompleted) + testScheduler.advanceTimeBy(2) + + assertTrue(waiting.isCompleted) + assertFalse(sut.reserve(1uL)) + assertEquals(0L, spend.spentCents) + } + + @Test + fun `an import that fails ends the wait and the payment holds`() = test { + makeImportStale() + whenever(settingsSyncRepo.sync()).thenReturn(Result.failure(IOException("offline"))) + + sut.awaitInputs() + + assertFalse(sut.reserve(1uL)) + } + + @Test + fun `nothing is waited for with a fresh import and rates, with quickpay off or before any import`() = test { + sut.awaitInputs() + + makeImportStale() + ratesAge = null + settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } + sut.awaitInputs() + settings.update { WatchSettings() } + sut.awaitInputs() + whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) + sut.awaitInputs() + + verify(settingsSyncRepo, never()).sync(any()) + verify(currencyRepo, never()).refresh() } @Test @@ -156,7 +256,7 @@ class QuickPayRepoTest : BaseUnitTest() { } @Test - fun `the next day starts a new count, read in the watch's time zone`() = test { + fun `the next day starts a new count`() = test { repeat(3) { sut.reserve(FIVE_DOLLARS) } assertFalse(sut.reserve(1uL)) @@ -167,6 +267,25 @@ class QuickPayRepoTest : BaseUnitTest() { 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) { assertTrue(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 + settings.update { it.copy(phoneSyncedAtMs = now) } + assertFalse(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 + settings.update { it.copy(phoneSyncedAtMs = now) } + assertTrue(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") diff --git a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt index 264e141c40..1360b5ab67 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.update 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.never @@ -25,11 +26,13 @@ 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 kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue @@ -58,6 +61,7 @@ class SettingsSyncRepoTest : BaseUnitTest() { 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() @@ -70,7 +74,16 @@ class SettingsSyncRepoTest : BaseUnitTest() { whenever(walletRepo.walletState).thenReturn(walletState) whenever(sparkService.wipeToken()).thenReturn(TOKEN) whenever(sparkService.isCurrent(TOKEN)).thenReturn(true) - sut = SettingsSyncRepo(testDispatcher, seedStore, reader, settingsStore, sparkService, walletRepo) { NOW } + sut = SettingsSyncRepo( + testDispatcher, + seedStore, + reader, + settingsStore, + sparkService, + walletRepo, + { elapsedMs }, + { NOW }, + ) } @Test @@ -97,13 +110,96 @@ class SettingsSyncRepoTest : BaseUnitTest() { for (raw in listOf("garbage", """{"version":2,"settings":{"isQuickPayEnabled":true}}""")) { read = { raw.toByteArray() } - assertTrue(sut.sync().isSuccess, raw) + 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") } @@ -177,4 +273,20 @@ class SettingsSyncRepoTest : BaseUnitTest() { verify(settingsStore, never()).applyPhoneSettings(any(), any()) 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 index 252fe3dfba..21a1d8f160 100644 --- a/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt +++ b/wear/src/test/java/to/bitkit/wear/services/PhoneBackupReaderTest.kt @@ -14,8 +14,12 @@ class PhoneBackupReaderTest { const val VSS_PACKAGE = "com.synonym.vssclient" const val READER_FILE = "PhoneBackupReader.kt" - /** Everything of vss-client the watch may call: derive the store id, sign in, read one object, shut down. */ + /** + * 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", @@ -43,7 +47,7 @@ class PhoneBackupReaderTest { } @Test - fun `the reader imports only the calls that derive, sign in, read and shut down`() { + 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 ") } 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 3eb2eb2bb9..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,6 +10,7 @@ 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 @@ -42,6 +43,7 @@ class HomeViewModelTest : BaseUnitTest() { private val networkMonitor = FakeNetworkMonitor() private val foregroundMonitor = FakeForegroundMonitor() private val settingsSyncRepo = mock() + private val ambientMonitor = AmbientMonitor() private lateinit var sut: HomeViewModel @@ -62,6 +64,7 @@ class HomeViewModelTest : BaseUnitTest() { networkMonitor, foregroundMonitor, settingsSyncRepo, + ambientMonitor, ) } @@ -100,6 +103,16 @@ class HomeViewModelTest : BaseUnitTest() { 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) { 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 0a3cc104ca..0cc55b414d 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 @@ -19,6 +19,7 @@ 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 @@ -33,6 +34,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 @@ -49,6 +51,9 @@ 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() { @@ -64,7 +69,9 @@ class SendViewModelTest : BaseUnitTest() { walletRepo, currencyRepo, settingsStore, - ) + foregroundMonitor, + ambientMonitor, + ) { elapsedMs } @Test fun `the input is read only once the wallet is ready`() = test { @@ -140,6 +147,105 @@ class SendViewModelTest : BaseUnitTest() { 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(prepared)).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.Offline, WalletStatus.Error, WalletStatus.Connecting)) { + walletState.update { it.copy(status = status) } + stubInvoice(prepared()) + whenever(paymentsRepo.skipConfirmation(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()) + verify(paymentsRepo, never()).send(any()) + } + + @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())).thenReturn(true) + + val sut = createSut() + interrupt() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step, name) + } + verify(paymentsRepo, never()).skipConfirmation(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())).thenReturn(true) + + val sut = createSut() + walletState.update { it.copy(status = WalletStatus.Ready) } + + assertIs(sut.uiState.value.step) + verify(paymentsRepo, never()).skipConfirmation(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(prepared)).doSuspendableAnswer { + ambientMonitor.set(true) + true + } + + 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() 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 4bbf266f4d..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 @@ -48,17 +48,33 @@ class SettingsViewModelTest : BaseUnitTest() { @Test fun `a tap on the row imports the phone's settings once at a time`() = test { val gate = CompletableDeferred>() - whenever { settingsSyncRepo.sync() }.doSuspendableAnswer { gate.await() } + whenever { settingsSyncRepo.sync(isForced = true) }.doSuspendableAnswer { gate.await() } sut.onSyncClick() sut.onSyncClick() assertTrue(sut.uiState.value.isSyncing) - verify(settingsSyncRepo, times(1)).sync() + verify(settingsSyncRepo, times(1)).sync(isForced = true) - gate.complete(Result.failure(SparkError.WipeInProgress())) + 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" + } + } +} From 16cabbe8dc632256c8e8769e2eda66f707c2ffc6 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 05:27:50 -0300 Subject: [PATCH 04/15] docs: update wear settings sync docs and journeys for round 1 fixes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 85 ++++++++++++++----- journeys/README.md | 2 +- journeys/wear/README.md | 67 ++++++++++++--- journeys/wear/quickpay-off-holds.xml | 7 +- journeys/wear/quickpay-on-app-start.xml | 24 ++++++ journeys/wear/quickpay-over-limit-holds.xml | 20 +++-- journeys/wear/quickpay-skips-hold.xml | 24 +++--- journeys/wear/settings-import-units.xml | 16 ++-- .../wear/settings-swap-survives-import.xml | 20 +++++ 9 files changed, 195 insertions(+), 70 deletions(-) create mode 100644 journeys/wear/quickpay-on-app-start.xml create mode 100644 journeys/wear/settings-swap-survives-import.xml diff --git a/docs/wear.md b/docs/wear.md index cfbb9c0142..cc55fc050d 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -81,6 +81,9 @@ settings by reading the phone's backup (see Settings sync). screen). - `tile`: `BalanceTileService` (the balance tile), `TileState` (what it shows) and `TileUpdates` (asks the system to draw it again). See Tile below. + `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). - `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 @@ -157,7 +160,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 @@ -223,8 +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 once the send is priced: under the phone's QuickPay the review and - the hold are skipped and the send goes out at once (see QuickPay). + `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 @@ -243,6 +247,7 @@ 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 @@ -252,13 +257,14 @@ On-screen copy stays short: a title or one line of at most about six words per s - **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), and a tap imports them now under the loading - ring. Tapping the balance still swaps which unit shows first, and the choice is kept across restarts until the + 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 @@ -354,21 +360,39 @@ result screens, only when every one of these holds: - It pays a BOLT11 invoice that carries its amount. An amount the wearer typed always gets the review and the hold: the review is the one place that shows what was typed, its fee and its payee. An LNURL, a Lightning address and a Spark address always get them too, also when the service fixes the amount. -- The phone's settings were imported at most 15 minutes ago, and QuickPay is on in them. With the app on screen - they are imported every 5 minutes, so this only bites when the import stopped working; it also means QuickPay - turned off on the phone stops on the watch within 15 minutes at most, and sooner when the phone's backup has - uploaded: by the next import. +- The wearer is there (`SendViewModel`). The send was 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 without a network that connects minutes later by itself, always ends on the review and + the hold, so nothing is paid after the wearer looked away. The phone does the same for a scan put off across + its lock. The 30 s cover a wallet that connects and syncs as the link opens the app. +- The phone's settings were imported at most 15 minutes ago, and QuickPay is on in them. The age is that of the + watch's last read of the backup, not of the phone's upload: QuickPay turned off on the phone stops on the watch + with the first import after the phone uploaded its settings, and within 15 minutes of the watch's last import + when the watch cannot read the backup any more. A phone that could not upload leaves its old backup in place, + and the watch keeps following that one. - A dollar rate fetched at most an hour ago values the payment's cost, the amount plus the fee, at no more than the - phone's QuickPay amount. The cost is rounded up to the cent. The phone compares the amount without the fee; the - watch counts the fee, which is the stricter reading. + phone's QuickPay amount. The hour is counted on the clock that keeps running while the watch sleeps + (`ElapsedClock`). The cost is rounded up to the cent. The phone compares the amount without the fee; the watch + counts the fee, which is the stricter reading. - Today's QuickPay payments from this watch, with this one, stay within the daily limit. +A payment link usually opens the app, after a start or a long absence, and the import and the rates that the start +brings are then still on their way when the send is priced. So before it reads the limits the decision waits for +them (`QuickPayRepo.awaitInputs`): when the last import has QuickPay on and is older than 15 minutes it joins the +import under way, or starts one, and when the rates are missing or older than an hour it fetches them, both together +for 5 s at most, under the loading ring. It waits only then: a watch whose last import has QuickPay off, or that has +none, goes to the review at once, so QuickPay newly turned on at the phone applies from the payment after the next +import. What is still missing after the wait answers no. The wait cannot turn into a late payment: it starts only +inside the 30 s above, and the wearer has to be there still when it ends. + Anything missing, stale or unreadable answers no, and the wearer holds to pay as without QuickPay: no import yet, a backup the phone never wrote, an unreadable or newer backup, QuickPay values outside what the phone's sliders offer (1 to 50 dollars, 1× to 50×), no rates, a settings file 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, and stays counted when it then fails: + clears. A payment is counted when QuickPay lets it out, before it is sent, and stays counted when it then fails + or when the wearer turns out to have looked away meanwhile and holds to pay after all: 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: two counts.** The phone keeps its own count of the day's QuickPay payments and the watch cannot read @@ -401,26 +425,41 @@ from VSS and never writes there. (`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. `PhoneBackupReaderTest` fails the + 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 across a lock, a pause or a wipe. -- **When.** While Home is open, each time the wallet is ready with the app on screen, so at every start and every - return to the app, and every 5 minutes from then; and on a tap on the Phone settings row. Never in the - background, and never for a wallet that is not connected and synced. Reading takes about 2 s; it is given up - after 30 s. +- **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; before a + QuickPay decision whose import is too old (see QuickPay); 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. Never in the background or + in ambient mode, and never 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 the client is shut down with it. + 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, is not the envelope, or has a `version` above 1 keeps the display values and turns QuickPay off. - 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; QuickPay then stops by itself once the last import is 15 minutes old. - Failures are logged and never shown or thrown. + 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; QuickPay then stops by itself once the last import is 15 minutes old. 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 diff --git a/journeys/README.md b/journeys/README.md index fcac4cccd7..cf898fdbe5 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -139,7 +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 recovery phrase writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) | +| The phone's settings on the watch (units, currency, QuickPay) | a phone dev build with the same private recovery phrase, never the public test phrase, 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 46a96c5dbe..e6e0b57951 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -129,11 +129,18 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `quickpay-skips-hold.xml` | local, and a phone that wrote its settings | yes, 2 000 sats | | `quickpay-over-limit-holds.xml` | local, and a phone that wrote its settings | yes, 12 000 sats | | `quickpay-off-holds.xml` | local, and a phone that wrote its settings, after `quickpay-skips-hold.xml` | yes, 2 000 sats | - -The four settings journeys read the phone's settings backup from Blocktank's hosted staging VSS, which every dev +| `settings-import-units.xml` | local, a private phrase, 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, a private phrase, 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, a private phrase, 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). +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, an amount the wearer typed, a missing, unreadable or newer backup, and settings older than 15 minutes have no journey: they depend on the exchange rate of the day, an amountless invoice the local stack does @@ -163,7 +170,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. @@ -227,6 +234,35 @@ 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)). + +### 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. + +1. Create a new wallet in a phone dev build, from its onboarding: a phrase nobody else has. Do not + reuse a phrase that holds or ever held real funds. +2. Read its 12 words at Settings › Security › Back up your wallet (`BackupWallet`). +3. Keep the words out of the repository, the journey files, logs, screenshots and pull requests. Hold them in a + shell variable for the session, read without echo: + + ```bash + read -rs PHRASE # paste the 12 words, separated by spaces, then Enter + ``` + +4. Restore it on the watch as in [Restored wallet](#restored-wallet), typing `for w in $PHRASE; do … done` with the + loop of [Typing several words](#typing-several-words). +5. On the local `./spark` stack, `receive-paid.xml` funds it on the watch. + +One private wallet serves all six journeys. Remove it from the watch (`remove-wallet.xml` or +[Fresh app](#fresh-app)) before the journeys on the public phrase run again. + ### Phone settings on VSS The watch never writes settings; it imports the ones a phone app backed up for the same recovery phrase @@ -237,9 +273,9 @@ names this precondition: ([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. Restore the wallet the watch uses in the phone app, or create a new wallet there and note its 12 words from - Settings › Security › Back up your wallet (`BackupWallet`), to restore on the watch. The recovery phrase and passphrase must be the same on - both, since they name the backup. +2. Use the [Private settings wallet](#private-settings-wallet) in the phone app: the wallet created there, or the + same private phrase restored. Never restore the public test phrase 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`). @@ -251,16 +287,23 @@ names this precondition: 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, every 5 minutes, and at - once on a tap on `WatchSettingsSync` on the Settings page. Debug builds log `Imported the phone's settings`: +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 -change without notice, and QuickPay may be on or off in it. For the QuickPay journeys use a private phrase: a new -wallet created in the phone app. On the local `./spark` stack `receive-paid.xml` funds it on the watch. +**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, 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. **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. diff --git a/journeys/wear/quickpay-off-holds.xml b/journeys/wear/quickpay-off-holds.xml index 46f702ecc1..7751ff4d4c 100644 --- a/journeys/wear/quickpay-off-holds.xml +++ b/journeys/wear/quickpay-off-holds.xml @@ -4,8 +4,9 @@ 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. Then, on the phone with the same recovery phrase, turn QuickPay - off, wait for the backup and close the phone app, see journeys/wear/README.md › Phone settings on VSS. Watch: the + Precondition: run quickpay-skips-hold.xml first, on its Private settings wallet and never the public test phrase. + Then, on the phone with the same recovery phrase, turn QuickPay off, 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. @@ -19,7 +20,7 @@ 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" - Wait 5 s and verify "WatchSendSent" is not listed: nothing was paid + 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..0dcc4b5c00 --- /dev/null +++ b/journeys/wear/quickpay-on-app-start.xml @@ -0,0 +1,24 @@ + + + A payment link that starts the app is paid under QuickPay too, although the last import of the phone's settings + is too old by then: the send waits a moment for the import and the rates that the start brings, and then goes + out without the review and the hold. Emulator and physical watch. + + Precondition: run quickpay-skips-hold.xml first, so the watch's last import has QuickPay 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. + + + Run `adb shell am force-stop to.bitkit.dev` + Wait 16 minutes: the last import is then too old for QuickPay + 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 "Imported the phone's settings" + 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 index 36be699b96..bd56c15e53 100644 --- a/journeys/wear/quickpay-over-limit-holds.xml +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -3,22 +3,24 @@ 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: as quickpay-skips-hold.xml: Phone settings on VSS with QuickPay on at $1 and 5×, see - journeys/wear/README.md › Phone settings on VSS; Restored wallet on the watch with the same recovery phrase on the - local ./spark stack with at least 12 000 sats, the app open on the Balance page and the loading ring stopped. - 10 000 sats are above $1 while a bitcoin costs more than $10 000. README › Holding to pay has the hold gesture. + Precondition: as quickpay-skips-hold.xml: Private settings wallet, never the public test phrase; Phone settings + on VSS with QuickPay on at $1 and 5×, see journeys/wear/README.md › Phone settings on VSS; that wallet restored + on the watch on the local ./spark stack with at least 12 000 sats, the app open on the Balance page and the + loading ring stopped. 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) - Verify "WatchSettingsSyncTime" reads a time of at most 5 minutes ago; if it does not, tap "WatchSettingsSync" and wait 10 s - Swipe right three times to the Balance page and wait until "WatchHomeBalanceSecondary" reads a fiat value, for up to 1 minute + 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 "WatchSendAmount" reads "10 000" - Wait 5 s and verify "WatchSendHold" is still listed and "WatchSendSent" is not: nothing was paid + 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 - Verify "WatchSendResultAmount" reads "10 000" diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml index 8b62b04cc2..fca60a96b0 100644 --- a/journeys/wear/quickpay-skips-hold.xml +++ b/journeys/wear/quickpay-skips-hold.xml @@ -4,25 +4,25 @@ 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: Phone settings on VSS, see journeys/wear/README.md › Phone settings on VSS, with QuickPay on at $1 - and the daily limit at 5× on the phone, and the phone app closed. Then Restored wallet on the watch with the same - recovery phrase on the local ./spark stack with at least 2 000 sats (run receive-paid.xml first), see README › - Local ./spark stack, with the app open on the Balance page and the loading ring stopped. 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. + Precondition: Private settings wallet, see journeys/wear/README.md › Private settings wallet, never the public + test phrase. Phone settings on VSS, see README › Phone settings on VSS, with QuickPay on at $1 and the daily limit + at 5× on the phone, and the phone app closed. Then that wallet restored on the watch on the local ./spark stack + with at least 2 000 sats (run receive-paid.xml first), see README › Local ./spark stack, with the app open on the + Balance page and the loading ring stopped. 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) - Verify "WatchSettingsSyncTime" reads a time of at most 5 minutes ago; if it does not, tap "WatchSettingsSync" and wait 10 s - Swipe right three times to the Balance page and wait until "WatchHomeBalanceSecondary" reads a fiat value, for up to 1 minute: QuickPay needs the rates - Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> 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 4 s - Verify the Balance page: "WatchHomeBalance" is listed - Verify "WatchSendHold" is not listed + Wait up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself diff --git a/journeys/wear/settings-import-units.xml b/journeys/wear/settings-import-units.xml index 5872ddfce2..0ed79ba213 100644 --- a/journeys/wear/settings-import-units.xml +++ b/journeys/wear/settings-import-units.xml @@ -4,10 +4,11 @@ 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: Phone settings on VSS, see journeys/wear/README.md › Phone settings on VSS, with Default Unit set to - the currency, Denomination set to Classic and Local Currency set to EUR on the phone, and the phone app closed. - Then Restored wallet on the watch with the same recovery phrase, see README › Restored wallet, with a balance above - 0. Backend: hosted regtest. + Precondition: Private settings wallet, see journeys/wear/README.md › Private settings wallet, never the public + test phrase. Phone settings on VSS, see README › Phone settings on VSS, with Default Unit set to the currency, + Denomination set to Classic and Local Currency set to EUR on the phone, and the phone app closed. Then that + wallet restored on the watch on the local ./spark stack with a balance above 0 (run receive-paid.xml first), see + README › Local ./spark stack. Restart the app (README › Restart) @@ -19,11 +20,6 @@ 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 - Tap "WatchHomeBalanceToggle" - Verify "WatchHomeBalanceSymbol" reads "₿" and "WatchHomeBalance" reads the balance with eight decimals - Restart the app (README › Restart) - Wait 30 s after "WatchHomeBalance" is listed, so the import ran - Verify "WatchHomeBalanceSymbol" still reads "₿": the wearer's swap lasts while the phone's setting stays the same + 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..84fd65d5f3 --- /dev/null +++ b/journeys/wear/settings-swap-survives-import.xml @@ -0,0 +1,20 @@ + + + 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 Balance page with "WatchHomeBalanceSymbol" reading "€" and the + loading ring stopped. + + + 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 + + From 42ffc1de84b9357ac7d205deb5b488c66d32756f Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 05:48:12 -0300 Subject: [PATCH 05/15] fix: keep quickpay from a restored send flow, run the settings import in the repo's own scope Co-Authored-By: Claude Fable 5.2 --- .../bitkit/wear/repositories/QuickPayRepo.kt | 7 +- .../wear/repositories/SettingsSyncRepo.kt | 102 +++++++++++------- .../bitkit/wear/services/PhoneBackupReader.kt | 4 + .../bitkit/wear/ui/screens/send/SendScreen.kt | 5 +- .../wear/ui/screens/send/SendViewModel.kt | 15 ++- .../wear/repositories/SettingsSyncRepoTest.kt | 79 +++++++++++++- .../wear/ui/screens/send/SendViewModelTest.kt | 32 +++++- 7 files changed, 190 insertions(+), 54 deletions(-) diff --git a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt index 411a0af35d..c30cfaad96 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -79,9 +79,10 @@ class QuickPayRepo internal constructor( * Brings what [reserve] reads up to date before it is asked, for a payment that arrives as the app starts or * returns: the import and the rates are then on their way but not in yet. When the last import has QuickPay on * and is older than [MAX_SETTINGS_AGE], it waits for an import, joining one that runs; when the rates are missing - * or older than [MAX_RATES_AGE], it fetches them. Both together take at most [INPUTS_TIMEOUT]. It decides - * nothing: whatever is still missing or old afterwards makes [reserve] answer no. A watch whose last import has - * QuickPay off, or that has none, never waits here. + * or older than [MAX_RATES_AGE], it fetches them. Both together take at most [INPUTS_TIMEOUT]: only the wait + * ends then, and an import still under way goes on and lands for the next payment. It decides nothing: + * whatever is still missing or old afterwards makes [reserve] answer no. A watch whose last import has QuickPay + * off, or that has none, never waits here. */ suspend fun awaitInputs(): Unit = withContext(ioDispatcher) { runSuspendCatching { diff --git a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt index 85a57a4b26..8f1eaf519d 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt @@ -1,13 +1,14 @@ package to.bitkit.wear.repositories import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.NonCancellable +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.withContext import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.data.ElapsedClock import to.bitkit.wear.data.SettingsStore @@ -49,7 +50,7 @@ class SettingsSyncRepo internal constructor( /** The key of the phone's settings backup, the name of its `BackupCategory.SETTINGS`. */ const val SETTINGS_KEY = "SETTINGS" - /** How long signing in to VSS and reading the backup may take. */ + /** How long an import waits for signing in to VSS and reading the backup. */ val READ_TIMEOUT = 30.seconds /** @@ -79,6 +80,12 @@ class SettingsSyncRepo internal constructor( 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]. */ @@ -88,16 +95,25 @@ class SettingsSyncRepo internal constructor( * 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 then stops by itself once the last import is too - * old ([QuickPayRepo.MAX_SETTINGS_AGE]). The read is given up as soon as the wallet stops being ready, as on a - * lock or a pause, so nothing derived from the seed outlives either. An import that a wallet wipe overtook is - * taken out again, so nothing of a removed wallet's settings stays. + * old ([QuickPayRepo.MAX_SETTINGS_AGE]). 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 = withContext(ioDispatcher) { - runSuspendCatching { mutex.withLock { syncLocked(isForced) } } - .onFailure { Logger.warn("Failed to import the phone's settings", it, context = TAG) } + 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) { @@ -106,33 +122,30 @@ class SettingsSyncRepo internal constructor( if (!isForced && isReadRecently(wipeToken)) return val seed = seedStore.load().getOrThrow() val backup = withTimeoutOrNull(READ_TIMEOUT) { readWhileReady(seed) } ?: throw SettingsSyncError.Timeout() - // From here the outcome is written whole, also when the caller goes away. - withContext(NonCancellable) { - 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) - } + 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() } - lastRead = wipeToken to clock.nowMs() - if (!sparkService.isCurrent(wipeToken)) { - settingsStore.clearPhoneSettings() - throw SparkError.WipeInProgress() + 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 { @@ -142,15 +155,24 @@ class SettingsSyncRepo internal constructor( /** * Reads the settings backup, or fails with [SettingsSyncError.NotReady] the moment the wallet is not ready any - * more. Either way the reader has shut its client down when this returns. + * 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 = channelFlow { - launch { send(runSuspendCatching { backupReader.read(seed, SETTINGS_KEY) }) } - launch { - walletRepo.walletState.first { it.status != WalletStatus.Ready } - send(Result.failure(SettingsSyncError.NotReady())) + 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() } - }.first() + } } sealed class SettingsSyncError(message: String) : AppError(message) { diff --git a/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt index 41c9355217..6f68ef81ec 100644 --- a/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt +++ b/wear/src/main/java/to/bitkit/wear/services/PhoneBackupReader.kt @@ -39,6 +39,10 @@ class PhoneBackupUnreadable : AppError("The phone's backup cannot be decrypted") * 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 { 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 2d5160cff2..d976eea637 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/screens/send/SendViewModel.kt @@ -52,7 +52,9 @@ import kotlin.time.Duration.Companion.seconds * QuickPay is asked only for a send the wearer is there for: one priced within [QUICKPAY_WINDOW] of its link, with * the app on screen, out of ambient mode and the watch unlocked all the while. A link that waited longer for the * wallet, as without a network, 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. + * so nothing is ever paid long after the wearer looked away. 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( @@ -88,6 +90,9 @@ class SendViewModel @Inject constructor( * 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() @@ -108,13 +113,17 @@ class SendViewModel @Inject constructor( /** 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. */ - private var wasAway = false + /** + * 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. + */ + 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( diff --git a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt index 1360b5ab67..191dc2314a 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt @@ -1,18 +1,22 @@ 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.never +import org.mockito.kotlin.timeout import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions @@ -31,16 +35,21 @@ 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", @@ -211,15 +220,66 @@ class SettingsSyncRepoTest : BaseUnitTest() { @Test fun `a read that takes too long is given up and changes nothing`() = test { - read = { awaitCancellation() } + 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) { @@ -264,13 +324,22 @@ class SettingsSyncRepoTest : BaseUnitTest() { } @Test - fun `a caller that goes away mid-read writes nothing`() = test { - read = { awaitCancellation() } + 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) - verify(settingsStore, never()).applyPhoneSettings(any(), any()) + assertTrue(next.await().isSuccess) + assertEquals(1, reads.size) + verify(settingsStore).applyPhoneSettings(SETTINGS, NOW) verifyNoMoreInteractions(settingsStore) } 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 0cc55b414d..05a8d1d9c3 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 @@ -63,8 +63,10 @@ class SendViewModelTest : BaseUnitTest() { whenever { paymentsRepo.skipConfirmation(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, @@ -183,6 +185,32 @@ class SendViewModelTest : BaseUnitTest() { 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(prepared)).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()) + verify(paymentsRepo, never()).send(any()) + + 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>>( From f9b2f647dbae30887b1bba7c7ac316faa064f7e2 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 05:48:13 -0300 Subject: [PATCH 06/15] docs: update wear settings sync docs and journeys for round 2 fixes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 38 ++++++++-- journeys/README.md | 2 +- journeys/wear/README.md | 80 ++++++++++++++++----- journeys/wear/quickpay-off-holds.xml | 7 +- journeys/wear/quickpay-on-app-start.xml | 15 ++-- journeys/wear/quickpay-over-limit-holds.xml | 10 +-- journeys/wear/quickpay-skips-hold.xml | 15 ++-- journeys/wear/receive-paid.xml | 8 ++- journeys/wear/settings-import-units.xml | 11 +-- 9 files changed, 134 insertions(+), 52 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index cc55fc050d..4546874f8f 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -214,7 +214,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 @@ -366,6 +368,11 @@ result screens, only when every one of these holds: wallet, as one opened without a network that connects minutes later by itself, always ends on the review and the hold, so nothing is paid after the wearer looked away. The phone does the same for a scan put off across its lock. The 30 s cover a wallet that connects and syncs as the link opens the app. +- 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 send the wearer left on the review or on a failure comes back on the review and the + hold, hours later too. - The phone's settings were imported at most 15 minutes ago, and QuickPay is on in them. The age is that of the watch's last read of the backup, not of the phone's upload: QuickPay turned off on the phone stops on the watch with the first import after the phone uploaded its settings, and within 15 minutes of the watch's last import @@ -381,7 +388,8 @@ A payment link usually opens the app, after a start or a long absence, and the i brings are then still on their way when the send is priced. So before it reads the limits the decision waits for them (`QuickPayRepo.awaitInputs`): when the last import has QuickPay on and is older than 15 minutes it joins the import under way, or starts one, and when the rates are missing or older than an hour it fetches them, both together -for 5 s at most, under the loading ring. It waits only then: a watch whose last import has QuickPay off, or that has +for 5 s at most, under the loading ring. After the 5 s only the wait ends: an import still under way goes on and +lands, so the next payment finds it and does not wait again. It waits only then: a watch whose last import has QuickPay off, or that has none, goes to the review at once, so QuickPay newly turned on at the phone applies from the payment after the next import. What is still missing after the wait answers no. The wait cannot turn into a late payment: it starts only inside the 30 s above, and the wearer has to be there still when it ends. @@ -398,6 +406,14 @@ backup the phone never wrote, an unreadable or newer backup, QuickPay values out - **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. @@ -440,15 +456,23 @@ from VSS and never writes there. 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 across a lock, a pause or a wipe. + 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. +- **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 or out of time, as a payment after its 5 s, 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; before a QuickPay decision whose import is too old (see QuickPay); 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. Never in the background or - in ambient mode, and never 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 the client is shut down with it. - Reading takes about 2 s; it is given up after 30 s. + 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 diff --git a/journeys/README.md b/journeys/README.md index cf898fdbe5..d3debdcb68 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -139,7 +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 recovery phrase, never the public test phrase, writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) | +| 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 e6e0b57951..20139d656d 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -130,10 +130,11 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `quickpay-over-limit-holds.xml` | local, and a phone that wrote its settings | yes, 12 000 sats | | `quickpay-off-holds.xml` | local, and a phone that wrote its settings, after `quickpay-skips-hold.xml` | yes, 2 000 sats | | `settings-import-units.xml` | local, a private phrase, and a phone that wrote its settings | yes, any balance above 0 | +| `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, a private phrase, and a phone that wrote its settings | yes, 2 000 sats | +| `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, a private phrase, and a phone that wrote its settings | yes, 12 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 @@ -237,7 +238,9 @@ A wallet restored by an earlier journey can stay: only [Fresh app](#fresh-app) a 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)). +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 @@ -246,22 +249,60 @@ never on the public test phrase. That phrase's settings backup is one object on 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. -1. Create a new wallet in a phone dev build, from its onboarding: a phrase nobody else has. Do not - reuse a phrase that holds or ever held real funds. -2. Read its 12 words at Settings › Security › Back up your wallet (`BackupWallet`). -3. Keep the words out of the repository, the journey files, logs, screenshots and pull requests. Hold them in a - shell variable for the session, read without echo: +The private wallet is the public test phrase with a passphrase that only this machine knows. With a passphrase the +phrase is another wallet, with a backup of its own that nobody else can name. No secret is read off a screen and +none is typed by hand, so an agent can set it up without ever seeing the passphrase. + +1. Make the passphrase, once per machine, in a file outside the repository that only you can read: + + ```bash + F=~/.config/bitkit-journeys/settings-passphrase + mkdir -p "${F%/*}" && chmod 700 "${F%/*}" + [ -s "$F" ] || (umask 077; LC_ALL=C tr -dc a-z0-9 "$F") + ``` + + It prints nothing and 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. Never print it: no `cat`, `echo` or `set -x` on it, and no screenshot, `android layout` or `uiautomator dump` + output while a passphrase field shows it. Never copy it into the repository, a journey file, a log or a pull + request. Every command below reads the file inside the command that uses it. +3. 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 - read -rs PHRASE # paste the 12 words, separated by spaces, then Enter + adb shell input text "$(cat ~/.config/bitkit-journeys/settings-passphrase)" ``` -4. Restore it on the watch as in [Restored wallet](#restored-wallet), typing `for w in $PHRASE; do … done` with the - loop of [Typing several words](#typing-several-words). -5. On the local `./spark` stack, `receive-paid.xml` funds it on the watch. + [Check it](#checking-the-passphrase), then tap `RestoreButton`. Leave the phone's settings at their defaults for + now and 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`, which reads `0` for a new wallet. +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 defaults. That journey expects "50 000", which is what a watch on + Bitcoin and Modern shows; after `settings-import-units.xml` set Classic, the same payment reads "0.00050000". +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. + +#### 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, without printing it: this prints only a count, which must be `1`. + +```bash +adb exec-out uiautomator dump /dev/tty | grep -c "text=\"$(cat ~/.config/bitkit-journeys/settings-passphrase)\"" +``` -One private wallet serves all six journeys. Remove it from the watch (`remove-wallet.xml` or -[Fresh app](#fresh-app)) before the journeys on the public phrase run again. +On `0`, clear the field, type again and check again. The proof that phone and watch hold the same wallet comes with +the first import: the watch logs `Imported the phone's settings` once the phone wrote its backup, and +`Found no settings backup of the phone` when the two differ. ### Phone settings on VSS @@ -273,13 +314,16 @@ names this precondition: ([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: the wallet created there, or the - same private phrase restored. Never restore the public test phrase 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. +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`. @@ -298,7 +342,7 @@ names this precondition: **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, as for [Funding the test wallet](#funding-the-test-wallet), must leave its units, currency and QuickPay at +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 diff --git a/journeys/wear/quickpay-off-holds.xml b/journeys/wear/quickpay-off-holds.xml index 7751ff4d4c..aa17ea6546 100644 --- a/journeys/wear/quickpay-off-holds.xml +++ b/journeys/wear/quickpay-off-holds.xml @@ -4,9 +4,10 @@ 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. - Then, on the phone with the same recovery phrase, turn QuickPay off, wait for the backup and close the phone app, - see journeys/wear/README.md › Phone settings on VSS. Watch: the + 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. diff --git a/journeys/wear/quickpay-on-app-start.xml b/journeys/wear/quickpay-on-app-start.xml index 0dcc4b5c00..73be03bd4c 100644 --- a/journeys/wear/quickpay-on-app-start.xml +++ b/journeys/wear/quickpay-on-app-start.xml @@ -2,16 +2,19 @@ A payment link that starts the app is paid under QuickPay too, although the last import of the phone's settings is too old by then: the send waits a moment for the import and the rates that the start brings, and then goes - out without the review and the hold. Emulator and physical watch. + 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, 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. + 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 watch that locked during + the 16 minutes: KEYCODE_WAKEUP lights the screen and unlocks nothing, and QuickPay never pays on a locked watch. + Use the emulator, which has no lock, or keep a physical watch on the wrist and unlocked for the whole wait. Run `adb shell am force-stop to.bitkit.dev` - Wait 16 minutes: the last import is then too old for QuickPay + Wait 16 minutes, as 16 waits of 1 minute and not one long sleep, touching nothing: the last import is then too old for QuickPay 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` diff --git a/journeys/wear/quickpay-over-limit-holds.xml b/journeys/wear/quickpay-over-limit-holds.xml index bd56c15e53..3fc1dc40f8 100644 --- a/journeys/wear/quickpay-over-limit-holds.xml +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -3,10 +3,12 @@ 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: as quickpay-skips-hold.xml: Private settings wallet, never the public test phrase; Phone settings - on VSS with QuickPay on at $1 and 5×, see journeys/wear/README.md › Phone settings on VSS; that wallet restored - on the watch on the local ./spark stack with at least 12 000 sats, the app open on the Balance page and the - loading ring stopped. 10 000 sats are above $1 while a bitcoin costs more than $10 000. README › Holding to pay + 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. diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml index fca60a96b0..513ea02e9d 100644 --- a/journeys/wear/quickpay-skips-hold.xml +++ b/journeys/wear/quickpay-skips-hold.xml @@ -4,12 +4,15 @@ 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: Private settings wallet, see journeys/wear/README.md › Private settings wallet, never the public - test phrase. Phone settings on VSS, see README › Phone settings on VSS, with QuickPay on at $1 and the daily limit - at 5× on the phone, and the phone app closed. Then that wallet restored on the watch on the local ./spark stack - with at least 2 000 sats (run receive-paid.xml first), see README › Local ./spark stack, with the app open on the - Balance page and the loading ring stopped. 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. + 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) 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 index 0ed79ba213..2d14787e86 100644 --- a/journeys/wear/settings-import-units.xml +++ b/journeys/wear/settings-import-units.xml @@ -4,11 +4,12 @@ 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: Private settings wallet, see journeys/wear/README.md › Private settings wallet, never the public - test phrase. Phone settings on VSS, see README › Phone settings on VSS, with Default Unit set to the currency, - Denomination set to Classic and Local Currency set to EUR on the phone, and the phone app closed. Then that - wallet restored on the watch on the local ./spark stack with a balance above 0 (run receive-paid.xml first), see - README › Local ./spark stack. + 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) From f5927d1d47a61a68b4aa6d3ef08388a82dada9fa Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 06:22:07 -0300 Subject: [PATCH 07/15] fix: match the phone's quickpay rules, ignore links from recents Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/wear/data/QuickPaySpendStore.kt | 35 ++- .../java/to/bitkit/wear/models/Payments.kt | 5 +- .../bitkit/wear/repositories/CurrencyRepo.kt | 11 - .../bitkit/wear/repositories/PaymentsRepo.kt | 58 +++-- .../bitkit/wear/repositories/QuickPayRepo.kt | 128 +++++----- .../wear/repositories/SettingsSyncRepo.kt | 5 +- .../java/to/bitkit/wear/ui/LaunchRequest.kt | 6 + .../java/to/bitkit/wear/ui/MainActivity.kt | 4 +- .../wear/ui/screens/send/SendViewModel.kt | 5 +- .../wear/data/QuickPaySpendStoreTest.kt | 84 +++++-- .../wear/repositories/CurrencyRepoTest.kt | 32 +-- .../wear/repositories/PaymentsRepoTest.kt | 152 +++++++++--- .../wear/repositories/QuickPayRepoTest.kt | 221 ++++++++---------- .../to/bitkit/wear/ui/ReplayedLaunchTest.kt | 20 ++ .../wear/ui/screens/send/SendViewModelTest.kt | 33 +-- 15 files changed, 455 insertions(+), 344 deletions(-) create mode 100644 wear/src/test/java/to/bitkit/wear/ui/ReplayedLaunchTest.kt diff --git a/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt index ed986df92b..959a3771fd 100644 --- a/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt @@ -11,11 +11,14 @@ 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 whether - * it was added. A day earlier than the one last counted does not start a new count, so setting the watch's date - * back frees nothing. + * 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): Boolean + 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. */ @@ -26,18 +29,26 @@ class SettingsQuickPaySpendStore @Inject constructor( private val dayKey = stringPreferencesKey("quickpay_spend_day") private val centsKey = longPreferencesKey("quickpay_spend_cents") - override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): Boolean { - if (cents <= 0 || capCents <= 0) return false - var isReserved = false + 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 isNewDay = countedDay == null || dayKey > countedDay - val spent = if (isNewDay) 0L else prefs[centsKey] ?: 0L + 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] = if (isNewDay) dayKey else requireNotNull(countedDay) + prefs[this.dayKey] = day prefs[centsKey] = spent + cents - isReserved = true + 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) } - return isReserved } } 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 7a14b0a2c1..2438050276 100644 --- a/wear/src/main/java/to/bitkit/wear/models/Payments.kt +++ b/wear/src/main/java/to/bitkit/wear/models/Payments.kt @@ -75,8 +75,9 @@ class PreparedSend internal constructor( */ internal val transferKey: String, /** - * Whether this pays a BOLT11 invoice that carries its amount, the only kind of request QuickPay covers. An - * amount the wearer typed is never fixed, and neither is any LNURL or Spark address payment. + * 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, ) { diff --git a/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt index ac72432f9a..254484d59d 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/CurrencyRepo.kt @@ -7,7 +7,6 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext -import to.bitkit.wear.data.ElapsedClock import to.bitkit.wear.data.RatesHttpClient import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.di.IoDispatcher @@ -16,15 +15,12 @@ import to.bitkit.wear.models.FxRate import to.bitkit.wear.utils.Logger import javax.inject.Inject import javax.inject.Singleton -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds @Singleton class CurrencyRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, private val ratesHttpClient: RatesHttpClient, private val settingsStore: SettingsStore, - private val clock: ElapsedClock, ) { companion object { private const val TAG = "CurrencyRepo" @@ -33,17 +29,10 @@ class CurrencyRepo @Inject constructor( private val _rates = MutableStateFlow>(emptyList()) val rates: StateFlow> = _rates.asStateFlow() - @Volatile - private var ratesFetchedAtMs: Long? = null - - /** How long ago [rates] were fetched, the time the watch slept included, or null when they never were. */ - fun ratesAge(): Duration? = ratesFetchedAtMs?.let { (clock.nowMs() - it).milliseconds } - suspend fun refresh(): Result = withContext(ioDispatcher) { runSuspendCatching { val tickers = ratesHttpClient.fetchLatestRates().tickers _rates.update { tickers } - ratesFetchedAtMs = clock.nowMs() } } 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 bff3808cb4..1e18eea041 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -50,6 +50,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 @@ -139,29 +140,39 @@ 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 [prepared] goes out without the hold to pay (QuickPay). This is the one place that decides it. It does - * only when all of these hold: + * 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; - * - it pays a BOLT11 invoice that carries its amount: an amount the wearer typed is always reviewed, since the - * review is the one place that shows what was typed, its fee and its payee, and so is every LNURL, Lightning - * address and Spark address payment; - * - [QuickPayRepo.reserve] takes the payment's cost, fee included, under the phone's QuickPay settings, after - * [QuickPayRepo.awaitInputs] gave an import and rates that are on their way a moment to arrive. + * - 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`. * - * 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. Anything that cannot be told answers no, and - * the wearer holds to pay. + * 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. Anything that cannot be told answers no, + * and the wearer holds to pay. */ - suspend fun skipConfirmation(prepared: PreparedSend): Boolean = withContext(ioDispatcher) { - if (!isReady() || sparkService.isWiping) return@withContext false - if (!prepared.isAmountFixed) return@withContext false - quickPayRepo.awaitInputs() - val isAllowed = quickPayRepo.reserve(prepared.totalSats) - // The wallet may have locked, paused or been wiped while the limit was awaited and read. - isAllowed && isReady() && !sparkService.isWiping - } + suspend fun skipConfirmation(prepared: PreparedSend, canSend: () -> Boolean): Boolean = + withContext(ioDispatcher) { + if (!isReady() || sparkService.isWiping) return@withContext false + if (!prepared.isAmountFixed) return@withContext false + quickPayRepo.awaitRate() + 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 + } /** * Creates an amountless BOLT11 invoice paid into the Spark balance, valid for [INVOICE_EXPIRY_SECS], and @@ -307,6 +318,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 -> { @@ -424,6 +436,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 anything but [SendError.Unknown]. */ suspend fun send(prepared: PreparedSend): Result = sendScope.async { runSuspendCatching { @@ -449,6 +464,13 @@ 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. + val reservation = quickPayReservations.remove(prepared.transferKey) + if (reservation != null && result.isFailure && result.exceptionOrNull() !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 index c30cfaad96..5594ef517f 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -1,9 +1,7 @@ package to.bitkit.wear.repositories import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext @@ -13,7 +11,11 @@ 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 @@ -21,13 +23,12 @@ import java.time.Instant import java.time.ZoneId import javax.inject.Inject import javax.inject.Singleton -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.minutes 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. - * Everything that is missing, stale or unreadable answers no. + * 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( @@ -35,7 +36,6 @@ class QuickPayRepo internal constructor( private val settingsStore: SettingsStore, private val currencyRepo: CurrencyRepo, private val spendStore: QuickPaySpendStore, - private val settingsSyncRepo: SettingsSyncRepo, private val nowMs: () -> Long, private val zone: () -> ZoneId, ) { @@ -43,17 +43,8 @@ class QuickPayRepo internal constructor( private const val TAG = "QuickPayRepo" private const val CENTS_SCALE = 2 - /** - * How old the last import of the phone's settings may be. A watch that could not read them for longer asks - * for the hold again, so QuickPay turned off on the phone stops on the watch within this time. - */ - val MAX_SETTINGS_AGE = 15.minutes - - /** How old the exchange rates may be for the limit, which is in dollars, to be checked against them. */ - val MAX_RATES_AGE = 1.hours - - /** How long [awaitInputs] holds a payment back for a new import and new rates before it goes on without. */ - val INPUTS_TIMEOUT = 5.seconds + /** How long [awaitRate] holds a payment back for the dollar rate before it goes on without. */ + val RATE_TIMEOUT = 5.seconds } @Inject @@ -62,13 +53,11 @@ class QuickPayRepo internal constructor( settingsStore: SettingsStore, currencyRepo: CurrencyRepo, spendStore: QuickPaySpendStore, - settingsSyncRepo: SettingsSyncRepo, ) : this( ioDispatcher, settingsStore, currencyRepo, spendStore, - settingsSyncRepo, System::currentTimeMillis, ZoneId::systemDefault, ) @@ -76,65 +65,66 @@ class QuickPayRepo internal constructor( private val mutex = Mutex() /** - * Brings what [reserve] reads up to date before it is asked, for a payment that arrives as the app starts or - * returns: the import and the rates are then on their way but not in yet. When the last import has QuickPay on - * and is older than [MAX_SETTINGS_AGE], it waits for an import, joining one that runs; when the rates are missing - * or older than [MAX_RATES_AGE], it fetches them. Both together take at most [INPUTS_TIMEOUT]: only the wait - * ends then, and an import still under way goes on and lands for the next payment. It decides nothing: - * whatever is still missing or old afterwards makes [reserve] answer no. A watch whose last import has QuickPay - * off, or that has none, never waits here. + * 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 awaitInputs(): Unit = withContext(ioDispatcher) { + suspend fun awaitRate(): Unit = withContext(ioDispatcher) { runSuspendCatching { - val settings = settingsStore.data.first() - if (settings.quickPay?.isEnabled != true) return@runSuspendCatching - val isImportFresh = settings.phoneSyncedAtMs?.let { isFresh(nowMs() - it) } == true - val areRatesFresh = currencyRepo.ratesAge()?.let { it <= MAX_RATES_AGE } == true - withTimeoutOrNull(INPUTS_TIMEOUT) { - coroutineScope { - if (!isImportFresh) launch { settingsSyncRepo.sync() } - if (!areRatesFresh) launch { currencyRepo.refresh() } - } - } - }.onFailure { Logger.warn("Failed to refresh what QuickPay reads", it, context = TAG) } + 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) } } - private fun isFresh(settingsAgeMs: Long): Boolean = settingsAgeMs in 0..MAX_SETTINGS_AGE.inWholeMilliseconds - /** - * Whether a payment that costs [totalSats], its fee included, may skip the hold to pay, and if so counts it - * against today's limit. It may when QuickPay was imported from the phone within [MAX_SETTINGS_AGE] and is on, - * a dollar rate no older than [MAX_RATES_AGE] values the payment at no more than the phone's QuickPay amount, and - * today's QuickPay payments from this watch stay within the phone's daily limit with it. A yes is counted - * whether or not the payment then succeeds. Any failure to read or count answers no. + * 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 at the dollar rate, 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(totalSats: ULong): Boolean = withContext(ioDispatcher) { - runSuspendCatching { mutex.withLock { reserveLocked(totalSats) } } + suspend fun reserve(amountSats: ULong): QuickPayReservation? = withContext(ioDispatcher) { + runSuspendCatching { mutex.withLock { reserveLocked(amountSats) } } .onFailure { Logger.warn("Failed to check QuickPay", it, context = TAG) } - .getOrDefault(false) + .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(totalSats: ULong): Boolean { - val settings = settingsStore.data.first() - val quickPay = settings.quickPay?.takeIf { it.isEnabled } ?: return false - val now = nowMs() - if (!isFresh(now - (settings.phoneSyncedAtMs ?: return false))) return false - val ratesAge = currencyRepo.ratesAge() ?: return false - if (ratesAge > MAX_RATES_AGE) return false - val rate = currencyRepo.rates.value.rateFor(USD)?.lastPrice?.toBigDecimalOrNull() ?: return false - val cents = usdCents(totalSats, rate) ?: return false - if (cents > quickPay.thresholdCents) return false - val dayKey = Instant.ofEpochMilli(now).atZone(zone()).toLocalDate().toString() - return spendStore.reserve(dayKey, cents, quickPay.dailyCapCents) + 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 cents = reserveCents(amountSats, rate, quickPay) ?: return null + val today = Instant.ofEpochMilli(nowMs()).atZone(zone()).toLocalDate().toString() + val dayKey = spendStore.reserve(today, cents, quickPay.dailyCapCents) ?: return null + return QuickPayReservation(dayKey, cents) } - /** [sats] at [usdPerBtc] in US cents, rounded up so a payment never counts for less than it is worth. */ - private fun usdCents(sats: ULong, usdPerBtc: BigDecimal): Long? { - if (sats == 0uL || sats > Long.MAX_VALUE.toULong() || usdPerBtc.signum() <= 0) return null - val cents = BigDecimal.valueOf(sats.toLong()) - .multiply(usdPerBtc) - .movePointLeft(BTC_SCALE - CENTS_SCALE) - .setScale(0, RoundingMode.CEILING) - return runCatching { cents.longValueExact() }.getOrNull() + 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() + } + + private fun reserveCents(amountSats: ULong, rate: FxRate, quickPay: QuickPayLimits): Long? { + val fiat = fiatValue(amountSats.toLong(), rate) ?: return null + val cents = fiat.movePointRight(CENTS_SCALE).setScale(0, RoundingMode.HALF_UP).toLong() + return minOf(cents, quickPay.thresholdCents).coerceAtLeast(1L) } } + +/** 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 index 8f1eaf519d..2b1f506528 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt @@ -94,9 +94,8 @@ class SettingsSyncRepo internal constructor( /** * 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 then stops by itself once the last import is too - * old ([QuickPayRepo.MAX_SETTINGS_AGE]). An import that a wallet wipe overtook is taken out again, so nothing of a - * removed wallet's settings stays. + * 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 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..1c955cb965 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 that once opened the app, sent again + * long after the wearer saw it. Such an intent is a plain launch. + */ +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 40929d7866..0d4811e771 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/MainActivity.kt @@ -46,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 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 d976eea637..83ca48d9ee 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 @@ -117,6 +117,7 @@ class SendViewModel @Inject constructor( * 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. */ @@ -224,8 +225,8 @@ class SendViewModel @Inject constructor( prepared = 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. - if (isQuickPayOpen() && paymentsRepo.skipConfirmation(result) && isAttended()) { + // have looked away while it was answered, hence the second look, which the repo takes before it says yes. + if (isQuickPayOpen() && paymentsRepo.skipConfirmation(result, ::isAttended)) { Logger.info("Skipped the hold to pay under QuickPay", context = TAG) send(result) return diff --git a/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt index cf9459d7c1..b2e81f9d82 100644 --- a/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt @@ -9,8 +9,9 @@ import org.junit.Test import org.junit.rules.TemporaryFolder import to.bitkit.wear.test.BaseUnitTest import java.io.File -import kotlin.test.assertFalse -import kotlin.test.assertTrue +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 { @@ -18,15 +19,20 @@ class FakeQuickPaySpendStore : QuickPaySpendStore { var spentCents = 0L var failure: Throwable? = null - override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): Boolean { + override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? { failure?.let { throw it } - if (cents <= 0 || capCents <= 0) return false + 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 false + if (cents > capCents - spent) return null if (isNewDay) day = dayKey spentCents = spent + cents - return true + return day + } + + override suspend fun release(dayKey: String, cents: Long) { + failure?.let { throw it } + if (dayKey == day) spentCents = (spentCents - cents).coerceAtLeast(0L) } } @@ -46,14 +52,14 @@ class QuickPaySpendStoreTest : BaseUnitTest() { @Test fun `a day takes payments up to its cap and not a cent more, also after a restart`() = test { val sut = open().first - assertTrue(sut.reserve(TODAY, cents = 400, capCents = 1_000)) - assertTrue(sut.reserve(TODAY, cents = 500, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 400, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 500, capCents = 1_000)) close() val next = open().first - assertFalse(next.reserve(TODAY, cents = 101, capCents = 1_000)) - assertTrue(next.reserve(TODAY, cents = 100, capCents = 1_000)) - assertFalse(next.reserve(TODAY, cents = 1, capCents = 1_000)) + 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() } @@ -61,30 +67,58 @@ class QuickPaySpendStoreTest : BaseUnitTest() { fun `a refused payment counts for nothing`() = test { val sut = open().first - assertFalse(sut.reserve(TODAY, cents = 1_001, capCents = 1_000)) + assertNull(sut.reserve(TODAY, cents = 1_001, capCents = 1_000)) - assertTrue(sut.reserve(TODAY, cents = 1_000, 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 - assertTrue(sut.reserve(TOMORROW, cents = 1_000, capCents = 1_000)) + 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)) - assertFalse(sut.reserve(TODAY, cents = 1, capCents = 1_000)) - assertFalse(sut.reserve(TOMORROW, 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)) - assertTrue(sut.reserve("2026-11-30", cents = 1_000, 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 - assertTrue(sut.reserve(TODAY, cents = 800, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 800, capCents = 1_000)) - assertFalse(sut.reserve(TODAY, cents = 1, capCents = 500)) + assertNull(sut.reserve(TODAY, cents = 1, capCents = 500)) close() } @@ -92,21 +126,21 @@ class QuickPaySpendStoreTest : BaseUnitTest() { fun `nothing and less than nothing are refused`() = test { val sut = open().first - assertFalse(sut.reserve(TODAY, cents = 0, capCents = 1_000)) - assertFalse(sut.reserve(TODAY, cents = -5, capCents = 1_000)) - assertFalse(sut.reserve(TODAY, cents = 1, capCents = 0)) - assertFalse(sut.reserve(TODAY, cents = Long.MAX_VALUE, capCents = 1_000)) + 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() - assertTrue(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) settings.finishWipe() - assertTrue(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) + assertNotNull(sut.reserve(TODAY, cents = 1_000, capCents = 1_000)) close() } diff --git a/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt index b61fc95e93..470a6d5b37 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/CurrencyRepoTest.kt @@ -9,45 +9,15 @@ import org.mockito.kotlin.whenever import to.bitkit.wear.data.RatesHttpClient import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings -import to.bitkit.wear.models.FxRateResponse import to.bitkit.wear.models.PrimaryDisplay -import to.bitkit.wear.models.rate import to.bitkit.wear.security.SeedStoreError import to.bitkit.wear.test.BaseUnitTest -import java.io.IOException -import kotlin.test.assertEquals import kotlin.test.assertIs -import kotlin.test.assertNull import kotlin.test.assertTrue -import kotlin.time.Duration -import kotlin.time.Duration.Companion.hours class CurrencyRepoTest : BaseUnitTest() { private val settingsStore = mock() - private val ratesHttpClient = mock() - private var elapsedMs = 5_000L - private val sut by lazy { CurrencyRepo(testDispatcher, ratesHttpClient, settingsStore) { elapsedMs } } - - @Test - fun `the rates' age counts from their fetch on the clock that runs through sleep`() = test { - whenever(ratesHttpClient.fetchLatestRates()).thenReturn(FxRateResponse(listOf(rate("100000")))) - assertNull(sut.ratesAge()) - - assertTrue(sut.refresh().isSuccess) - assertEquals(Duration.ZERO, sut.ratesAge()) - - elapsedMs += 3.hours.inWholeMilliseconds - assertEquals(3.hours, sut.ratesAge()) - } - - @Test - fun `a fetch that fails leaves the rates' age as it was`() = test { - whenever(ratesHttpClient.fetchLatestRates()).thenAnswer { throw IOException("offline") } - - assertTrue(sut.refresh().isFailure) - - assertNull(sut.ratesAge()) - } + private val sut by lazy { CurrencyRepo(testDispatcher, mock(), settingsStore) } @Test fun `switching the unit stores fiat first when bitcoin was first, and back`() = test { 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 d07c91d1a1..ca0e4613de 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -72,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() @@ -543,80 +544,113 @@ class PaymentsRepoTest : BaseUnitTest() { } @Test - fun `quickpay skips the hold for an invoice with an amount, at its cost with the fee`() = test { - whenever(quickPayRepo.reserve(500uL + FEE)).thenReturn(true) + 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())) + assertTrue(sut.skipConfirmation(preparedSend()) { true }) verify(quickPayRepo, times(1)).reserve(any()) + verify(quickPayRepo, never()).release(any()) } @Test - fun `quickpay waits for a running import and the rates before it reads the limits`() = test { - whenever(quickPayRepo.reserve(any())).thenReturn(true) + fun `quickpay fetches a missing rate before it reads the limits`() = test { + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) - sut.skipConfirmation(preparedSend()) + sut.skipConfirmation(preparedSend()) { true } val order = inOrder(quickPayRepo) - order.verify(quickPayRepo).awaitInputs() + order.verify(quickPayRepo).awaitRate() order.verify(quickPayRepo).reserve(any()) } @Test - fun `quickpay holds when the wallet stopped being ready while it waited for the import`() = test { - whenever(quickPayRepo.reserve(any())).thenReturn(true) - whenever(quickPayRepo.awaitInputs()).doSuspendableAnswer { + 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())) + assertFalse(sut.skipConfirmation(preparedSend()) { true }) } @Test fun `quickpay holds when the limits say no`() = test { - whenever(quickPayRepo.reserve(any())).thenReturn(false) + whenever(quickPayRepo.reserve(any())).thenReturn(null) - assertFalse(sut.skipConfirmation(preparedSend())) + 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(true) + 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)) + assertFalse(sut.skipConfirmation(amountless) { true }) + assertFalse(sut.skipConfirmation(typed) { true }) - verify(quickPayRepo, never()).awaitInputs() + verify(quickPayRepo, never()).awaitRate() verify(quickPayRepo, never()).reserve(any()) } @Test - fun `quickpay never skips the hold for a spark address or an lnurl payment`() = test { - whenever(quickPayRepo.reserve(any())).thenReturn(true) + 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 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() - val fixed = SendRequest.Lnurl(lnurl(), minSats = 15uL, maxSats = 15uL, payee = null) - 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)) - val lnurl = sut.prepare(fixed).getOrThrow() - assertFalse(sut.skipConfirmation(transfer)) - assertFalse(sut.skipConfirmation(lnurl)) + 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(true) + 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), "$status") + assertFalse(sut.skipConfirmation(prepared) { true }, "$status") } verify(quickPayRepo, never()).reserve(any()) @@ -626,20 +660,67 @@ class PaymentsRepoTest : BaseUnitTest() { 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)) + 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) } - true + RESERVATION } - assertFalse(sut.skipConfirmation(prepared)) + 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 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(true) + whenever(quickPayRepo.reserve(any())).thenReturn(RESERVATION) ownInvoices.add(PAYMENT_HASH, SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY) assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) @@ -1268,6 +1349,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 index 9281e72b68..85b6cf8f9d 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -1,6 +1,5 @@ package to.bitkit.wear.repositories -import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation @@ -9,7 +8,6 @@ import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.update import org.junit.Before import org.junit.Test -import org.mockito.kotlin.any import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -26,10 +24,11 @@ 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 +import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.milliseconds 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. */ @@ -45,12 +44,10 @@ class QuickPayRepoTest : BaseUnitTest() { private val settingsStore = mock() private val currencyRepo = mock() private val spend = FakeQuickPaySpendStore() - private val settingsSyncRepo = mock() 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 var ratesAge: Duration? = 1.minutes private lateinit var sut: QuickPayRepo @@ -58,110 +55,75 @@ class QuickPayRepoTest : BaseUnitTest() { fun setUp() { whenever(settingsStore.data).thenReturn(settings) whenever(currencyRepo.rates).thenReturn(rates) - whenever(currencyRepo.ratesAge()).thenAnswer { ratesAge } - whenever { settingsSyncRepo.sync() }.thenReturn(Result.success(Unit)) whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) - sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, settingsSyncRepo, { now }, { zone }) - } - - private fun makeImportStale() { - now = NOW + QuickPayRepo.MAX_SETTINGS_AGE.inWholeMilliseconds + 1 - } - - @Test - fun `an import still under way when the payment is priced is waited for, and then decides`() = test { - makeImportStale() - val imported = CompletableDeferred() - whenever(settingsSyncRepo.sync()).doSuspendableAnswer { - imported.await() - settings.update { it.copy(phoneSyncedAtMs = now) } - Result.success(Unit) - } - assertFalse(sut.reserve(1uL)) - - val waiting = async { sut.awaitInputs() } - assertFalse(waiting.isCompleted) - - imported.complete(Unit) - waiting.await() - - assertTrue(sut.reserve(FIVE_DOLLARS)) - verify(currencyRepo, never()).refresh() + sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, { now }, { zone }) } @Test - fun `missing or old rates are fetched before the payment is decided`() = 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 { - ratesAge = Duration.ZERO + rates.update { listOf(rate("100000")) } Result.success(Unit) } - for (age in listOf(null, QuickPayRepo.MAX_RATES_AGE + 1.milliseconds)) { - ratesAge = age - sut.awaitInputs() + sut.awaitRate() - assertTrue(sut.reserve(1uL), "$age") - } - verify(currencyRepo, times(2)).refresh() - verify(settingsSyncRepo, never()).sync(any()) + assertNotNull(sut.reserve(1uL)) + verify(currencyRepo, times(1)).refresh() } @Test - fun `the wait for an import and rates ends after five seconds and the payment then holds`() = test { - makeImportStale() - ratesAge = null - whenever(settingsSyncRepo.sync()).doSuspendableAnswer { awaitCancellation() } + 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.awaitInputs() } - testScheduler.advanceTimeBy(QuickPayRepo.INPUTS_TIMEOUT.inWholeMilliseconds - 1) + val waiting = async { sut.awaitRate() } + testScheduler.advanceTimeBy(QuickPayRepo.RATE_TIMEOUT.inWholeMilliseconds - 1) assertFalse(waiting.isCompleted) testScheduler.advanceTimeBy(2) assertTrue(waiting.isCompleted) - assertFalse(sut.reserve(1uL)) + assertNull(sut.reserve(1uL)) assertEquals(0L, spend.spentCents) } @Test - fun `an import that fails ends the wait and the payment holds`() = test { - makeImportStale() - whenever(settingsSyncRepo.sync()).thenReturn(Result.failure(IOException("offline"))) - - sut.awaitInputs() + fun `no rate is fetched with one at hand, with quickpay off or before any import`() = test { + sut.awaitRate() - assertFalse(sut.reserve(1uL)) - } - - @Test - fun `nothing is waited for with a fresh import and rates, with quickpay off or before any import`() = test { - sut.awaitInputs() - - makeImportStale() - ratesAge = null + rates.update { emptyList() } settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } - sut.awaitInputs() + sut.awaitRate() settings.update { WatchSettings() } - sut.awaitInputs() + sut.awaitRate() whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) - sut.awaitInputs() + sut.awaitRate() - verify(settingsSyncRepo, never()).sync(any()) 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 { - assertFalse(sut.reserve(FIVE_DOLLARS + 1uL)) + assertNull(sut.reserve(FIVE_DOLLARS + 1uL)) assertEquals(0L, spend.spentCents) - assertTrue(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(FIVE_DOLLARS)) assertEquals(500L, spend.spentCents) } @Test fun `the smallest payment skips the hold and counts as a whole cent`() = test { - assertTrue(sut.reserve(1uL)) + assertNotNull(sut.reserve(1uL)) assertEquals(1L, spend.spentCents) } @@ -170,100 +132,119 @@ class QuickPayRepoTest : BaseUnitTest() { fun `nothing skips the hold before the phone's settings were ever imported`() = test { settings.update { WatchSettings() } - assertFalse(sut.reserve(1uL)) - assertFalse(sut.reserve(FIVE_DOLLARS)) + 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)) } - assertFalse(sut.reserve(1uL)) + assertNull(sut.reserve(1uL)) } @Test - fun `limits without the time of their import skip nothing`() = test { - settings.update { it.copy(phoneSyncedAtMs = null) } + 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) - assertFalse(sut.reserve(1uL)) + rates.update { listOf(rate("100000")) } + assertNotNull(sut.reserve(1uL)) } @Test - fun `an import older than fifteen minutes, or from the future, skips nothing`() = test { - now = NOW + QuickPayRepo.MAX_SETTINGS_AGE.inWholeMilliseconds - assertTrue(sut.reserve(1uL)) + 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) + } - now += 1 - assertFalse(sut.reserve(1uL)) + @Test + fun `a payment counts for no more than the phone's amount`() = 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")) } - now = NOW - 1 - assertFalse(sut.reserve(1uL)) + assertEquals(500L, sut.reserve(167uL)?.cents) + assertNull(sut.reserve(168uL)) } @Test - fun `without a fresh dollar rate nothing skips the hold`() = test { - ratesAge = null - assertFalse(sut.reserve(1uL)) + 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)) - ratesAge = QuickPayRepo.MAX_RATES_AGE + 1.milliseconds - assertFalse(sut.reserve(1uL)) + sut.release(failed) - ratesAge = QuickPayRepo.MAX_RATES_AGE - rates.update { listOf(rate("90000", quote = "EUR")) } - assertFalse(sut.reserve(1uL)) + assertEquals(1_000L, spend.spentCents) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + } - for (price in listOf("n/a", "0", "-100000", "")) { - rates.update { listOf(rate(price)) } - assertFalse(sut.reserve(1uL), price) - } - assertEquals(0L, spend.spentCents) + @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)) - rates.update { listOf(rate("100000")) } - assertTrue(sut.reserve(1uL)) + 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")) } - assertFalse(sut.reserve(2_501uL)) - assertTrue(sut.reserve(2_500uL)) + assertNull(sut.reserve(2_501uL)) + assertNotNull(sut.reserve(2_500uL)) } @Test fun `no amount and an absurd amount skip nothing`() = test { - assertFalse(sut.reserve(0uL)) - assertFalse(sut.reserve(ULong.MAX_VALUE)) - assertFalse(sut.reserve(Long.MAX_VALUE.toULong())) + 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) { assertTrue(sut.reserve(FIVE_DOLLARS), "payment $it") } + repeat(3) { assertNotNull(sut.reserve(FIVE_DOLLARS), "payment $it") } - assertFalse(sut.reserve(1uL)) + assertNull(sut.reserve(1uL)) assertEquals(1_500L, spend.spentCents) } @Test fun `a payment that would pass the daily limit is refused whole`() = test { - assertTrue(sut.reserve(FIVE_DOLLARS)) - assertTrue(sut.reserve(FIVE_DOLLARS)) - assertTrue(sut.reserve(4_000uL)) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(4_000uL)) - assertFalse(sut.reserve(1_001uL)) - assertTrue(sut.reserve(1_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) } - assertFalse(sut.reserve(1uL)) + assertNull(sut.reserve(1uL)) now = NOW + 12.hours.inWholeMilliseconds - settings.update { it.copy(phoneSyncedAtMs = now) } - assertTrue(sut.reserve(FIVE_DOLLARS)) + assertNotNull(sut.reserve(FIVE_DOLLARS)) assertEquals("2026-11-29", spend.day) } @@ -271,28 +252,26 @@ class QuickPayRepoTest : BaseUnitTest() { 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) { assertTrue(sut.reserve(FIVE_DOLLARS)) } + 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 - settings.update { it.copy(phoneSyncedAtMs = now) } - assertFalse(sut.reserve(1uL)) + 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 - settings.update { it.copy(phoneSyncedAtMs = now) } - assertTrue(sut.reserve(FIVE_DOLLARS)) + 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") - assertFalse(sut.reserve(1uL)) + assertNull(sut.reserve(1uL)) spend.failure = null whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) - assertFalse(sut.reserve(1uL)) + assertNull(sut.reserve(1uL)) } } 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/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index 05a8d1d9c3..35b9201890 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 @@ -14,6 +14,7 @@ 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 @@ -60,7 +61,7 @@ class SendViewModelTest : BaseUnitTest() { whenever(walletRepo.walletState).thenReturn(walletState) whenever(currencyRepo.rates).thenReturn(MutableStateFlow(emptyList())) whenever(settingsStore.data).thenReturn(flowOf(WatchSettings())) - whenever { paymentsRepo.skipConfirmation(any()) }.thenReturn(false) + whenever { paymentsRepo.skipConfirmation(any(), any()) }.thenReturn(false) } private fun createSut( @@ -133,14 +134,14 @@ class SendViewModelTest : BaseUnitTest() { val prepared = prepared() stubInvoice(prepared) val sent = CompletableDeferred>() - whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(true) + 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(prepared) + verify(paymentsRepo, times(1)).skipConfirmation(eq(prepared), any()) sent.complete(Result.success(payment(PaymentState.Completed))) @@ -155,7 +156,7 @@ class SendViewModelTest : BaseUnitTest() { walletState.update { it.copy(status = status) } val prepared = prepared() stubInvoice(prepared) - whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(true) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) whenever(paymentsRepo.send(prepared)).doSuspendableAnswer { awaitCancellation() } val sut = createSut() @@ -172,7 +173,7 @@ class SendViewModelTest : BaseUnitTest() { for (status in listOf(WalletStatus.Offline, WalletStatus.Error, WalletStatus.Connecting)) { walletState.update { it.copy(status = status) } stubInvoice(prepared()) - whenever(paymentsRepo.skipConfirmation(any())).thenReturn(true) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) val sut = createSut() elapsedMs += SendViewModel.QUICKPAY_WINDOW.inWholeMilliseconds + 1 @@ -181,7 +182,7 @@ class SendViewModelTest : BaseUnitTest() { assertIs(sut.uiState.value.step, "$status") assertTrue(sut.uiState.value.isHoldEnabled) } - verify(paymentsRepo, never()).skipConfirmation(any()) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) verify(paymentsRepo, never()).send(any()) } @@ -189,7 +190,7 @@ class SendViewModelTest : BaseUnitTest() { 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(prepared)).thenReturn(true) + 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) @@ -203,7 +204,7 @@ class SendViewModelTest : BaseUnitTest() { assertIs(sut.uiState.value.step) assertTrue(sut.uiState.value.isHoldEnabled) - verify(paymentsRepo, never()).skipConfirmation(any()) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) verify(paymentsRepo, never()).send(any()) sut.onHoldComplete() @@ -234,7 +235,7 @@ class SendViewModelTest : BaseUnitTest() { for ((name, interrupt) in interruptions) { walletState.update { it.copy(status = WalletStatus.Connecting) } stubInvoice(prepared()) - whenever(paymentsRepo.skipConfirmation(any())).thenReturn(true) + whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) val sut = createSut() interrupt() @@ -242,7 +243,7 @@ class SendViewModelTest : BaseUnitTest() { assertIs(sut.uiState.value.step, name) } - verify(paymentsRepo, never()).skipConfirmation(any()) + verify(paymentsRepo, never()).skipConfirmation(any(), any()) verify(paymentsRepo, never()).send(any()) } @@ -250,22 +251,22 @@ class SendViewModelTest : BaseUnitTest() { 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())).thenReturn(true) + 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()) + 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(prepared)).doSuspendableAnswer { + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).doSuspendableAnswer { ambientMonitor.set(true) - true + it.getArgument<() -> Boolean>(1)() } val sut = createSut() @@ -278,7 +279,7 @@ class SendViewModelTest : BaseUnitTest() { fun `a quickpay send that fails shows the failure like any other`() = test { val prepared = prepared() stubInvoice(prepared) - whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(true) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(true) whenever(paymentsRepo.send(prepared)).thenReturn(Result.failure(SendError.Failed())) val sut = createSut() @@ -292,7 +293,7 @@ class SendViewModelTest : BaseUnitTest() { .thenReturn(flowOf(WatchSettings(displayUnit = BitcoinDisplayUnit.CLASSIC))) val prepared = prepared(amountSats = 21_000uL) stubInvoice(prepared) - whenever(paymentsRepo.skipConfirmation(prepared)).thenReturn(false) + whenever(paymentsRepo.skipConfirmation(eq(prepared), any())).thenReturn(false) val sut = createSut() From d527d7cee86416d2fc4292edf3aeabeffbe3be60 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 06:22:07 -0300 Subject: [PATCH 08/15] docs: update wear quickpay docs and journeys for phone parity Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 118 ++++++++++-------- journeys/wear/README.md | 85 ++++++++----- journeys/wear/quickpay-on-app-start.xml | 14 +-- .../wear/settings-swap-survives-import.xml | 5 +- 4 files changed, 130 insertions(+), 92 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index 4546874f8f..c8946a4bbf 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -353,56 +353,66 @@ in any other state. 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). 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: +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. -- It pays a BOLT11 invoice that carries its amount. An amount the wearer typed always gets the review and the hold: - the review is the one place that shows what was typed, its fee and its payee. An LNURL, a Lightning address and - a Spark address always get them too, also when the service fixes the amount. -- The wearer is there (`SendViewModel`). The send was 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 without a network that connects minutes later by itself, always ends on the review and - the hold, so nothing is paid after the wearer looked away. The phone does the same for a scan put off across - its lock. The 30 s cover a wallet that connects and syncs as the link opens the app. -- 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 send the wearer left on the review or on a failure comes back on the review and the - hold, hours later too. -- The phone's settings were imported at most 15 minutes ago, and QuickPay is on in them. The age is that of the - watch's last read of the backup, not of the phone's upload: QuickPay turned off on the phone stops on the watch - with the first import after the phone uploaded its settings, and within 15 minutes of the watch's last import - when the watch cannot read the backup any more. A phone that could not upload leaves its old backup in place, - and the watch keeps following that one. -- A dollar rate fetched at most an hour ago values the payment's cost, the amount plus the fee, at no more than the - phone's QuickPay amount. The hour is counted on the clock that keeps running while the watch sleeps - (`ElapsedClock`). The cost is rounded up to the cent. The phone compares the amount without the fee; the watch - counts the fee, which is the stricter reading. -- Today's QuickPay payments from this watch, with this one, stay within the daily limit. - -A payment link usually opens the app, after a start or a long absence, and the import and the rates that the start -brings are then still on their way when the send is priced. So before it reads the limits the decision waits for -them (`QuickPayRepo.awaitInputs`): when the last import has QuickPay on and is older than 15 minutes it joins the -import under way, or starts one, and when the rates are missing or older than an hour it fetches them, both together -for 5 s at most, under the loading ring. After the 5 s only the wait ends: an import still under way goes on and -lands, so the next payment finds it and does not wait again. It waits only then: a watch whose last import has QuickPay off, or that has -none, goes to the review at once, so QuickPay newly turned on at the phone applies from the payment after the next -import. What is still missing after the wait answers no. The wait cannot turn into a late payment: it starts only -inside the 30 s above, and the wearer has to be there still when it ends. - -Anything missing, stale or unreadable answers no, and the wearer holds to pay as without QuickPay: no import yet, a -backup the phone never wrote, an unreadable or newer backup, QuickPay values outside what the phone's sliders offer -(1 to 50 dollars, 1× to 50×), no rates, a settings file that cannot be read. +- 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. 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. +- 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, at least one cent and at most the QuickPay amount, 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 without a network that connects minutes + later by itself, always ends on the review and the hold. The 30 s cover a wallet that connects and syncs as + the link opens the app. + - 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, and stays counted when it then fails - or when the wearer turns out to have looked away meanwhile and holds to pay after all: - 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. + 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`). It stays counted when it was paid, when it is still pending and when its outcome is + unknown. 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. @@ -460,13 +470,19 @@ from VSS and never writes there. 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 or out of time, as a payment after its 5 s, 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 + 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; before a - QuickPay decision whose import is too old (see QuickPay); and on a tap on the Phone settings row. An import + 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 @@ -481,7 +497,7 @@ from VSS and never writes there. 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; QuickPay then stops by itself once the last import is 15 minutes old. Failures are + 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 @@ -733,7 +749,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 QuickPay should also cover a fixed-amount LNURL, and whether the watch's count of the day's QuickPay - payments should be shared with the phone's before pairing exists. +- 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/wear/README.md b/journeys/wear/README.md index 20139d656d..f22db6653f 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -143,15 +143,21 @@ regtest. Nothing extra runs locally, no VSS and no LNURL-auth server. They need 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, an amount the wearer typed, a missing, unreadable or newer backup, and settings older than -15 minutes have no journey: they depend on the exchange rate of the day, an amountless invoice the local stack does -not make, or a backup only a broken phone would write. `QuickPayRepoTest.kt`, `PaymentsRepoTest.kt`, -`SettingsSyncRepoTest.kt` and `PhoneSettingsParserTest.kt` cover them. - -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. +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 @@ -249,24 +255,28 @@ never on the public test phrase. That phrase's settings backup is one object on 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 that only this machine knows. With a passphrase the -phrase is another wallet, with a backup of its own that nobody else can name. No secret is read off a screen and -none is typed by hand, so an agent can set it up without ever seeing the passphrase. +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 that only you can read: +1. Make the passphrase, once per machine, in a file outside the repository: ```bash F=~/.config/bitkit-journeys/settings-passphrase - mkdir -p "${F%/*}" && chmod 700 "${F%/*}" - [ -s "$F" ] || (umask 077; LC_ALL=C tr -dc a-z0-9 "$F") + mkdir -p "${F%/*}" + [ -s "$F" ] || LC_ALL=C tr -dc a-z0-9 "$F" ``` - It prints nothing and 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. Never print it: no `cat`, `echo` or `set -x` on it, and no screenshot, `android layout` or `uiautomator dump` - output while a passphrase field shows it. Never copy it into the repository, a journey file, a log or a pull - request. Every command below reads the file inside the command that uses it. -3. Restore it in the phone app, a plain dev build (see [Phone settings on VSS](#phone-settings-on-vss), step 1). From + 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` @@ -276,33 +286,46 @@ none is typed by hand, so an agent can set it up without ever seeing the passphr adb shell input text "$(cat ~/.config/bitkit-journeys/settings-passphrase)" ``` - [Check it](#checking-the-passphrase), then tap `RestoreButton`. Leave the phone's settings at their defaults for - now and close the phone app (`adb shell am force-stop to.bitkit.dev`). + [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`, which reads `0` for a new wallet. + 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 defaults. That journey expects "50 000", which is what a watch on - Bitcoin and Modern shows; after `settings-import-units.xml` set Classic, the same payment reads "0.00050000". + 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, without printing it: this prints only a count, which must be `1`. +backup. Check the field before you confirm: the layout dump has to hold the passphrase as typed, so this prints `1` +or more. ```bash -adb exec-out uiautomator dump /dev/tty | grep -c "text=\"$(cat ~/.config/bitkit-journeys/settings-passphrase)\"" +android layout | grep -c -F "$(cat ~/.config/bitkit-journeys/settings-passphrase)" ``` -On `0`, clear the field, type again and check again. The proof that phone and watch hold the same wallet comes with -the first import: the watch logs `Imported the phone's settings` once the phone wrote its backup, and -`Found no settings backup of the phone` when the two differ. +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 diff --git a/journeys/wear/quickpay-on-app-start.xml b/journeys/wear/quickpay-on-app-start.xml index 73be03bd4c..e309cb8d11 100644 --- a/journeys/wear/quickpay-on-app-start.xml +++ b/journeys/wear/quickpay-on-app-start.xml @@ -1,27 +1,25 @@ - A payment link that starts the app is paid under QuickPay too, although the last import of the phone's settings - is too old by then: the send waits a moment for the import and the rates that the start brings, and then goes - out without the review and the hold. Emulator, or a physical watch that stays on the wrist and unlocked. + 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 watch that locked during - the 16 minutes: KEYCODE_WAKEUP lights the screen and unlocks nothing, and QuickPay never pays on a locked watch. - Use the emulator, which has no lock, or keep a physical watch on the wrist and unlocked for the whole wait. + 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` - Wait 16 minutes, as 16 waits of 1 minute and not one long sleep, touching nothing: the last import is then too old for QuickPay 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 "Imported the phone's settings" Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" diff --git a/journeys/wear/settings-swap-survives-import.xml b/journeys/wear/settings-swap-survives-import.xml index 84fd65d5f3..8b218b1ab4 100644 --- a/journeys/wear/settings-swap-survives-import.xml +++ b/journeys/wear/settings-swap-survives-import.xml @@ -5,10 +5,11 @@ 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 Balance page with "WatchHomeBalanceSymbol" reading "€" and the - loading ring stopped. + 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" From daf5dadd613bc42a72ca9c45d7f2dc8920744be4 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 07:10:34 -0300 Subject: [PATCH 09/15] docs: drop rows the wear rebase duplicated Co-Authored-By: Claude Opus 5.5 --- docs/wear.md | 6 ++---- journeys/wear/README.md | 5 ----- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index c8946a4bbf..a4e01714ce 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -77,13 +77,11 @@ settings by reading the phone's backup (see Settings sync). `WipeMarker` for the note itself), `OwnInvoiceStore` (the invoices this wallet created, in the settings file), `QuickPaySpendStore` (the day's QuickPay spend, in the settings file), the rates client, `NetworkMonitor` (`ConnectivityManager`'s default network, online once the system validated it), - `NfcMonitor` (the NFC adapter's state) and `ForegroundMonitor` (the process lifecycle: whether the app is on - screen). -- `tile`: `BalanceTileService` (the balance tile), `TileState` (what it shows) and `TileUpdates` (asks the system - to draw it again). See Tile below. `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 diff --git a/journeys/wear/README.md b/journeys/wear/README.md index f22db6653f..c2b0cf24ea 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -125,11 +125,6 @@ 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 | -| `settings-import-units.xml` | hosted, and a phone that wrote its settings | yes, any balance above 0 | -| `quickpay-skips-hold.xml` | local, and a phone that wrote its settings | yes, 2 000 sats | -| `quickpay-over-limit-holds.xml` | local, and a phone that wrote its settings | yes, 12 000 sats | -| `quickpay-off-holds.xml` | local, and a phone that wrote its settings, after `quickpay-skips-hold.xml` | yes, 2 000 sats | -| `settings-import-units.xml` | local, a private phrase, and a phone that wrote its settings | yes, any balance above 0 | | `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 | From c141ec84d4e932ca4be6ecca6828804d71e8cf2d Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 07:34:45 -0300 Subject: [PATCH 10/15] fix: compile the balance tile against the wear display unit Co-Authored-By: Claude Fable 5.2 --- wear/src/main/java/to/bitkit/wear/tile/TileState.kt | 2 +- wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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..cc3d347173 100644 --- a/wear/src/main/java/to/bitkit/wear/tile/TileState.kt +++ b/wear/src/main/java/to/bitkit/wear/tile/TileState.kt @@ -23,7 +23,7 @@ sealed interface TileState { fun tileState(hasWallet: Boolean, wallet: WalletState, 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, locale = locale) }) } private val walletGoneStatuses = setOf(WalletStatus.Removed, WalletStatus.Missing) 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 1c955cb965..2f8ea0425a 100644 --- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt +++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt @@ -32,7 +32,7 @@ sealed interface LaunchRequest { } /** - * Whether an intent with [flags] is one Android replays from Recents: the link that once opened the app, sent again - * long after the wearer saw it. Such an intent is a plain launch. + * 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 From ed221151aaa03c11706cfc69c0807e75d6187add Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 07:34:46 -0300 Subject: [PATCH 11/15] fix: hold quickpay at the phone's boundary, keep its count exact Co-Authored-By: Claude Fable 5.2 --- .../bitkit/wear/repositories/PaymentsRepo.kt | 39 ++++++++++++------- .../bitkit/wear/repositories/QuickPayRepo.kt | 14 +++---- .../wear/repositories/PaymentsRepoTest.kt | 31 +++++++++++++++ .../wear/repositories/QuickPayRepoTest.kt | 19 +++++++-- 4 files changed, 79 insertions(+), 24 deletions(-) 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 1e18eea041..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 @@ -156,23 +158,33 @@ class PaymentsRepo @Inject constructor( * 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. Anything that cannot be told answers no, - * and the wearer holds to pay. + * 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. */ - suspend fun skipConfirmation(prepared: PreparedSend, canSend: () -> Boolean): Boolean = + 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() - 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 + // 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 } - 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 @@ -438,7 +450,7 @@ class PaymentsRepo @Inject constructor( * 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 anything but [SendError.Unknown]. + * fails with a [SendError] other than [SendError.Unknown]. */ suspend fun send(prepared: PreparedSend): Result = sendScope.async { runSuspendCatching { @@ -466,9 +478,10 @@ class PaymentsRepo @Inject constructor( 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. + // 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) - if (reservation != null && result.isFailure && result.exceptionOrNull() !is SendError.Unknown) { + val error = result.exceptionOrNull() + if (reservation != null && error is SendError && error !is SendError.Unknown) { quickPayRepo.release(reservation) } } diff --git a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt index 5594ef517f..419668aca6 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -80,7 +80,8 @@ class QuickPayRepo internal constructor( /** * 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 at the dollar rate, and today's QuickPay payments + * 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) { @@ -104,7 +105,10 @@ class QuickPayRepo internal constructor( val rate = currencyRepo.rates.value.rateFor(USD) ?: return null val thresholdSats = thresholdSats(quickPay, rate) ?: return null if (thresholdSats == 0uL || amountSats > thresholdSats) return null - val cents = reserveCents(amountSats, rate, quickPay) ?: 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) @@ -118,12 +122,6 @@ class QuickPayRepo internal constructor( .setScale(0, RoundingMode.HALF_UP) return runCatching { sats.longValueExact().toULong() }.getOrNull() } - - private fun reserveCents(amountSats: ULong, rate: FxRate, quickPay: QuickPayLimits): Long? { - val fiat = fiatValue(amountSats.toLong(), rate) ?: return null - val cents = fiat.movePointRight(CENTS_SCALE).setScale(0, RoundingMode.HALF_UP).toLong() - return minOf(cents, quickPay.thresholdCents).coerceAtLeast(1L) - } } /** A payment counted against the QuickPay limit of [dayKey], an ISO date, as [cents] US cents. */ 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 ca0e4613de..7510cad166 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -709,6 +709,37 @@ class PaymentsRepoTest : BaseUnitTest() { 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)) diff --git a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt index 85b6cf8f9d..2413efa15d 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -121,6 +121,19 @@ class QuickPayRepoTest : BaseUnitTest() { 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)) @@ -170,12 +183,12 @@ class QuickPayRepoTest : BaseUnitTest() { } @Test - fun `a payment counts for no more than the phone's amount`() = 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")) } - assertEquals(500L, sut.reserve(167uL)?.cents) - assertNull(sut.reserve(168uL)) + assertNull(sut.reserve(167uL)) + assertEquals(498L, sut.reserve(166uL)?.cents) } @Test From 3de93dbbccb6055747f1ec533c590a4b318df871 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 07:34:46 -0300 Subject: [PATCH 12/15] docs: update wear quickpay docs for the round 4 fixes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 11 +++++++---- journeys/wear/README.md | 5 +++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index a4e01714ce..ae44726d35 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -364,9 +364,11 @@ usual result screens, only when every one of these holds: - 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. + 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, at least one cent and at most the QuickPay amount, as on the phone. + 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 @@ -402,8 +404,9 @@ 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`). It stays counted when it was paid, when it is still pending and when its outcome is - unknown. The phone goes on to take out a pending payment that fails later, from its ledger; the watch keeps no + (`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. diff --git a/journeys/wear/README.md b/journeys/wear/README.md index c2b0cf24ea..0765e2636a 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -367,6 +367,11 @@ their defaults. 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. +**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. From 693f8ea38bb059ce4558fcd598d90de9926bd70b Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 07:44:48 -0300 Subject: [PATCH 13/15] fix: show the tile balance in the imported display unit Co-Authored-By: Claude Opus 5.5 --- docs/wear.md | 20 +++++----- .../to/bitkit/wear/tile/BalanceTileService.kt | 11 +++++- .../java/to/bitkit/wear/tile/TileState.kt | 16 +++++--- .../java/to/bitkit/wear/tile/TileUpdates.kt | 12 ++++-- .../java/to/bitkit/wear/tile/TileStateTest.kt | 38 +++++++++++++------ 5 files changed, 66 insertions(+), 31 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index ae44726d35..9d3789bf7c 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -180,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 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 cc3d347173..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 = 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/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)) } } From e9c4b458f892efad02724b28ba63aa18e95d20ea Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 08:57:01 -0300 Subject: [PATCH 14/15] fix: end a quickpay link on the offline error, never across an offline wait Co-Authored-By: Claude Fable 5.2 --- .../wear/ui/screens/send/SendViewModel.kt | 17 +++++-- .../wear/repositories/PaymentsRepoTest.kt | 49 +++++++++++++++++++ .../wear/ui/screens/send/SendViewModelTest.kt | 45 ++++++++++++++++- 3 files changed, 106 insertions(+), 5 deletions(-) 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 83ca48d9ee..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 @@ -51,8 +51,9 @@ import kotlin.time.Duration.Companion.seconds * * QuickPay is asked only for a send the wearer is there for: one priced within [QUICKPAY_WINDOW] of its link, with * the app on screen, out of ambient mode and the watch unlocked all the while. A link that waited longer for the - * wallet, as without a network, 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. Only the first flow of a link asks: one that Android + * 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. */ @@ -226,7 +227,7 @@ class SendViewModel @Inject constructor( 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, ::isAttended)) { + if (isQuickPayOpen() && paymentsRepo.skipConfirmation(result, ::canQuickPay)) { Logger.info("Skipped the hold to pay under QuickPay", context = TAG) send(result) return @@ -236,7 +237,15 @@ class SendViewModel @Inject constructor( /** Whether QuickPay may be asked for a send priced now: see the class. */ private fun isQuickPayOpen(): Boolean = - isAttended() && clock.nowMs() - arrivedAtMs in 0..QUICKPAY_WINDOW.inWholeMilliseconds + 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 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 7510cad166..a06071d199 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -620,6 +620,55 @@ class PaymentsRepoTest : BaseUnitTest() { 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) 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 35b9201890..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 @@ -170,7 +170,7 @@ class SendViewModelTest : BaseUnitTest() { @Test fun `a link that waited long for the wallet is reviewed and held, never paid under quickpay`() = test { - for (status in listOf(WalletStatus.Offline, WalletStatus.Error, WalletStatus.Connecting)) { + for (status in listOf(WalletStatus.Error, WalletStatus.Connecting)) { walletState.update { it.copy(status = status) } stubInvoice(prepared()) whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) @@ -186,6 +186,49 @@ class SendViewModelTest : BaseUnitTest() { 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() From aa511466652a99d4b86ab046220a6bf13f1be611 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sat, 28 Nov 2026 08:57:02 -0300 Subject: [PATCH 15/15] docs: describe wear quickpay with the offline error and the new link schemes Co-Authored-By: Claude Fable 5.2 --- docs/wear.md | 12 ++++++++---- journeys/wear/README.md | 3 ++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/wear.md b/docs/wear.md index 9d3789bf7c..cbda663fc8 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -359,7 +359,9 @@ usual result screens, only when every one of these holds: - 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. An + `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. @@ -382,9 +384,11 @@ The two differences from the phone: 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 without a network that connects minutes - later by itself, always ends on the review and the hold. The 30 s cover a wallet that connects and syncs as - the link opens the app. + 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 diff --git a/journeys/wear/README.md b/journeys/wear/README.md index 0765e2636a..0c0e287425 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -365,7 +365,8 @@ 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. +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