diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index c0e75d6b6a..db02482851 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -180,7 +180,7 @@ class CacheStore internal constructor( /** * Remembers the Spark invoice with [paymentHash] as one this wallet created, until [expiresAt] in epoch seconds, * so the wallet refuses to pay it. Invoices expired at [now] are dropped, as nobody can pay them. A paired - * device's invoices are added the same way. + * watch's invoices are not kept here but in [WatchLinkStore], so they never push the phone's own out. */ suspend fun addSparkOwnInvoice(paymentHash: String, expiresAt: Long, now: Long) { var dropped = 0 diff --git a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt index dd1ee81438..b14cedfaae 100644 --- a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt +++ b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt @@ -11,8 +11,12 @@ import kotlinx.coroutines.flow.map import kotlinx.serialization.Serializable import to.bitkit.data.serializers.WatchLinkSerializer import to.bitkit.wearlink.Handshake +import to.bitkit.wearlink.LinkGuards import to.bitkit.wearlink.LinkRecord import to.bitkit.wearlink.LinkRecordStore +import to.bitkit.wearlink.OpenSend +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc import to.bitkit.wearlink.ThrottleState import to.bitkit.wearlink.ThrottleStore import java.security.SecureRandom @@ -25,14 +29,32 @@ private val Context.watchLinkDataStore: DataStore by dataStore( ) /** - * The phone's note of its paired watch, this install's random id for pairings, and the count of seed transfers that - * were started and not finished. It belongs to the install and is in no backup: the link keys are in the Keystore - * and cannot be restored, so a restored phone pairs again. Nothing here is secret. + * What the paired watch last told the phone for the shared guards: its unexpired invoices, its QuickPay count and + * its open sends. They are kept apart from the phone's own state, so nothing the watch says displaces it, and they + * hold only while a pairing exists. Whatever feeds these, the link today, the guards read them the same way. + * `docs/wear.md`, Pairing › Shared guards. + */ +interface WatchGuardState { + /** Whether [paymentHash], in hex of either case, is an invoice the watch created that is unexpired at [now]. */ + suspend fun hasWatchInvoice(paymentHash: String, now: Long): Boolean + + /** The watch's last QuickPay count, or null without a paired watch or before its first count. */ + suspend fun watchQuickPay(): QuickPayDoc? + + /** The watch's open sends as it last listed them. */ + suspend fun watchSends(): List +} + +/** + * The phone's note of its paired watch, this install's random id for pairings, the count of seed transfers that + * were started and not finished, and what the watch last said for the shared guards ([WatchGuardState]). It belongs + * to the install and is in no backup: the link keys are in the Keystore and cannot be restored, so a restored phone + * pairs again. Nothing here is secret. */ @Singleton class WatchLinkStore internal constructor( private val store: DataStore, -) : LinkRecordStore { +) : LinkRecordStore, WatchGuardState { @Inject constructor(@ApplicationContext context: Context) : this(context.watchLinkDataStore) @@ -56,6 +78,36 @@ class WatchLinkStore internal constructor( } } + override suspend fun hasWatchInvoice(paymentHash: String, now: Long): Boolean = + paired()?.watchInvoices?.get(paymentHash.lowercase())?.let { it > now } == true + + override suspend fun watchQuickPay(): QuickPayDoc? = paired()?.watchQuickPay + + override suspend fun watchSends(): List = paired()?.watchSends.orEmpty() + + /** Replaces the watch's invoices with [invoices], leaving out the ones expired at [now]. */ + suspend fun setWatchInvoices(invoices: List, now: Long) { + val unexpired = invoices.filter { it.expiresAtSecs > now } + .associate { it.paymentHash.lowercase() to it.expiresAtSecs } + store.updateData { it.copy(watchInvoices = unexpired) } + } + + suspend fun setWatchQuickPay(quickPay: QuickPayDoc) { + store.updateData { it.copy(watchQuickPay = quickPay) } + } + + /** Replaces the watch's open sends with [sends], each one already known keeping its earlier start. */ + suspend fun setWatchSends(sends: List) { + store.updateData { it.copy(watchSends = LinkGuards.keptStarts(sends, it.watchSends)) } + } + + /** Drops the watch's invoices, count and open sends, as when the pairing ends. */ + suspend fun clearWatchGuards() { + store.updateData { it.copy(watchInvoices = emptyMap(), watchQuickPay = null, watchSends = emptyList()) } + } + + private suspend fun paired(): WatchLinkData? = store.data.first().takeIf { it.record != null } + /** This install's id for pairings, made at first use. */ @OptIn(ExperimentalStdlibApi::class) suspend fun installId(): ByteArray = store.updateData { @@ -70,4 +122,7 @@ data class WatchLinkData( val installId: String? = null, val transferAttempts: Int = 0, val transferLockedUntilMs: Long = 0, + val watchInvoices: Map = emptyMap(), + val watchQuickPay: QuickPayDoc? = null, + val watchSends: List = emptyList(), ) diff --git a/app/src/main/java/to/bitkit/di/WatchLinkModule.kt b/app/src/main/java/to/bitkit/di/WatchLinkModule.kt index 5eed89d089..f61a2e63d6 100644 --- a/app/src/main/java/to/bitkit/di/WatchLinkModule.kt +++ b/app/src/main/java/to/bitkit/di/WatchLinkModule.kt @@ -4,6 +4,8 @@ import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent +import to.bitkit.data.WatchGuardState +import to.bitkit.data.WatchLinkStore import to.bitkit.watch.KeystoreLinkKeys import to.bitkit.wearlink.LinkKeyStore import javax.inject.Singleton @@ -14,4 +16,8 @@ abstract class WatchLinkModule { @Binds @Singleton abstract fun bindLinkKeyStore(keys: KeystoreLinkKeys): LinkKeyStore + + @Binds + @Singleton + abstract fun bindWatchGuardState(store: WatchLinkStore): WatchGuardState } diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index e6ff629b86..4f0525c74d 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -35,6 +35,7 @@ import to.bitkit.async.appScope import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.WatchGuardState import to.bitkit.data.requiresPaymentAuth import to.bitkit.di.IoDispatcher import to.bitkit.ext.callbackAmountMsats @@ -51,6 +52,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.asNodeException import to.bitkit.utils.isStoppedAtSubmission +import to.bitkit.wearlink.LinkGuards import java.math.BigDecimal import java.util.UUID import java.util.concurrent.ConcurrentHashMap @@ -69,12 +71,14 @@ class QuickPayRepo @Inject constructor( private val paymentLookup: QuickPayPaymentLookup, @IoDispatcher private val ioDispatcher: CoroutineDispatcher, clock: Clock, + private val watchGuards: WatchGuardState, ) { companion object { private const val TAG = "QuickPayRepo" } - private val spend = QuickPaySpendStore(cacheStore, clock) + /** The daily limit is the wallet's: what a paired watch spent under QuickPay on the phone's day counts too. */ + private val spend = QuickPaySpendStore(cacheStore, clock) { day -> watchCents(day) } private val scope = appScope(ioDispatcher, TAG) private val mutex = Mutex() private val opsByKey = mutableMapOf() @@ -874,6 +878,12 @@ class QuickPayRepo @Inject constructor( return notified } + /** What the paired watch spent on [day]; a count that cannot be read fills the day, so the user swipes. */ + private suspend fun watchCents(day: String): Long = runSuspendCatching { + LinkGuards.peerCents(watchGuards.watchQuickPay(), day) + }.onFailure { Logger.warn("Failed to read the watch's QuickPay count", it, context = TAG) } + .getOrDefault(LinkGuards.MAX_CENTS) + private suspend fun readSettings(): SettingsData? = runSuspendCatching { settingsStore.data.first() } .onFailure { Logger.warn("Failed to read QuickPay settings", it, context = TAG) } .getOrNull() diff --git a/app/src/main/java/to/bitkit/repositories/QuickPaySpendStore.kt b/app/src/main/java/to/bitkit/repositories/QuickPaySpendStore.kt index cadd5b3c3c..ca3bf32e78 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPaySpendStore.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPaySpendStore.kt @@ -11,9 +11,15 @@ import to.bitkit.models.QuickPayRecordPhase import java.util.UUID import kotlin.time.Clock +/** + * The phone's QuickPay count of the day. [peerCents] is what a paired watch said it spent under QuickPay on a day, + * which counts against the same daily limit (`docs/wear.md`, Pairing › Shared guards); it is never written into the + * phone's own count, which is what the phone publishes. + */ internal class QuickPaySpendStore( private val cacheStore: CacheStore, private val clock: Clock, + private val peerCents: suspend (String) -> Long = { 0 }, ) { companion object { const val LEDGER_VERSION = 1 @@ -25,7 +31,7 @@ internal class QuickPaySpendStore( val dayKey = currentDayKey() if (!supported) return SpendSnapshot(0L, supported = false, ledger = ledger) val spend = spendFor(ledger, dayKey) - return SpendSnapshot(spend.spentCents, supported = true, ledger = ledger) + return SpendSnapshot(spend.spentCents + peerCents(spend.dayKey), supported = true, ledger = ledger) } suspend fun matching(hash: String): QuickPayLedgerRecord? { @@ -41,12 +47,17 @@ internal class QuickPaySpendStore( keepHashes: Set = emptySet(), ): QuickPayLedgerRecord? { var reserved: QuickPayLedgerRecord? = null - val wrote = writeLedger { ledger, dayKey -> + val dayKey = currentDayKey() + val peerDay = spendFor(cacheStore.data.first().resolvedLedger().first, dayKey).dayKey + val peer = peerCents(peerDay) + val wrote = writeLedger { ledger, today -> if (ledger.recordMatching(paymentHash) != null) return@writeLedger ledger - val spend = spendFor(ledger, dayKey) - if (spend.spentCents > Long.MAX_VALUE - amountCents) return@writeLedger ledger + val spend = spendFor(ledger, today) + // The day turned between reading the watch's count and counting: nothing is counted, the user swipes. + if (spend.dayKey != peerDay) return@writeLedger ledger + if (spend.spentCents > Long.MAX_VALUE - amountCents - peer) return@writeLedger ledger val total = spend.spentCents + amountCents - if (total > capCents) return@writeLedger ledger + if (total + peer > capCents) return@writeLedger ledger val next = ledger.pruned(spend.dayKey, keepHashes) val record = QuickPayLedgerRecord( id = UUID.randomUUID().toString(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 5b6ded3929..cc3d4bd514 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -53,6 +53,7 @@ import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain import to.bitkit.data.SparkSendAttempt +import to.bitkit.data.WatchGuardState import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env @@ -67,6 +68,7 @@ import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError +import to.bitkit.wearlink.LinkGuards import java.io.File import java.util.UUID import java.util.concurrent.ConcurrentHashMap @@ -100,6 +102,7 @@ class SparkRepo @Inject constructor( private val coreService: Provider, private val settingsStore: SettingsStore, private val payoutChain: SparkPayoutChain, + private val watchGuards: WatchGuardState, ) { companion object { private const val TAG = "SparkRepo" @@ -550,17 +553,27 @@ class SparkRepo @Inject constructor( * Whether [bolt11], with [paymentHash] in hex, pays this Spark wallet: an unexpired invoice this wallet remembers * creating, or one that carries this wallet's Spark address. Remembered invoices that cannot be read count as * own, so the invoice is refused instead of paid unchecked. The second check needs Spark connected and is skipped - * without it, as on a build or network without Spark. An invoice a paired watch created is known only once its - * hash was added to the cache. + * without it, as on a build or network without Spark. An invoice a paired watch created is own too, once the + * watch said so; those are kept apart from the phone's own, and a set of them that cannot be read refuses + * nothing, as without a watch. */ suspend fun isOwnInvoice(bolt11: String, paymentHash: String): Boolean = withContext(bgDispatcher) { - val isRemembered = runSuspendCatching { cacheStore.hasSparkOwnInvoice(paymentHash, clock.now().epochSeconds) } + val now = clock.now().epochSeconds + val isRemembered = runSuspendCatching { cacheStore.hasSparkOwnInvoice(paymentHash, now) } .onFailure { Logger.warn("Failed to read the wallet's own Spark invoices", it, context = TAG) } .getOrDefault(true) - isRemembered || runSuspendCatching { sparkService.carriesOwnSparkAddress(bolt11) } + isRemembered || isWatchInvoice(paymentHash, now) || carriesOwnSparkAddress(bolt11) + } + + private suspend fun carriesOwnSparkAddress(bolt11: String): Boolean = + runSuspendCatching { sparkService.carriesOwnSparkAddress(bolt11) } .onFailure { Logger.debug("Skipped the Spark address check of an invoice: '${it.message}'", context = TAG) } .getOrDefault(false) - } + + private suspend fun isWatchInvoice(paymentHash: String, now: Long): Boolean = + runSuspendCatching { watchGuards.hasWatchInvoice(paymentHash, now) } + .onFailure { Logger.warn("Failed to read the watch's invoices", it, context = TAG) } + .getOrDefault(false) /** Returns the Lightning routing fee plus Spark's 0.25% service fee for paying [bolt11]. */ suspend fun estimateFeeSats(bolt11: String, amountSats: ULong?): Result = withContext(bgDispatcher) { @@ -598,9 +611,13 @@ class SparkRepo @Inject constructor( * again right before the send; refused there, it fails with [ServiceError.PaymentStoppedAtSubmission]. A failure * inside the send is a [PaymentPendingException], as the payment may have been dispatched, and its event decides * it. An invoice this wallet already sends is not sent again: one in flight or - * pending fails with [PaymentPendingException], and one Spark completed returns its hash. After a restore, a - * still-valid invoice created before it that the Spark operators can't show unsent fails with - * [SparkError.RestoredInvoiceUnverified], under the same rule as the node's send. + * pending fails with [PaymentPendingException], and one Spark completed returns its hash. So does one a paired + * watch lists as an open send, until the watch drops it, Spark's list shows that attempt failed, or it is + * [LinkGuards.OPEN_SEND_HOLD_SECS] old, when one Spark still does not list never reached it. A watch list that + * cannot be read holds nothing; the two devices still derive the same keys for an invoice, which Spark pays once. + * After a restore, a still-valid invoice created before it that the Spark + * operators can't show unsent fails with [SparkError.RestoredInvoiceUnverified], under the same rule as the + * node's send. */ suspend fun payInvoice( bolt11: String, @@ -663,6 +680,11 @@ class SparkRepo @Inject constructor( Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) return@runSuspendCatching paymentHash } + // The paired watch may be paying the invoice under a key Spark does not list yet: it stays pending here. + if (isOpenOnWatch(paymentHash, local)) { + Logger.info("Skipped Spark send of '$paymentHash', open on the watch", context = TAG) + throw PaymentPendingException(paymentHash) + } // A cancel, block or identity change can land while Spark prepares, so the caller checks again here, and // once more right before the send. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() @@ -771,6 +793,15 @@ class SparkRepo @Inject constructor( } } + private suspend fun isOpenOnWatch(paymentHash: String, local: List?): Boolean { + val sends = runSuspendCatching { watchGuards.watchSends() } + .onFailure { Logger.warn("Failed to read the watch's open sends", it, context = TAG) } + .getOrDefault(emptyList()) + if (sends.isEmpty()) return false + val failed = local.orEmpty().filter { it.status == PaymentStatus.FAILED }.mapTo(HashSet()) { it.id } + return LinkGuards.pendingSend(sends, paymentHash, failed, clock.now().epochSeconds) != null + } + /** * Whether Spark's [local] list shows the send of [paymentHash] paid; throws while it shows the send pending, or, * unless it is a [isKeyedRetry], while the list can't be read and an older build sent the invoice. diff --git a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt index 950be8bb6f..b0c5161c48 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt @@ -31,6 +31,8 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.WatchLinkStore @@ -50,11 +52,15 @@ import to.bitkit.wearlink.LinkNode import to.bitkit.wearlink.LinkPacket import to.bitkit.wearlink.LinkRecord import to.bitkit.wearlink.LinkTransport +import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairingState import to.bitkit.wearlink.PairingThrottle +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.PeerStateListener import to.bitkit.wearlink.PhoneLink import to.bitkit.wearlink.PhonePairing import to.bitkit.wearlink.PhonePairingEnv +import to.bitkit.wearlink.QuickPayDoc import to.bitkit.wearlink.SeedPayload import to.bitkit.wearlink.SettingsDoc import to.bitkit.wearlink.WalletLink @@ -77,9 +83,18 @@ import kotlin.time.ExperimentalTime * from the keychain at that point and not before. A phone without a PIN still pairs with a watch that holds its * wallet and pushes it the settings: nothing secret is sent then. * - * The phone's settings are published to the paired watch when the pairing is made and whenever one of them changes. - * This is the one place that feeds the watch: a later source of the same state, such as a backup both devices can - * read, would publish the same documents without the watch's readers changing. + * The phone's settings are published to the paired watch when the pairing is made and whenever one of them changes, + * and so are the shared guards' documents: the phone's own unexpired Spark invoices, its QuickPay count of its day, + * and its open Spark sends. Each document has one publisher, which also publishes it again once the watch's first + * status shows it noted the pairing, since the watch drops what arrives before that. What the watch publishes of its + * own lands here too: its invoices, its count and its open sends go to [WatchLinkStore] as + * [to.bitkit.data.WatchGuardState], which `QuickPayRepo` and `SparkRepo` read, and never into the phone's own state + * in [CacheStore]. This is the one place that feeds the watch and is fed by it: a later source of the same state, + * such as a backup both devices can read, would publish and store the same documents without the guards changing. + * + * The phone's open sends are the Spark sends it holds as of unknown outcome, noted before each goes out and kept + * until Spark settles it. A hold an older build left without its key goes out with an empty key, which no failed + * payment matches, so it holds the watch back only for [to.bitkit.wearlink.LinkGuards.OPEN_SEND_HOLD_SECS]. */ @OptIn(ExperimentalTime::class) @Singleton @@ -90,6 +105,7 @@ class WatchLinkRepo internal constructor( private val store: WatchLinkStore, private val keychain: Keychain, private val settingsStore: SettingsStore, + private val cacheStore: CacheStore, private val clock: Clock, private val appId: String, private val signingDigests: () -> Set, @@ -152,6 +168,7 @@ class WatchLinkRepo internal constructor( store: WatchLinkStore, keychain: Keychain, settingsStore: SettingsStore, + cacheStore: CacheStore, clock: Clock, httpClient: HttpClient, ) : this( @@ -161,6 +178,7 @@ class WatchLinkRepo internal constructor( store = store, keychain = keychain, settingsStore = settingsStore, + cacheStore = cacheStore, clock = clock, appId = context.packageName, signingDigests = { signingDigests(context) }, @@ -170,12 +188,33 @@ class WatchLinkRepo internal constructor( ) private val scope = CoroutineScope(SupervisorJob() + ioDispatcher) + private val republish = MutableStateFlow(0) + + private val watchGuards = object : PeerStateListener { + override suspend fun applyInvoices(invoices: List) { + store.setWatchInvoices(invoices, clock.now().epochSeconds) + Logger.debug("Applied '${invoices.size}' invoices of the watch", context = TAG) + } + + override suspend fun applyQuickPay(quickPay: QuickPayDoc) = store.setWatchQuickPay(quickPay) + + override suspend fun applySends(sends: List) { + store.setWatchSends(sends) + Logger.debug("Applied '${sends.size}' open sends of the watch", context = TAG) + } + + override suspend fun clearPeerState() = runSuspendCatching { store.clearWatchGuards() } + .onFailure { Logger.warn("Failed to clear the watch's guard state", it, context = TAG) } + .getOrThrow() + } private val link = PhoneLink( transport = transport, keys = keys, store = store, + peer = watchGuards, onSettingsMissed = { scope.launch { publishSettings(settingsStore.data.first().toWatchSettings()) } }, + onWatchPaired = { republish.update { it + 1 } }, nowMs = { clock.nowMs() }, ) @@ -194,6 +233,9 @@ class WatchLinkRepo internal constructor( init { transport.attach(::onPacket) scope.launch { publishSettingsOnChange() } + scope.launch { publishOnChange({ it.ownInvoices(clock.now().epochSeconds) }) { link.publishInvoices(it) } } + scope.launch { publishOnChange({ it.quickPaySpend() }) { link.publishQuickPay(it) } } + scope.launch { publishOnChange({ it.openSparkSends() }) { link.publishSends(it) } } } /** The watches connected to this phone, with whether each has Bitkit and is reached directly. */ @@ -328,6 +370,17 @@ class WatchLinkRepo internal constructor( .onFailure { Logger.warn("Failed to publish the settings to the watch", it, context = TAG) } } + private suspend fun publishOnChange(read: (AppCacheData) -> T, publish: suspend (T) -> Unit) { + val pairing = store.record.map { record -> record?.pairingId?.takeIf { record.removal == null } } + val value = cacheStore.data.map(read).distinctUntilChanged() + combine(pairing.distinctUntilChanged(), value, republish) { pairingId, current, _ -> pairingId to current } + .collectLatest { (pairingId, current) -> + if (pairingId == null) return@collectLatest + runSuspendCatching { publish(current) } + .onFailure { Logger.warn("Failed to publish a guard document to the watch", it, context = TAG) } + } + } + private fun SettingsData.toWatchSettings() = SettingsDoc( primaryDisplay = primaryDisplay.name, displayUnit = displayUnit.name, @@ -373,6 +426,21 @@ class WatchLinkRepo internal constructor( } } +private fun AppCacheData.ownInvoices(nowSecs: Long): List = + sparkOwnInvoices.filterValues { it > nowSecs }.map { PeerInvoice(it.key, it.value) } + +private fun AppCacheData.quickPaySpend(): QuickPayDoc? = + quickPayLedger?.takeIf { it.dayKey.isNotEmpty() }?.let { QuickPayDoc(it.dayKey, it.spentCents) } + +private fun AppCacheData.openSparkSends(): List = sparkUncertainSends.map { (hash, startedAt) -> + OpenSend( + key = sparkSendAttemptIds[hash].orEmpty(), + paymentHash = hash, + expiresAtSecs = sparkSendAttempts[hash]?.expiresAt ?: sparkSendExpiries[hash], + startedAtSecs = startedAt, + ) +} + /** Where the phone's side of a pairing stands. */ sealed interface WatchPairingStatus { data object Idle : WatchPairingStatus diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index b50a9e7f18..8a60a5cf8d 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -84,6 +84,8 @@ import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.WatchLinkData +import to.bitkit.data.WatchLinkStore import to.bitkit.data.backup.VssBackupClientLdk import to.bitkit.data.keychain.Keychain import to.bitkit.data.keychain.WalletBackupRestorePendingError @@ -2296,6 +2298,7 @@ class LightningRepoTest : BaseUnitTest() { coreService = { coreService }, settingsStore = settingsStore, payoutChain = mock(), + watchGuards = WatchLinkStore(InMemoryDataStore(WatchLinkData())), ) sut = LightningRepo( bgDispatcher = testDispatcher, diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index af3c71bde8..65a92e6359 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -44,10 +44,12 @@ import to.bitkit.models.QuickPayRecordPhase import to.bitkit.models.USD import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest +import to.bitkit.test.FakeWatchGuardState import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.AppError import to.bitkit.utils.LdkError import to.bitkit.utils.ServiceError +import to.bitkit.wearlink.QuickPayDoc import java.math.BigDecimal import java.util.Locale import kotlin.test.assertEquals @@ -110,6 +112,7 @@ class QuickPayRepoTest : BaseUnitTest() { """.trimIndent() } private val cacheStore = CacheStore(InMemoryDataStore(AppCacheData())) + private val watchGuards = FakeWatchGuardState() private val settingsStore: SettingsStore = mock() private val currencyRepo: CurrencyRepo = mock() private val lightningRepo: LightningRepo = mock() @@ -593,6 +596,46 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(1, cacheStore.data.first().quickPayLedger!!.records.size) } + @Test + fun `what the paired watch spent today counts against the daily limit, and only the phone's is counted`() = + test { + watchGuards.quickPay = QuickPayDoc("2026-08-15", 2_000) + + assertNotNull(sut.reserveBound("a", 1000u).getOrThrow()) + assertNull(sut.reserveBound("b", 1u).getOrThrow()) + assertFalse(sut.canApply(1u).getOrThrow()) + assertEquals(500L, spentCents()) + } + + @Test + fun `what the paired watch spent on another day counts for nothing`() = test { + watchGuards.quickPay = QuickPayDoc("2026-08-14", 2_500) + + assertTrue(sut.canApply(1000u).getOrThrow()) + assertNotNull(sut.reserveBound("a", 1000u).getOrThrow()) + } + + @Test + fun `a day that turns between reading the watch's count and counting counts nothing`() = test { + val store = QuickPaySpendStore(cacheStore, clock) { + clock.instant = Instant.parse("2026-08-16T12:00:00Z") + 0 + } + + assertNull(store.reserve("a", amountCents = 100, capCents = 1_000)) + assertNull(cacheStore.data.first().quickPayLedger?.records?.singleOrNull()) + + assertNotNull(store.reserve("a", amountCents = 100, capCents = 1_000)) + } + + @Test + fun `a watch count that cannot be read lets nothing skip the swipe`() = test { + watchGuards.failure = IllegalStateException("disk") + + assertFalse(sut.canApply(1u).getOrThrow()) + assertNull(sut.reserveBound("a", 1u).getOrThrow()) + } + @Test fun `canApply is true under threshold and cap`() = test { assertTrue(sut.canApply(500u).getOrThrow()) @@ -1746,6 +1789,7 @@ class QuickPayRepoTest : BaseUnitTest() { }, ioDispatcher = testDispatcher, clock = clock, + watchGuards = watchGuards, ) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index cf6f34f8d2..fa756e34ce 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -94,9 +94,12 @@ import to.bitkit.services.OnchainService import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest +import to.bitkit.test.FakeWatchGuardState import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.AppError import to.bitkit.utils.ServiceError +import to.bitkit.wearlink.LinkGuards +import to.bitkit.wearlink.OpenSend import java.io.File import java.io.IOException import java.math.BigInteger @@ -138,6 +141,7 @@ class SparkRepoTest : BaseUnitTest() { private val coreService = mock { on { onchain } doReturn onchainService } private val payoutChain = mock() private val settingsStore = mock { on { data } doReturn flowOf(SettingsData()) } + private val watchGuards = FakeWatchGuardState() private var now = Instant.fromEpochSeconds(1_800_000_000) /** The Spark operators' answer to a send status fetch; unreachable unless a test says otherwise. */ @@ -160,6 +164,7 @@ class SparkRepoTest : BaseUnitTest() { coreService = { coreService }, settingsStore = settingsStore, payoutChain = payoutChain, + watchGuards = watchGuards, ) @get:Rule @@ -240,6 +245,20 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(sut.isOwnInvoice("lnbcrt1other", "cd34")) } + @Test + fun `an invoice the paired watch created is the wallet's own, and a watch set that cannot be read is not`() = + test { + whenever { sparkService.carriesOwnSparkAddress(any()) }.thenReturn(false) + val sut = createSut(cacheStore = CacheStore(InMemoryDataStore(AppCacheData()), clock)) + watchGuards.invoices = setOf("ab12") + + assertTrue(sut.isOwnInvoice("lnbcrt1watch", "AB12")) + assertFalse(sut.isOwnInvoice("lnbcrt1other", "cd34")) + + watchGuards.failure = IllegalStateException("disk") + assertFalse(sut.isOwnInvoice("lnbcrt1watch", "AB12")) + } + @Test fun `a remembered invoice is the wallet's own while spark is not connected`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) @@ -3768,6 +3787,74 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).send(any(), anyOrNull()) } + @Test + fun `an invoice the paired watch has an open send of is pending and never sent`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + watchGuards.sends = listOf(open("hash-0", paymentHash = "HASH")) + val sut = createSut() + + val error = sut.payInvoice("lnbc1", 100uL).exceptionOrNull() + + assertEquals("hash", assertIs(error).paymentHash) + verify(sparkService, never()).send(any(), anyOrNull()) + assertTrue(cacheStore.data.first().sparkUncertainSends.isEmpty()) + } + + @Test + fun `a watch send whose attempt spark lists failed holds nothing, and the next attempt goes out`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0).copy(id = "hash-1")) + watchGuards.sends = listOf(open("hash-0")) + val sut = createSut() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + verify(sparkService).send(any(), eq("hash-1")) + } + + @Test + fun `a watch send spark never listed stops holding the invoice five minutes after its start`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + watchGuards.sends = listOf(open("hash-0")) + val sut = createSut() + + now += (LinkGuards.OPEN_SEND_HOLD_SECS - 1).seconds + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + + now += 1.seconds + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + } + + @Test + fun `a watch send of another invoice, or a watch list that cannot be read holds nothing`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut() + + watchGuards.sends = listOf(open("other-0", paymentHash = "other")) + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + watchGuards.sends = listOf(open("hash-0")) + watchGuards.failure = IllegalStateException("disk") + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + } + + private fun open(key: String, paymentHash: String = "hash") = + OpenSend(key, paymentHash = paymentHash, startedAtSecs = now.epochSeconds) + @Test fun `an invoice spark already paid or is paying is not sent again`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt index d826121ce3..9e325c03dd 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt @@ -14,21 +14,30 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.WatchLinkData import to.bitkit.data.WatchLinkStore import to.bitkit.data.keychain.Keychain +import to.bitkit.models.QuickPayLedger import to.bitkit.test.BaseUnitTest import to.bitkit.test.InMemoryDataStore import to.bitkit.wearlink.AttestationFailure import to.bitkit.wearlink.Handshake +import to.bitkit.wearlink.InvoicesDoc import to.bitkit.wearlink.LinkError +import to.bitkit.wearlink.LinkGuards import to.bitkit.wearlink.LinkNode import to.bitkit.wearlink.LinkPaths +import to.bitkit.wearlink.LinkRole import to.bitkit.wearlink.LinkTransport +import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairingState import to.bitkit.wearlink.PairingThrottle +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc import to.bitkit.wearlink.Removal import to.bitkit.wearlink.SeedPayload import to.bitkit.wearlink.SeedStoreResult @@ -64,6 +73,8 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { const val NOW = 1_800_000_000_000L const val MNEMONIC = "abandon abandon about" const val PASSPHRASE = "pass" + val HASH = "ab".repeat(32) + val OWN_HASH = "cd".repeat(32) /** The network name of this build, as `Env.network` gives it. */ const val NETWORK = "REGTEST" @@ -86,6 +97,14 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { /** Holds the phone's search for the watch until completed, as the Data Layer's query takes its time. */ private var nodesGate: CompletableDeferred? = null private val appliedSettings = mutableListOf() + private val cacheStore = CacheStore(InMemoryDataStore(AppCacheData())) + + /** What the watch received of the phone's guard documents. */ + private val watchGot = object { + var invoices: List? = null + var quickPay: QuickPayDoc? = null + var sends: List? = null + } private val storedSeeds = mutableListOf() private var erases = 0 private var nowMs = NOW @@ -97,13 +116,15 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { private var hasWatchWallet = true private lateinit var network: FakeLinkNetwork + private lateinit var linkData: InMemoryDataStore private lateinit var store: WatchLinkStore private lateinit var watchLink: WatchLink private lateinit var sut: WatchLinkRepo private fun TestScope.setUp(isUnverifiedTransferAllowed: Boolean = true) { network = FakeLinkNetwork(backgroundScope) - store = WatchLinkStore(InMemoryDataStore(WatchLinkData())) + linkData = InMemoryDataStore(WatchLinkData()) + store = WatchLinkStore(linkData) whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(MNEMONIC) whenever(keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)).thenReturn(PASSPHRASE) whenever(settingsStore.data).thenReturn(settings) @@ -123,6 +144,16 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { } override suspend fun onUnpaired() = Unit + + override suspend fun applyInvoices(invoices: List) = run { watchGot.invoices = invoices } + + override suspend fun applyQuickPay(quickPay: QuickPayDoc) = run { watchGot.quickPay = quickPay } + + override suspend fun applySends(sends: List) = run { watchGot.sends = sends } + + override suspend fun clearPeerState() = Unit + + override fun onPhonePaired() = Unit }, info = { WatchInfo("1.0", isLockSet = false) }, nowMs = { nowMs }, @@ -140,6 +171,7 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { store = store, keychain = keychain, settingsStore = settingsStore, + cacheStore = cacheStore, clock = clock, appId = APP_ID, signingDigests = { setOf("00") }, @@ -602,6 +634,158 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { verify(keychain, never()).wipe() } + // region shared guards + + @Test + fun `pairing publishes the phone's own invoices, quickpay count and open sends to the watch`() = test { + setUp() + val nowSecs = NOW / 1_000 + cacheStore.addSparkOwnInvoice(HASH, nowSecs + 3_600, nowSecs) + cacheStore.update { it.copy(quickPayLedger = QuickPayLedger(1, "2026-11-28", 250)) } + cacheStore.addSparkUncertainSend(HASH, nowSecs - 10, "attempt-0") + + pair() + + assertEquals(listOf(PeerInvoice(HASH, nowSecs + 3_600)), watchGot.invoices) + assertEquals(QuickPayDoc("2026-11-28", 250), watchGot.quickPay) + assertEquals(listOf(OpenSend("attempt-0", HASH, startedAtSecs = nowSecs - 10)), watchGot.sends) + } + + @Test + fun `a send the phone settles is withdrawn from the watch's list`() = test { + setUp() + cacheStore.addSparkUncertainSend(HASH, 1, "attempt-0") + pair() + + cacheStore.removeSparkUncertainSend(HASH) + runCurrent() + + assertEquals(emptyList(), watchGot.sends) + } + + @Test + fun `the phone publishes its guard documents again once the watch's first status shows it noted the pairing`() = + test { + setUp() + cacheStore.update { it.copy(quickPayLedger = QuickPayLedger(1, "2026-11-28", 250)) } + + // The phone notes the pairing first, so the watch drops what the phone publishes at once. + pair() + + val quickPay = LinkPaths.guard(LinkRole.Phone, LinkGuards.QUICKPAY) + assertEquals(2, network.sent.count { it.isState && it.path.endsWith(quickPay) }) + assertEquals(QuickPayDoc("2026-11-28", 250), watchGot.quickPay) + assertEquals(emptyList(), watchGot.invoices) + assertEquals(emptyList(), watchGot.sends) + } + + @Test + fun `the watch's invoices, count and open sends are kept for the guards, apart from the phone's own`() = test { + setUp() + pair() + val nowSecs = NOW / 1_000 + val send = OpenSend("key-0", paymentHash = HASH, expiresAtSecs = nowSecs + 60, startedAtSecs = nowSecs) + + watchLink.publishInvoices(listOf(PeerInvoice(HASH.uppercase(), nowSecs + 3_600))) + watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 400)) + watchLink.publishSends(listOf(send)) + runCurrent() + + assertTrue(store.hasWatchInvoice(HASH, nowSecs)) + assertFalse(store.hasWatchInvoice(HASH, nowSecs + 3_600)) + assertTrue(cacheStore.data.first().sparkOwnInvoices.isEmpty()) + assertEquals(QuickPayDoc("2026-11-28", 400), store.watchQuickPay()) + assertEquals(listOf(send), store.watchSends()) + } + + @Test + fun `a send the watch lists again keeps the start it had when it first arrived`() = test { + setUp() + pair() + val nowSecs = NOW / 1_000 + val send = OpenSend("key-0", paymentHash = HASH, startedAtSecs = nowSecs + 9_000) + watchLink.publishSends(listOf(send)) + runCurrent() + + nowMs += 60_000 + watchLink.publishSends(listOf(send, OpenSend("key-1", paymentHash = OWN_HASH, startedAtSecs = nowSecs))) + runCurrent() + + assertEquals(listOf(nowSecs, nowSecs), store.watchSends().map { it.startedAtSecs }) + } + + @Test + fun `the phone publishes a count of no day before it spent anything under quickpay`() = test { + setUp() + + pair() + + assertEquals(QuickPayDoc(LinkGuards.NO_DAY, 0), watchGot.quickPay) + } + + @Test + fun `a full watch document with endless expiries leaves the phone's own invoices, and the next replaces it`() = + test { + setUp() + val nowSecs = NOW / 1_000 + cacheStore.addSparkOwnInvoice(OWN_HASH, nowSecs + 3_600, nowSecs) + pair() + val forged = List(2 * InvoicesDoc.MAX_INVOICES) { PeerInvoice("%064x".format(it), Long.MAX_VALUE) } + + forged.chunked(InvoicesDoc.MAX_INVOICES).forEach { watchLink.publishInvoices(it) } + runCurrent() + + val kept = linkData.data.first().watchInvoices + assertEquals(InvoicesDoc.MAX_INVOICES, kept.size) + assertTrue(kept.values.all { it == nowSecs + LinkGuards.MAX_EXPIRY_AHEAD_SECS }) + assertEquals(mapOf(OWN_HASH to nowSecs + 3_600), cacheStore.data.first().sparkOwnInvoices) + assertTrue(cacheStore.hasSparkOwnInvoice(OWN_HASH, nowSecs)) + + watchLink.publishInvoices(listOf(PeerInvoice(HASH, nowSecs + 60))) + runCurrent() + + assertEquals(mapOf(HASH to nowSecs + 60), linkData.data.first().watchInvoices) + // The watch's hashes are never sent back to it as the phone's. + assertEquals(listOf(PeerInvoice(OWN_HASH, nowSecs + 3_600)), watchGot.invoices) + } + + @Test + fun `unpairing drops the watch's invoices, count and open sends`() = test { + setUp() + pair() + val nowSecs = NOW / 1_000 + watchLink.publishInvoices(listOf(PeerInvoice(HASH, nowSecs + 3_600))) + watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 400)) + watchLink.publishSends(listOf(OpenSend("key-0", paymentHash = HASH))) + runCurrent() + + sut.remove(isErase = false).getOrThrow() + runCurrent() + + assertNull(store.load()) + assertNull(store.watchQuickPay()) + assertTrue(store.watchSends().isEmpty()) + assertFalse(store.hasWatchInvoice(HASH, nowSecs)) + assertEquals(WatchLinkData(installId = linkData.data.first().installId), linkData.data.first()) + } + + @Test + fun `what a watch said holds nothing without a pairing, as when its state could not be cleared`() = test { + val left = WatchLinkData( + watchInvoices = mapOf(HASH to Long.MAX_VALUE), + watchQuickPay = QuickPayDoc("2026-11-28", 400), + watchSends = listOf(OpenSend("key-0", paymentHash = HASH)), + ) + + val unpaired = WatchLinkStore(InMemoryDataStore(left)) + + assertFalse(unpaired.hasWatchInvoice(HASH, 0)) + assertNull(unpaired.watchQuickPay()) + assertTrue(unpaired.watchSends().isEmpty()) + } + + // endregion + @Test fun `the install id is made once and kept`() = test { setUp() diff --git a/app/src/test/java/to/bitkit/test/FakeWatchGuardState.kt b/app/src/test/java/to/bitkit/test/FakeWatchGuardState.kt new file mode 100644 index 0000000000..c0c078ee75 --- /dev/null +++ b/app/src/test/java/to/bitkit/test/FakeWatchGuardState.kt @@ -0,0 +1,28 @@ +package to.bitkit.test + +import to.bitkit.data.WatchGuardState +import to.bitkit.wearlink.OpenSend +import to.bitkit.wearlink.QuickPayDoc + +/** What a paired watch said for the shared guards, set by the test. [failure] makes every read fail. */ +class FakeWatchGuardState : WatchGuardState { + var invoices: Set = emptySet() + var quickPay: QuickPayDoc? = null + var sends: List = emptyList() + var failure: Throwable? = null + + override suspend fun hasWatchInvoice(paymentHash: String, now: Long): Boolean { + failure?.let { throw it } + return paymentHash.lowercase() in invoices + } + + override suspend fun watchQuickPay(): QuickPayDoc? { + failure?.let { throw it } + return quickPay + } + + override suspend fun watchSends(): List { + failure?.let { throw it } + return sends + } +} diff --git a/docs/wear.md b/docs/wear.md index 775872d99c..88febebf20 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -1,6 +1,9 @@ # Bitkit on Wear OS -> Do not publish the watch app yet: two live Spark instances on one seed are unsafe until #2152 is resolved. +> Do not publish the watch app yet: two live Spark instances on one seed are unsafe until #2152 is resolved. The +> phone and the watch are opened on one seed together only for the journeys `journeys/wear/README.md` › Two apps on +> one wallet allows: the pairing journeys on a throwaway wallet with no funds, and the shared-guard journeys on the +> local `./spark` stack only. 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. It needs no phone nearby: it adopts the phone's @@ -450,8 +453,9 @@ in any other state. attempt number than the phone: when the phone's attempt failed before it reached the operators and its next attempt is in flight, unseen by the watch's sync, the watch's send under the first key is a second payment of 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. + does not show. A transfer to a Spark address has no shared key at all. A paired phone and watch share their open + sends, and each refuses an invoice the other lists as open, for 5 minutes from its start (Pairing › Shared + guards); an unpaired pair keeps this gap, and so does a paired one for a send started while the two were apart. - **QuickPay.** `PaymentsRepo.skipConfirmation` is the one place that decides whether a send skips the review and the hold to pay. See QuickPay below. @@ -477,8 +481,9 @@ usual result screens, only when every one of these holds: turned into sats at the dollar rate, rounded half up, and the invoice's sats are compared with that. The invoice's unrounded dollar value is compared with the QuickPay amount too, which is the phone's check when it pays: where the sats rounded up, the last sat is worth a fraction of a cent too much and is reviewed. -- Today's QuickPay payments from this watch, with this one, stay within the daily limit. The payment counts as its - dollar value in cents, rounded half up and at least one cent, as on the phone. +- Today's QuickPay payments from this watch, with this one, and those a paired phone last said it made today stay + within the daily limit. The payment counts as its dollar value in cents, rounded half up and at least one cent, as + on the phone. - The wearer is there: the first of the two differences below. The rate is the last one the watch fetched, whatever its age: the phone has no age limit on its rates either. The @@ -531,9 +536,10 @@ or a count that cannot be read. 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 (a later PR) - is where the two can share one count. +- **Two counts, one limit when paired.** Each device keeps its own count of the day's QuickPay payments. A paired + phone and watch tell each other theirs and stay together within the phone's daily limit (Pairing › Shared + guards). **Known gap:** unpaired, each allows the daily limit, together up to twice it a day; paired but apart, + the two can go over it by what the other spent since they last reached each other. - **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 @@ -839,10 +845,9 @@ the local regtest stack on 2026-11-27: with the setting off the invoice had the on it gained the hint above, whose node equalled the identity key. The SDK itself prices a payment of the wallet's own invoice without complaint. -**Known gap.** A device does not know the invoices the other one created: the watch pays an invoice the phone made, -and the phone one the watch made, until the two share their hashes. Both stores take hashes from outside -(`OwnInvoiceStore.add`, `CacheStore.addSparkOwnInvoice`), which the pairing work (a later PR) uses to merge them. An -unpaired watch has no way to learn the phone's invoices. The watch runs the guard when an input is read, if the +**Paired devices share their invoices** (Pairing › Shared guards): each keeps the other's hashes apart from its +own. **Known gap:** an unpaired watch has no way to learn the phone's +invoices, and a paired one learns of an invoice made while the two were apart only once they reconnect. The watch runs the guard when an input is read, if the wallet is ready then, and always before a send is priced, also on the invoice an LNURL service returns; a guard that cannot tell refuses the send. @@ -852,9 +857,9 @@ The phone app and the watch app can be linked. Pairing does three things: it let sending it the wallet, it gives the phone a live, authenticated way to push its settings to the watch, and it lets the phone unpair the watch or erase its wallet. The watch still works without it, by the backup import above. -This is part 1 of the pairing work. Parts 2 and 3 are later PRs and are named where they attach: part 2 shares the -self-send guard's invoice hashes, the QuickPay counts and the send records; part 3 adds watch-specific limits, a -payment handed from the phone to the watch and the prompt to install the watch app. +Part 2 of the pairing work adds the shared guards: the self-send guard's invoice hashes, the QuickPay counts and +the open sends travel both ways (Shared guards, below). Part 3, a later PR, adds watch-specific limits, a payment +handed from the phone to the watch and the prompt to install the watch app. - **Off on mainnet.** `Env.isWatchLinkEnabled` is false on mainnet for as long as the watch app is (#2152). The phone's Watch row is then not shown, the link repository is not created at startup or by Settings, and the @@ -1089,11 +1094,121 @@ associated data. One key per direction, so a message cannot be sent back to its clock is off. A backup that is missing or unreadable does not turn QuickPay off while a push holds. When the pairing ends, the import holds again. - **A seam for another source.** The Data Layer is how the phone's state reaches the watch today. The watch may one - day read it from VSS instead, which is not possible yet. The sink is the seam for that: the settings now, and in - part 2 the invoice hashes, the QuickPay counts and the send records, land in the watch's stores through it, and - the guards read the stores. A source can be added or replaced without touching a guard. On the phone, + day read it from VSS instead, which is not possible yet. The sink is the seam for that: the settings, the invoice + hashes, the QuickPay count and the open sends land in the watch's stores through it, and the guards read the + stores. A source can be added or replaced without touching a guard. On the phone, `WatchLinkRepo` is the one place that publishes them. The watch stays read-only on VSS. +### Shared guards + +The phone and the watch spend from one Spark wallet. Three guards would each work on one device alone; paired, each +device tells the other what it needs, as three more documents per direction (`:wearlink` `LinkGuards`). Each is a +full snapshot with one writer, the device it describes, encrypted in the envelope above and stored by the carrier +for delivery after a reconnect. Each device publishes its three when the pairing is made and whenever one changes. + +| Document | Writer's content | Reader's rule | +|---|---|---| +| `p2w/invoices`, `w2p/invoices` | the payment hashes and expiries of its own unexpired invoices, the 1 000 that expire last: a format byte, the count, then 40 bytes each | refuses to pay them: the phone's toast "Cannot Pay Own Invoice", the watch's "Can't pay own invoice" | +| `p2w/quickpay`, `w2p/quickpay` | the day it last counted, as an ISO date of its own clock, and the US cents it spent under QuickPay that day; before it counted anything, an empty day and 0 | adds the cents to its own count when the day equals its own, and ignores them otherwise | +| `p2w/sends`, `w2p/sends` | its open sends: noted before they go out and kept until it learned their outcome, each with the idempotency key it went out under, the invoice's payment hash and expiry (which no reader uses), or the Spark payee of a transfer, and its start time; the newest 200 | refuses to send an invoice the other lists as open, for 5 minutes from its start: "Pending" | + +- **Invoices.** Each device keeps the other's hashes apart from its own, and each document replaces the last: the + watch in `PeerGuardStore` (in the settings file), never in `OwnInvoiceStore`, whose 200 entries the phone's could + push out; the phone in `WatchLinkStore`, never in `CacheStore.sparkOwnInvoices`, which is in the phone's backup + and whose entries a document full of far expiries could push out for good. `WalletSelfSendGuard` on the watch + and `SparkRepo.isOwnInvoice` on the phone ask both sets. Each publishes only its own, so no hash is sent back to + the device that made it. A peer's set that never arrived, or cannot be read, refuses nothing: the guard then + works as for an unpaired device. The own store's rule, a guard that cannot tell refuses, is unchanged. An invoice + made while the two are apart is unknown to the other until they reconnect. +- **Bounded by the reader's clock.** What a peer says is cut to the reader's clock when it arrives + (`LinkGuards`): no invoice expiry is taken further ahead than 7 days (`MAX_EXPIRY_AHEAD_SECS`, above the day a + phone invoice and the hour a watch invoice live), and no send's start later than now. A send the next document + lists again keeps the start it was stored with (`LinkGuards.keptStarts`), so a writer whose clock runs ahead does + not renew it each time its document arrives. A stored start later than the reader's now means the reader's clock + went back since, and the send is then stale (`LinkGuards.isStale`). So a peer whose clock runs ahead, or a + document forged with the link key, cannot leave anything that holds for good: an invoice is refused for a week at + most, an open send holds for minutes, a count for its day. +- **Versions.** The invoices document is binary and starts with a format byte. A reader refuses another format and + ignores whatever follows the invoices the count declares, which is where a later build adds to the format. The + other two are JSON, read with unknown fields ignored. +- **QuickPay count: one daily limit for the wallet.** The phone's daily limit (the QuickPay amount times the + multiplier) is the wallet's: phone and watch together stay within it. The watch's `QuickPayRepo` passes the + phone's cents of the day to `QuickPaySpendStore.reserve`, and the phone's `QuickPaySpendStore` adds the watch's to + the spend its reserve and `canApply` check, but never writes them into its own count, which is what it publishes. + Each count has one writer, so a release on one side just publishes a lower number. A device that has counted + nothing publishes an empty day and 0, so a new pairing replaces any count an earlier one left. A count that + cannot be read + answers no, as the rest of QuickPay does: the payment asks for the hold or the swipe. Apart, each side uses the + other's last count, so the two can together go over the limit by what the other spent since, at most one day's + limit. A send the watch made under QuickPay and still watches, cut off inside the call, that the phone then pays + under QuickPay after the 5 minutes below, is one payment both count, so the day's shared limit is used twice for + it. That only refuses more, and ends with the day. A per-device cap for the watch comes with part 3. +- **Open sends: the pending rule.** Before an invoice is sent, the watch (`PaymentsRepo`, before the review and + again at the send) and the phone (`SparkRepo.payInvoice`, after its checks of Spark's list and before anything is + noted) look up the other's open sends of that payment hash. One that counts refuses the send as pending: the + watch shows "Pending", the phone its pending screen, as for a send Spark lists as under way. It stops counting + when the other drops it, when Spark's own list shows that attempt failed (the key is the payment's id), or 5 + minutes after its start (below); the start bounds every open send, so the invoice's expiry decides nothing. A + list that cannot be read refuses nothing: the two + derive the same idempotency key for an invoice's attempt (`SparkSendKey`), so Spark pays it once anyway; the rule + closes the window in which the other's send is out and not yet listed, and spares the second device a send of + unknown outcome. +- **An open send holds the other device for 5 minutes** (`LinkGuards.OPEN_SEND_HOLD_SECS`). A send that is cut off + inside the SDK call, the usual way a watch send fails, leaves its note on the device and nothing on Spark, so + nothing would ever release it on the other device, and "it did not work on the watch, pay with the phone" would + show Pending until the invoice expired. Spark lists a send it took within moments, and both devices read the + same list, which then decides: pending holds, completed is paid, failed frees it. So the peer's note is needed + only until Spark could have listed the send. The SDK itself settles a Lightning payment within about 3 minutes + (the watch's `SETTLE_HOLD`); 5 minutes adds time for the document to cross and for the two clocks to differ. + After that the other device may send: it does so under the idempotency key both derive for the invoice, which + Spark pays once. The age is counted from the send's start by the writer's clock, cut to the reader's on arrival; + a writer whose clock runs behind by minutes holds the reader for that much less. +- **Spark-address transfers.** The watch adds the phone's open transfers to the same payee to the lookup it makes + before such a send: completed is "Already paid", failed is over, pending is "Pending", and one Spark does not + list is "Pending" for the same 5 minutes from its start and nothing after. The phone sends no transfers to Spark + addresses today, so it publishes none, and reads the watch's only for invoices. A transfer's key is random per + device, not shared as an invoice's is, so before the phone publishes transfers the watch has to reuse a stale + phone transfer's listed key, or hold transfers without the time limit; otherwise both could pay. +- **The phone's open sends** are its Spark sends held as of unknown outcome (`sparkUncertainSends`, with + `sparkSendAttemptIds` and the attempt's expiry). A hold an older build left without its key goes out with an + empty key, which no failed payment matches, so it holds for its 5 minutes. **The watch's** are + `UncertainSendStore`'s notes, which now keep the invoice's payment hash; a note written before that is read as + before and published without one. +- **One publisher for each document.** Each app has one coroutine per document, which publishes it when the pairing + is made, when its content changes, and when it is asked to publish again; so a newer document is never followed + by an older snapshot. A publish that fails is logged and made again at the next change or request, or when the + app starts: no retry runs in between, so a new invoice whose publish failed stays unknown to the other until + then, and a "settled" that did not go out holds the other for its 5 minutes at most. +- **Arriving before the other noted the pairing.** A document sent before the other side noted the pairing is + dropped there, and the carrier does not replay it. So each side publishes its three again once it knows the + other has noted the pairing: the phone at the watch's first status of the pairing (`PhoneLink`'s + `onWatchPaired`), whatever that status says of the settings, and the watch when the phone's `p2w/control` says + paired (`onPhonePaired`). Separately, the phone publishes its settings again when a status shows none applied. +- **Unpair, re-pair, wipe.** The end of a pairing, either side's, clears the other's invoice hashes, count and open + sends on both devices, and withdraws the documents from the carrier; a new pairing clears them again before its + first document. A clear that fails is logged and does not stop the pairing's end: the record, the published + documents and the keys still go, and the watch still lets the backup import hold again. Each device reads what + the other said only while it has a pairing. After an unpair, what a failed clear left is not read. After a + re-pair, it holds until the new peer's documents replace it, which they do as the pairing is noted, a count + included, and until then it only refuses more. Once unpaired, a device that still holds the wallet can pay the + other's invoices again, at a fee, as for any unpaired pair (Self-send guard). The watch's wipe clears all of it with the settings file; + the phone's reset forgets the watch, which clears the link store's. +- **Size on the watch.** The phone's up to 1 000 invoices are one string set of about 75 KB in the watch's + settings file, which every settings write rewrites. They stay there, so the one wipe note covers them; a file of + their own is the change to make if the writes ever show. +- **One writer, one seam.** On the phone `WatchLinkRepo` publishes the phone's documents and stores the watch's + (`WatchLinkStore` as `WatchGuardState`, read by `QuickPayRepo` and `SparkRepo`); on the watch `PhoneLinkRepo` does + the same through `PhoneStateSink`. A later source of the same state, such as VSS, would feed the same stores. +- **Not logged:** invoices, hashes and keys. The apps log the number of invoices or sends that arrived. +- **Tests.** `LinkGuardsTest` (both roles over the in-process carrier: delivery, replay, reflection, encryption, + malformed counts and sends, the bounds on arrival, the first status, a clear that fails, the rules and the + invoices encoding), `PhoneLinkRepoTest` and `WatchLinkRepoTest` (each app's repository against the other role, + with the publishing again and a full forged invoices document), `SelfSendGuardTest`, `PaymentsRepoTest`, + `QuickPayRepoTest` and the store tests on the watch (the spend store reading the phone's count from the same + settings file), and `QuickPayRepoTest` and `SparkRepoTest` on the phone. Journeys: + `send-phone-invoice-guard.xml` and `quickpay-shared-daily-limit.xml` over the debug socket, on the local + `./spark` stack only (see the note on #2152 in `journeys/wear/README.md`). + ### Unpair, erase and wipe - **Unpair from the phone.** The phone publishes "revoked" and marks its record. The watch forgets the phone, @@ -1199,8 +1314,12 @@ Watch: wallet. Pairing again then succeeds by proof. - The phone publishes its settings to the watch; the wearer's own unit swap still lasts only until the phone's setting changes, as for the import. -- Not in this part: the shared invoice hashes, QuickPay counts and send records (part 2); watch-specific limits, - the payment handoff and the install prompt (part 3). Until part 3 the watch's QuickPay follows the phone's. +- The shared guards hold only while the two reach each other: what one device did while apart reaches the other on + reconnect (Shared guards). A send started on both within the moment it takes a document to cross is refused by + neither, and neither is one started more than 5 minutes after the other's that Spark never listed; Spark's shared + idempotency key for an invoice still pays it once. +- Not in this part: watch-specific limits, the payment handoff and the install prompt (part 3). Until part 3 the + watch's QuickPay follows the phone's, within the one daily limit the two share. ## Seed storage diff --git a/journeys/README.md b/journeys/README.md index 5e79d56d35..2d90f003b9 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -140,7 +140,7 @@ journey PR, which is what made this file conflict on every merge. | A watch to run the Wear OS app on | a Wear OS watch emulator (`Wear_Large_Round_API37`, `Wear_Small_Round_API34`), or a physical watch over Wi-Fi debugging — [wear](wear/README.md) | | Watch gestures: pager swipes, swipe-to-dismiss, rotary crown, ambient mode | `adb shell input swipe`, `adb shell input rotaryencoder scroll --axis SCROLL,` and `KEYCODE_SLEEP`/`KEYCODE_WAKEUP` on the emulator; the real crown, bezel and wrist on a physical watch — [wear](wear/README.md#watch-gestures) | | The phone's settings on the watch (units, currency, QuickPay) | a phone dev build with the same private settings wallet (the test phrase with a passphrase kept on this machine), never the public test phrase alone, writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) | -| A phone and a watch that reach each other, for pairing | a phone emulator (`Bitkit_Phone_API36`) and a watch emulator with debug builds of both apps, joined by the debug socket carrier over `adb forward` and `adb reverse`; the Wear Data Layer itself, the watch's hardware Keystore and its attestation, and so a release-build seed transfer, are not covered — [wear](wear/README.md#phone-and-watch-over-the-debug-socket) | +| A phone and a watch that reach each other, for pairing and, on the local `./spark` stack only, the shared guards | a phone emulator (`Bitkit_Phone_API36`) and a watch emulator with debug builds of both apps, joined by the debug socket carrier over `adb forward` and `adb reverse`; the Wear Data Layer itself, the watch's hardware Keystore and its attestation, and so a release-build seed transfer, are not covered — [wear](wear/README.md#phone-and-watch-over-the-debug-socket) | | 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 2a13f06544..f9310cc4a6 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -139,6 +139,8 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `quickpay-on-app-start.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | | `quickpay-over-limit-holds.xml` | local, the private settings wallet, and a phone that wrote its settings | yes, 12 000 sats | | `quickpay-off-holds.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | +| `send-phone-invoice-guard.xml` | local only, phone and watch paired over the debug socket ([Two apps on one wallet](#two-apps-on-one-wallet)) | no | +| `quickpay-shared-daily-limit.xml` | local only, phone and watch paired over the debug socket ([Two apps on one wallet](#two-apps-on-one-wallet)) | yes, 20 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 @@ -183,7 +185,7 @@ On the local stack, `receive-paid.xml` funds the watch through its own receive Q 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. +keep both open on a wallet you keep; [Two apps on one wallet](#two-apps-on-one-wallet) has the exceptions. - **Hosted regtest:** send to the deposit address from https://app.lightspark.com/regtest-faucet (up to 50,000 sats per deposit). Lightspark mines about once a minute and Spark claims it after 3 confirmations. @@ -356,7 +358,8 @@ names this precondition: 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). + open on the same Spark network with this recovery phrase at the same time (#2152); the exceptions, which are + never this wallet, are in [Two apps on one wallet](#two-apps-on-one-wallet). 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 @@ -432,6 +435,30 @@ Notes: keys of each emulator. - To go back to the Data Layer, delete the file on both devices and restart both apps. +#### Two apps on one wallet + +Two live Spark instances on one seed are unsafe until #2152 is resolved, so everywhere else in this file the phone +app is closed before the watch app opens on the same wallet. The journeys of this section cannot keep that rule: +after a pairing both apps are open on one wallet. They are allowed under these conditions only, and never with +[the test wallet](#the-test-wallet), the [private settings wallet](#private-settings-wallet) or any wallet you +keep: + +- **The `pair-*.xml` journeys** use a wallet created in the phone's onboarding for the run, with no funds, and make + no payment. Wipe both apps when the run is over ([Fresh app](#fresh-app)). +- **The two shared-guard journeys** (`send-phone-invoice-guard.xml`, `quickpay-shared-daily-limit.xml`) receive and + pay on both devices, so they run **only on the local `./spark` stack, with throwaway funds**: the watch as in + [Local ./spark stack](#local-spark-stack), the phone as in the `spark-regtest` skill + (`.claude/plugins/spark-regtest`), with the same `SPARK_LOCAL_CONFIG_B64`. Never run them on hosted regtest or + any other Spark network. Build both apps for the local stack before the first pairing journey of the chain, so + the wallet never exists on a hosted network. The two share one Spark balance; fund it once. Run each `adb + reverse` of the stack's ports on both devices, with `-s`. +- **Afterwards**, compare the Spark balance on the two devices once both have synced. If they differ, or a send + ends in an error no step expects, note it against #2152 with the journey and step, and start over from a new + wallet: `../bitkit-docker/spark down`, then `up`, and [Fresh app](#fresh-app) on both devices. + +The pairing these two journeys need is one wallet on both devices, paired: `pair-receive-wallet.xml` alone leaves +that, and so does `pair-same-wallet.xml` after it and `pair-unpair-from-phone.xml`. + ### Restart The journeys restart the app with: @@ -819,7 +846,7 @@ same wallet the phone's invoice would be the watch's own. Debug builds log the t These need capabilities the journey environment lacks: a watch paired with the phone over the Wear Data Layer, which needs the companion app and a Google account, and a watch with a hardware Keystore. Run them with a phone and a physical Wear OS watch that are paired in the system, both with builds of the same flavor signed with the -same key. Tests 1 to 8 use dev builds without the `wearlink-socket` file; tests 3a and 9 need release-signed +same key. Tests 1 to 8 and 10 use dev builds without the `wearlink-socket` file; tests 3a and 9 need release-signed builds (`assembleDevRelease` of both apps with a local keystore). 1. **Discovery.** With the watch connected and Bitkit installed on it, open Settings › General › Watch on the phone. @@ -874,3 +901,13 @@ builds (`assembleDevRelease` of both apps with a local keystore). 8. **Wipe the phone's wallet** (Settings › Reset): the watch shows not paired and keeps its wallet. 9. **Release build has no socket.** With the `wearlink-socket` file created by hand in a release-signed build's data (rooted device or emulator): the app still uses the Data Layer, and nothing listens on port 47115. +10. **Shared guards over the Data Layer.** Paired over the system's Data Layer as in test 2, with both builds on + the local `./spark` stack and throwaway funds, never on hosted regtest + ([Two apps on one wallet](#two-apps-on-one-wallet)); both devices reach the stack through `adb reverse`. + - 10a. Make an invoice on the phone's Receive and open it on the watch (an NFC tag or the phone's share sheet): + "Can't pay own invoice". The same the other way round: the phone's toast "Cannot Pay Own Invoice". + - 10b. With QuickPay at $5 and 1×, pay $3 by QuickPay on the phone, then a $3 invoice on the watch: the watch + asks for the hold. + - 10c. With the watch out of range, make an invoice on the watch and open it on the phone: the phone pays it + while the two are apart (known gap); back in range and after a few seconds, a second watch invoice is refused. + - Not run yet. diff --git a/journeys/wear/quickpay-shared-daily-limit.xml b/journeys/wear/quickpay-shared-daily-limit.xml new file mode 100644 index 0000000000..1e1c0fd12d --- /dev/null +++ b/journeys/wear/quickpay-shared-daily-limit.xml @@ -0,0 +1,34 @@ + + + A paired phone and watch share one QuickPay daily limit, the phone's (docs/wear.md › Pairing › Shared guards): + each publishes what it spent under QuickPay today, and each adds the other's count of the same day. With QuickPay + at $5 and 1× on the phone, a payment of about $3 by QuickPay on the watch leaves too little of the day's $5 for + another $3 on the phone, which then asks for the swipe. The watch's payment skipping the hold proves the settings + reached it, so the phone's swipe can only come from the watch's count. Two emulators over the debug socket. + + Both apps are open on one wallet and both pay, which is unsafe on a wallet you keep (#2152): run this only on + the local ./spark stack with throwaway funds, never on hosted regtest (journeys/wear/README.md › Two apps on one + wallet). + + Precondition: journeys/wear/README.md › Phone and watch over the debug socket, with both apps built for the + local ./spark stack from the start and one wallet on both, paired: after pair-receive-wallet.xml, or after + pair-same-wallet.xml. A Spark balance of at least 20 000 sats, and no QuickPay payment made on either today. + Phone: Local Currency USD, on Home. Watch: on the Balance page with the loading ring stopped and a fiat value + showing. Note N, the sats worth $3 at the dollar rate the phone shows (Settings › Local Currency). README › + Phone settings on VSS, step 3, has the QuickPay sliders. + + + Run `adb -s $WATCH logcat -c` and `adb -s $PHONE logcat -c` + On the phone, open Settings ▸ QuickPay (tag "QuickpaySettings", past "QuickpayIntro-button" the first time) and turn QuickPay on (tag "QuickpayToggle") + Set the amount to $5 (tag "QuickpayAmountSlider") and the daily limit to 1× (tag "QuickpayDailyLimitSlider") by tapping the slider track above each stop's label, then return to the wallet overview + Wait up to 10 s until `adb -s $WATCH logcat -d -s BitkitWear` lists "Applied the settings the phone pushed" + Run `../bitkit-docker/spark invoice N` and note the BOLT11 invoice it prints as <first> + Run `adb -s $WATCH shell am start -a android.intent.action.VIEW -d "lightning:<first>" to.bitkit.dev` + Wait up to 20 s until "WatchSendSent" is listed on the watch, touching nothing, and verify `adb -s $WATCH logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay": the watch paid by QuickPay + Wait 5 s for the watch's count to reach the phone + Run `../bitkit-docker/spark invoice N` and note the BOLT11 invoice it prints as <second> + Run `adb -s $PHONE shell am start -a android.intent.action.VIEW -d "lightning:<second>" to.bitkit.dev` + Wait up to 15 s until the phone shows the review with the swipe (tags "SendConfirm" and "GRAB"), and verify `adb -s $PHONE logcat -d -s APP` lists "Skipping QuickPay: daily spend '<about 300>' + '<about 300>' exceeds cap '500'": the day's limit counts the watch's payment, not an unreadable count (which shows as 10^18) + Swipe "GRAB" to pay, complete authorization if requested, and verify it ends on the sent sheet + + diff --git a/journeys/wear/send-phone-invoice-guard.xml b/journeys/wear/send-phone-invoice-guard.xml new file mode 100644 index 0000000000..5d0b52fa6b --- /dev/null +++ b/journeys/wear/send-phone-invoice-guard.xml @@ -0,0 +1,32 @@ + + + A paired phone and watch refuse to pay each other's invoices (docs/wear.md › Pairing › Shared guards): each + publishes the payment hashes of its own invoices to the other. The phone's Spark invoice, opened as a + `lightning:` link on the watch, ends on "Can't pay own invoice" before any hold; the watch's Receive invoice, + opened on the phone, ends on the phone's "Cannot Pay Own Invoice" toast. Two emulators over the debug socket. + + Both apps are open on one wallet, which is unsafe on a wallet you keep (#2152): run this only on the local + ./spark stack with throwaway funds, never on hosted regtest (journeys/wear/README.md › Two apps on one wallet). + + Precondition: journeys/wear/README.md › Phone and watch over the debug socket, with both apps built for the + local ./spark stack from the start and one wallet on both, paired: after pair-receive-wallet.xml, or after + pair-same-wallet.xml. No balance is needed: both refusals come before any balance check. The phone has no + Lightning channel, so its Receive invoice is made on Spark, without an amount. Phone: on Home. Watch: on the + Balance page with the loading ring stopped. The toast never reaches `android layout`: take a screenshot within + 2 s. + + + On the phone, tap Receive (tag "Receive") and wait up to 15 s until the QR code (tag "QRCode") is listed and "ReceiveLightningLoading" is not + Read the unified `bitcoin:` URI from the content-desc of "QRCode" in `android layout` and note its `lightning=` value as <phone invoice>; never type it + Wait 5 s for the phone's invoices to reach the watch + Run `adb -s $WATCH shell am start -a android.intent.action.VIEW -d "lightning:<phone invoice>" to.bitkit.dev` + Wait up to 10 s until "WatchSendError" is listed on the watch, and verify it reads "Can't pay own invoice" and "WatchSendHold" is not listed + Tap "WatchSendClose" on the watch + On the phone, press the device back button until the wallet overview is visible + On the watch, swipe the pager left once (`adb -s $WATCH shell input swipe 400 227 60 227 300`) and tap "WatchReceiveOpen" + Wait up to 10 s until "WatchReceiveQr" is listed, then read the invoice from the watch's log as in README › Reading the receive invoice and note it as <watch invoice> + Wait 5 s for the watch's invoices to reach the phone + Run `adb -s $PHONE shell am start -a android.intent.action.VIEW -d "lightning:<watch invoice>" to.bitkit.dev` + Verify from a phone screenshot that an error toast titled "Cannot Pay Own Invoice" is visible (tag "SelfPaymentToast") and no Send sheet opened + + diff --git a/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt index 9a85e98806..fa5e2fda86 100644 --- a/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/OwnInvoiceStore.kt @@ -4,13 +4,17 @@ import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringSetPreferencesKey +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import to.bitkit.wearlink.PeerInvoice import javax.inject.Inject import javax.inject.Singleton /** * The payment hashes of the invoices this wallet created and that can still be paid, which the wallet refuses to pay - * itself. The watch adds each invoice it creates; a paired phone's hashes can be merged in with [add] too. + * itself. The watch adds each invoice it creates; a paired phone's are kept apart, in [PeerGuardStore]. */ interface OwnInvoiceStore { /** Remembers the invoice with [paymentHash], in hex, until [expiresAtSecs], its expiry in epoch seconds. */ @@ -21,6 +25,9 @@ interface OwnInvoiceStore { /** Whether [paymentHash], in hex of either case, is an unexpired invoice of this wallet. */ suspend fun contains(paymentHash: String): Boolean + + /** The invoices remembered, as they change, for the paired phone; expired ones are dropped as they are read. */ + val remembered: Flow> } /** @@ -44,6 +51,11 @@ class SettingsOwnInvoiceStore internal constructor( private val key = stringSetPreferencesKey("own_invoices") + override val remembered: Flow> = dataStore.data.map { prefs -> + val now = nowSecs() + decode(prefs[key]).filter { it.value > now }.map { PeerInvoice(it.key, it.value.toLong()) } + }.distinctUntilChanged() + override suspend fun add(paymentHash: String, expiresAtSecs: ULong) { val now = nowSecs() dataStore.edit { prefs -> diff --git a/wear/src/main/java/to/bitkit/wear/data/PeerGuardStore.kt b/wear/src/main/java/to/bitkit/wear/data/PeerGuardStore.kt new file mode 100644 index 0000000000..c76948b4bb --- /dev/null +++ b/wear/src/main/java/to/bitkit/wear/data/PeerGuardStore.kt @@ -0,0 +1,140 @@ +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 androidx.datastore.preferences.core.stringSetPreferencesKey +import kotlinx.coroutines.flow.first +import kotlinx.serialization.json.Json +import to.bitkit.wear.link.WatchLinkStore +import to.bitkit.wear.utils.Logger +import to.bitkit.wearlink.InvoicesDoc +import to.bitkit.wearlink.LinkGuards +import to.bitkit.wearlink.OpenSend +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc +import javax.inject.Inject +import javax.inject.Singleton + +/** + * What the paired phone last told the watch for the shared guards: its own unexpired invoices, which the watch + * refuses to pay, its QuickPay spend of its day, and its open sends. Kept apart from the watch's own stores, so the + * phone's many invoices never push the watch's own out of [OwnInvoiceStore]. Only [PhoneStateSink] writes it; the + * guards read it, and only while a pairing exists, as the phone reads what the watch said. The link bounds what + * arrives by the watch's clock (`LinkGuards.MAX_EXPIRY_AHEAD_SECS`): an open send holds for minutes, a count for its + * day, an invoice for a week at most. + */ +interface PeerGuardStore { + /** Replaces the phone's invoices with [invoices]. */ + suspend fun setInvoices(invoices: List) + + /** Whether [paymentHash], in hex of either case, is an unexpired invoice the phone created. */ + suspend fun containsInvoice(paymentHash: String): Boolean + + suspend fun setQuickPay(quickPay: QuickPayDoc) + + /** The phone's last QuickPay count, or null when none arrived. */ + suspend fun quickPay(): QuickPayDoc? + + /** + * Replaces the phone's open sends with [sends], each one already known keeping its earlier start. A stored list + * that cannot be decoded is replaced as if it were empty, so it never blocks the next one. + */ + suspend fun setSends(sends: List) + + /** The phone's open sends as it last listed them. */ + suspend fun sends(): List + + /** Drops the phone's invoices, count and open sends, as when the pairing ends. */ + suspend fun clear() +} + +/** + * [PeerGuardStore] in the watch's settings file, so the wallet's wipe clears it with the settings. At most + * [InvoicesDoc.MAX_INVOICES] invoices are kept, the ones that expire last, and expired ones are dropped on each write. + * A full set is about 75 KB of that file, which every settings write then rewrites; a file of its own would need + * the wipe to clear a second file under the same note, so it stays here while that costs nothing a wearer notices. + */ +@Singleton +class SettingsPeerGuardStore internal constructor( + private val dataStore: DataStore, + private val nowSecs: () -> Long, +) : PeerGuardStore { + companion object { + private const val TAG = "PeerGuardStore" + + /** Between an invoice's payment hash and its expiry in a stored entry. */ + private const val SEPARATOR = ':' + + /** Milliseconds in a second, for the epoch seconds the phone's documents carry. */ + private const val MILLIS_PER_SEC = 1_000L + private val json = Json { ignoreUnknownKeys = true } + } + + @Inject + constructor(dataStore: DataStore) : this(dataStore, { System.currentTimeMillis() / MILLIS_PER_SEC }) + + private val invoicesKey = stringSetPreferencesKey("peer_invoices") + private val quickPayDayKey = stringPreferencesKey("peer_quickpay_day") + private val quickPayCentsKey = longPreferencesKey("peer_quickpay_cents") + private val sendsKey = stringPreferencesKey("peer_sends") + + override suspend fun setInvoices(invoices: List) { + val now = nowSecs() + dataStore.edit { prefs -> + prefs[invoicesKey] = invoices + .filter { it.expiresAtSecs > now } + .sortedByDescending { it.expiresAtSecs } + .take(InvoicesDoc.MAX_INVOICES) + .mapTo(HashSet()) { "${it.paymentHash.lowercase()}$SEPARATOR${it.expiresAtSecs}" } + } + } + + override suspend fun containsInvoice(paymentHash: String): Boolean { + val hash = paymentHash.lowercase() + val entry = paired()?.get(invoicesKey).orEmpty().firstOrNull { it.substringBefore(SEPARATOR) == hash } + val expiresAt = entry?.substringAfter(SEPARATOR, "")?.toLongOrNull() ?: return false + return expiresAt > nowSecs() + } + + override suspend fun setQuickPay(quickPay: QuickPayDoc) { + dataStore.edit { prefs -> + prefs[quickPayDayKey] = quickPay.dayKey + prefs[quickPayCentsKey] = quickPay.spentCents + } + } + + override suspend fun quickPay(): QuickPayDoc? { + val prefs = paired() ?: return null + val day = prefs[quickPayDayKey] ?: return null + return QuickPayDoc(day, prefs[quickPayCentsKey] ?: return null) + } + + override suspend fun setSends(sends: List) { + dataStore.edit { prefs -> + val stored = runCatching { prefs.sends() } + .onFailure { Logger.warn("Failed to decode the stored phone sends, replacing them", it, context = TAG) } + .getOrDefault(emptyList()) + prefs[sendsKey] = json.encodeToString(LinkGuards.keptStarts(sends, stored)) + } + } + + override suspend fun sends(): List = paired()?.sends().orEmpty() + + override suspend fun clear() { + dataStore.edit { + it.remove(invoicesKey) + it.remove(quickPayDayKey) + it.remove(quickPayCentsKey) + it.remove(sendsKey) + } + } + + private suspend fun paired(): Preferences? = + dataStore.data.first().takeIf { it.contains(WatchLinkStore.RECORD_KEY) } + + private fun Preferences.sends(): List = + this[sendsKey]?.let { json.decodeFromString>(it) }.orEmpty() +} diff --git a/wear/src/main/java/to/bitkit/wear/data/PhoneStateSink.kt b/wear/src/main/java/to/bitkit/wear/data/PhoneStateSink.kt index d46fbb6e51..e646b88257 100644 --- a/wear/src/main/java/to/bitkit/wear/data/PhoneStateSink.kt +++ b/wear/src/main/java/to/bitkit/wear/data/PhoneStateSink.kt @@ -1,6 +1,9 @@ package to.bitkit.wear.data import to.bitkit.wear.models.PhoneSettings +import to.bitkit.wearlink.OpenSend +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.minutes @@ -35,6 +38,18 @@ interface PhoneStateSink { /** The pairing ended: the next backup import holds again, whatever its age. */ suspend fun onPushSourceGone() + + /** The phone's own unexpired invoices, which the watch refuses to pay; they replace the ones it said before. */ + suspend fun applyPeerInvoices(invoices: List) + + /** What the phone spent under QuickPay on its day, which counts against the watch's daily limit on that day. */ + suspend fun applyPeerQuickPay(quickPay: QuickPayDoc) + + /** The phone's open sends, whose invoices the watch does not pay while they are open. */ + suspend fun applyPeerSends(sends: List) + + /** The phone's count and open sends no longer hold, as when the pairing ended. */ + suspend fun clearPeerState() } /** @@ -54,6 +69,7 @@ interface PhoneStateSink { @Singleton class SettingsPhoneStateSink @Inject constructor( private val settingsStore: SettingsStore, + private val peerGuardStore: PeerGuardStore, ) : PhoneStateSink { companion object { /** How far ahead of the watch's clock the phone's time of a push is still taken as it is. */ @@ -81,4 +97,12 @@ class SettingsPhoneStateSink @Inject constructor( } override suspend fun onPushSourceGone() = settingsStore.clearPushedSettingsAt() + + override suspend fun applyPeerInvoices(invoices: List) = peerGuardStore.setInvoices(invoices) + + override suspend fun applyPeerQuickPay(quickPay: QuickPayDoc) = peerGuardStore.setQuickPay(quickPay) + + override suspend fun applyPeerSends(sends: List) = peerGuardStore.setSends(sends) + + override suspend fun clearPeerState() = peerGuardStore.clear() } 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 959a3771fd..614e0c2e52 100644 --- a/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/QuickPaySpendStore.kt @@ -5,22 +5,37 @@ 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 kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import javax.inject.Inject import javax.inject.Singleton /** What the watch's QuickPay payments added up to today, in US cents, for the daily limit. */ interface QuickPaySpendStore { /** - * Adds [cents] to the spend of [dayKey], an ISO date, unless that takes the day above [capCents]. Returns the day - * it was added to, or null when it was not. A day earlier than the one last counted does not start a new count: - * the payment is added to the day last counted, so setting the watch's date back frees nothing. + * Adds [cents] to the spend of [dayKey], an ISO date, unless that takes the day above [capCents] together with + * [peerCents] of that day, what the paired phone spent on it. Returns the day it was added to, or null when it was + * not. A day earlier than the one last counted does not start a new count: the payment is added to the day last + * counted, so setting the watch's date back frees nothing. */ - suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? + suspend fun reserve( + dayKey: String, + cents: Long, + capCents: Long, + peerCents: suspend (String) -> Long = { 0 }, + ): String? /** Takes [cents] out of the spend of [dayKey] again, when that is still the day counted. */ suspend fun release(dayKey: String, cents: Long) + + /** The watch's own count, as it changes: the day last counted and its cents, or null before the first. */ + val spent: Flow } +/** What the watch counted under QuickPay on [dayKey], in US cents. */ +data class QuickPaySpend(val dayKey: String, val cents: Long) + /** [QuickPaySpendStore] in the watch's settings file, so the wallet's wipe clears it with the settings. */ @Singleton class SettingsQuickPaySpendStore @Inject constructor( @@ -29,14 +44,24 @@ 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): String? { + override val spent: Flow = dataStore.data.map { prefs -> + prefs[dayKey]?.let { QuickPaySpend(it, prefs[centsKey] ?: 0L) } + }.distinctUntilChanged() + + override suspend fun reserve( + dayKey: String, + cents: Long, + capCents: Long, + peerCents: suspend (String) -> Long, + ): String? { if (cents <= 0 || capCents <= 0) return null var reservedDay: String? = null dataStore.edit { prefs -> val countedDay = prefs[this.dayKey] val day = if (countedDay == null || dayKey > countedDay) dayKey else countedDay val spent = if (day == countedDay) prefs[centsKey] ?: 0L else 0L - if (spent < 0 || cents > capCents - spent) return@edit + val peer = peerCents(day) + if (spent < 0 || peer < 0 || cents > capCents - spent - peer) return@edit prefs[this.dayKey] = day prefs[centsKey] = spent + cents reservedDay = day diff --git a/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt index fe56518f6a..fcbefbac7c 100644 --- a/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt +++ b/wear/src/main/java/to/bitkit/wear/data/UncertainSendStore.kt @@ -4,19 +4,25 @@ import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringSetPreferencesKey +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import to.bitkit.wearlink.OpenSend import javax.inject.Inject import javax.inject.Singleton /** * A send this watch handed to Spark under the idempotency [key], whose outcome it has not learned. [sparkPayee] is * set for a transfer to a Spark address: the Spark identity public key the address encodes, in hex, which is the - * same for every spelling of a wallet's address. [expiresAtSecs] is set for an invoice: its expiry in epoch seconds. + * same for every spelling of a wallet's address. [expiresAtSecs] and [paymentHash] are set for an invoice: its expiry + * in epoch seconds and its payment hash in hex. */ data class UncertainSend( val key: String, val sparkPayee: String? = null, val expiresAtSecs: ULong? = null, + val paymentHash: String? = null, ) /** @@ -50,6 +56,9 @@ interface UncertainSendStore { /** Drops the send under [key], whose outcome is known. */ suspend fun settle(key: String) + /** The noted sends as they change, for the paired phone, which does not pay what the watch may be paying. */ + val open: Flow> + /** * The keys of the noted transfers to the wallet with the identity key [sparkPayee], in either case, the newest * first. More than one is noted only when an earlier one could not be dropped. @@ -98,7 +107,10 @@ class SettingsUncertainSendStore internal constructor( /** How long a send whose outcome the wearer was not told is remembered, in seconds: 30 days. */ const val WATCHED_KEPT_SECS = 2_592_000uL private const val SEPARATOR = '|' - private const val FIELDS = 4 + private const val FIELDS = 5 + + /** Notes written before the payment hash was kept have one field less. */ + private const val OLD_FIELDS = 4 private const val WATCHED_FIELDS = 6 private const val SENT = "sent" private const val FAILED = "failed" @@ -129,6 +141,18 @@ class SettingsUncertainSendStore internal constructor( return wasNoted } + override val open: Flow> = dataStore.data.map { prefs -> + decode(prefs[key]).map { + OpenSend( + key = it.send.key, + paymentHash = it.send.paymentHash, + sparkPayee = it.send.sparkPayee, + expiresAtSecs = it.send.expiresAtSecs?.toLong(), + startedAtSecs = it.startedAtSecs.toLong(), + ) + }.sortedByDescending { it.startedAtSecs } + }.distinctUntilChanged() + override suspend fun settle(key: String) { dataStore.edit { prefs -> val sends = decode(prefs[this.key]) @@ -220,16 +244,19 @@ class SettingsUncertainSendStore internal constructor( send.sparkPayee.orEmpty(), send.expiresAtSecs?.toString().orEmpty(), startedAtSecs.toString(), + send.paymentHash.orEmpty(), ).joinToString(SEPARATOR.toString()) } private fun decode(entries: Set?): List = entries.orEmpty().mapNotNull { entry -> - val fields = entry.split(SEPARATOR).takeIf { it.size == FIELDS } ?: return@mapNotNull null + val fields = entry.split(SEPARATOR).takeIf { it.size == FIELDS || it.size == OLD_FIELDS } + ?: return@mapNotNull null val startedAt = fields[3].toULongOrNull() ?: return@mapNotNull null val send = UncertainSend( key = fields[0], sparkPayee = fields[1].takeIf { it.isNotEmpty() }, expiresAtSecs = fields[2].toULongOrNull(), + paymentHash = fields.getOrNull(4)?.takeIf { it.isNotEmpty() }, ) Entry(send, startedAt) } 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 2fff8bacb9..5359a57d19 100644 --- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt +++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt @@ -21,10 +21,12 @@ import to.bitkit.wear.data.ForegroundMonitor import to.bitkit.wear.data.NetworkMonitor import to.bitkit.wear.data.NfcMonitor import to.bitkit.wear.data.OwnInvoiceStore +import to.bitkit.wear.data.PeerGuardStore import to.bitkit.wear.data.PhoneStateSink import to.bitkit.wear.data.ProcessForegroundMonitor import to.bitkit.wear.data.QuickPaySpendStore import to.bitkit.wear.data.SettingsOwnInvoiceStore +import to.bitkit.wear.data.SettingsPeerGuardStore import to.bitkit.wear.data.SettingsPhoneStateSink import to.bitkit.wear.data.SettingsQuickPaySpendStore import to.bitkit.wear.data.SettingsUncertainSendStore @@ -108,6 +110,10 @@ abstract class SecurityModule { @Singleton abstract fun bindPhoneStateSink(sink: SettingsPhoneStateSink): PhoneStateSink + @Binds + @Singleton + abstract fun bindPeerGuardStore(store: SettingsPeerGuardStore): PeerGuardStore + @Binds @Singleton abstract fun bindLinkKeyStore(keys: KeystoreLinkKeys): LinkKeyStore diff --git a/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt b/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt index 9fed5a22fb..780c611fb9 100644 --- a/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt +++ b/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt @@ -24,7 +24,11 @@ import javax.inject.Singleton class WatchLinkStore @Inject constructor( private val dataStore: DataStore, ) : LinkRecordStore { - private val recordKey = stringPreferencesKey("phone_link") + companion object { + /** The settings key of the pairing record; what the phone said for the guards is read only while it is set. */ + val RECORD_KEY = stringPreferencesKey("phone_link") + } + private val installIdKey = stringPreferencesKey("link_install_id") override val record: Flow = dataStore.data.map { it.record() }.distinctUntilChanged() @@ -34,7 +38,7 @@ class WatchLinkStore @Inject constructor( override suspend fun update(transform: (LinkRecord?) -> LinkRecord?): LinkRecord? = dataStore.edit { prefs -> val updated = transform(prefs.record()) - if (updated == null) prefs.remove(recordKey) else prefs[recordKey] = updated.encode() + if (updated == null) prefs.remove(RECORD_KEY) else prefs[RECORD_KEY] = updated.encode() }.record() /** This install's id for pairings, made at first use. */ @@ -45,5 +49,5 @@ class WatchLinkStore @Inject constructor( } }[installIdKey].orEmpty().hexToByteArray() - private fun Preferences.record(): LinkRecord? = this[recordKey]?.let(LinkRecord::decode) + private fun Preferences.record(): LinkRecord? = this[RECORD_KEY]?.let(LinkRecord::decode) } 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 d77c4064f1..fd2e179c5d 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PaymentsRepo.kt @@ -34,6 +34,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import to.bitkit.wear.data.OwnInvoiceStore +import to.bitkit.wear.data.PeerGuardStore import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.UncertainSend import to.bitkit.wear.data.UncertainSendStore @@ -51,6 +52,8 @@ import to.bitkit.wear.services.SelfSendGuard import to.bitkit.wear.services.SparkError import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.utils.Logger +import to.bitkit.wearlink.LinkGuards +import to.bitkit.wearlink.OpenSend import java.net.URI import java.util.UUID import java.util.concurrent.ConcurrentHashMap @@ -74,10 +77,12 @@ class PaymentsRepo @Inject constructor( private val quickPayRepo: QuickPayRepo, private val sendMonitor: SendMonitor, private val sendOutcomeRepo: SendOutcomeRepo, + private val peerGuardStore: PeerGuardStore, ) { companion object { private const val TAG = "PaymentsRepo" private const val MSATS_PER_SAT = 1_000uL + private const val MILLIS_PER_SEC = 1_000L /** How long a receive invoice lives. The receive screen makes a new one when it expires. */ const val INVOICE_EXPIRY_SECS = 3_600u @@ -318,9 +323,9 @@ class PaymentsRepo @Inject constructor( * [SendError.NotReady], [SendError.AmountRequired], [SendError.AmountOutOfRange], [SendError.Expired], * [SendError.OwnInvoice], [SendError.InsufficientBalance], [SendError.Invalid] when an LNURL service answers with * an invoice of another amount, [SendError.AlreadyPaid] and [SendError.InFlight] for an invoice that Spark's - * list, as it is on the watch, shows this wallet paid or is paying, and for a Spark address whose earlier - * transfer of unknown outcome Spark now lists, and [SendError.Failed] when Spark cannot price it. Nothing is paid - * here. + * list, as it is on the watch, shows this wallet paid or is paying, or that the paired phone lists as an open + * send, and for a Spark address whose earlier transfer of unknown outcome Spark now lists, and [SendError.Failed] + * when Spark cannot price it. Nothing is paid here. */ suspend fun prepare(request: SendRequest, amountSats: ULong? = null): Result = withContext(ioDispatcher) { @@ -399,6 +404,7 @@ class PaymentsRepo @Inject constructor( if (input is InputType.Bolt11Invoice) { val listed = runSuspendCatching { sparkService.listPayments() }.getOrElse { throw SendError.NotReady() } ensureUnpaid(listed, input.v1.paymentHash) + ensureNotSentByPhone(listed, input.v1.paymentHash) } val response = runSuspendCatching { sparkService.prepareSend(paymentRequest, amountSats.takeIf { !isAmountInRequest }) @@ -451,6 +457,25 @@ class PaymentsRepo @Inject constructor( ?.let { throw SendError.InFlight(it.id, it.amount.toLong().toULong()) } } + private suspend fun ensureNotSentByPhone(listed: List, paymentHash: String) { + val failed = listed.filter { it.status == PaymentStatus.FAILED }.mapTo(HashSet()) { it.id } + val nowSecs = System.currentTimeMillis() / MILLIS_PER_SEC + if (LinkGuards.pendingSend(phoneSends(), paymentHash, failed, nowSecs) != null) { + Logger.info("Refused a send the phone has open", context = TAG) + throw SendError.InFlight() + } + } + + private fun isUnderWay(status: PaymentStatus?, isStale: Boolean): Boolean = when (status) { + PaymentStatus.FAILED -> false + null -> !isStale + else -> true + } + + private suspend fun phoneSends(): List = runSuspendCatching { peerGuardStore.sends() } + .onFailure { Logger.warn("Failed to read the phone's open sends", it, context = TAG) } + .getOrDefault(emptyList()) + /** * The Spark identity public key the Spark [address] encodes, in lowercase hex. The `sp…` and the `spark…` * spelling of one wallet's address give the same key, which is what an uncertain transfer is noted under. @@ -482,6 +507,13 @@ class PaymentsRepo @Inject constructor( * 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. * + * An invoice the paired phone lists as an open send is refused as [SendError.InFlight], shown as pending, until + * the phone drops it or Spark's list shows that attempt failed. A phone send started + * [LinkGuards.OPEN_SEND_HOLD_SECS] ago that Spark still does not list never reached it and no longer counts. A + * phone list that cannot be read refuses nothing: the two then still share the invoice's idempotency keys, which + * Spark pays once. When the phone then pays an invoice whose QuickPay send the watch still watches, both count the + * one payment against the shared daily limit until the day ends, which only refuses more. + * * A send that [skipConfirmation] counted against the QuickPay limit is taken out of the count again when it * fails with a [SendError] other than [SendError.Unknown]. One that is pending or unknown stays counted, and * [SendOutcomeRepo] takes it out when Spark later shows it failed. @@ -568,6 +600,7 @@ class PaymentsRepo @Inject constructor( private suspend fun invoiceKey(paymentHash: String): String { val listed = runSuspendCatching { sparkService.listPayments() }.getOrElse { throw SendError.NotReady() } ensureUnpaid(listed, paymentHash) + ensureNotSentByPhone(listed, paymentHash) val failed = listed.filter { it.status == PaymentStatus.FAILED }.mapTo(HashSet()) { it.id } fun key(attempt: Int) = runCatching { sparkService.sendKey(paymentHash, attempt) } .getOrElse { throw SendError.NotReady() } @@ -582,16 +615,26 @@ class PaymentsRepo @Inject constructor( * list decides: a transfer it shows completed is not sent again ([SendError.AlreadyPaid], once, as the wearer was * never told), one it shows pending is under way ([SendError.InFlight]), one it shows failed is over, and one it * does not show goes out again under its key, which pays once. Every noted transfer is asked about, so one that - * could not be dropped never hides another. A store or a list that cannot be read refuses the send. + * could not be dropped never hides another. A store or a list that cannot be read refuses the send. A transfer + * the paired phone lists as open to the same payee is the phone's to settle: completed, it is paid; failed, it is + * over; pending, or not listed and started within [LinkGuards.OPEN_SEND_HOLD_SECS], it is under way. One Spark + * does not list after that never reached it, and no longer holds the watch back. */ private suspend fun earlierTransferKey(sparkPayee: String): String? { val earlier = runSuspendCatching { uncertainSendStore.transferKeys(sparkPayee) } .getOrElse { throw SendError.Failed(it) } - if (earlier.isEmpty()) return null + val phone = LinkGuards.transfers(phoneSends(), sparkPayee).filter { it.key !in earlier } + if (earlier.isEmpty() && phone.isEmpty()) return null syncForSend() - val listed = runSuspendCatching { sparkService.listPayments().filter { it.id in earlier } } + val keys = earlier + phone.map { it.key } + val listed = runSuspendCatching { sparkService.listPayments().filter { it.id in keys } } .getOrElse { throw SendError.NotReady() } .associate { it.id to it.status } + // The phone's transfers are its own to settle: one it shows completed is paid, and one still open is under way. + if (phone.any { listed[it.key] == PaymentStatus.COMPLETED }) throw SendError.AlreadyPaid() + val nowSecs = System.currentTimeMillis() / MILLIS_PER_SEC + phone.firstOrNull { isUnderWay(listed[it.key], LinkGuards.isStale(it, nowSecs)) } + ?.let { throw SendError.InFlight(it.key.takeIf { key -> listed[key] == PaymentStatus.PENDING }) } earlier.filter { listed[it] == PaymentStatus.FAILED }.forEach { settle(it) } val completed = earlier.filter { listed[it] == PaymentStatus.COMPLETED } if (completed.isNotEmpty()) { @@ -643,7 +686,9 @@ class PaymentsRepo @Inject constructor( try { // Noted before it goes out, so a send the app is closed during is known to be in doubt afterwards. val wasUncertain = runSuspendCatching { - uncertainSendStore.begin(UncertainSend(key, prepared.sparkPayee, prepared.expiresAtSecs)) + uncertainSendStore.begin( + UncertainSend(key, prepared.sparkPayee, prepared.expiresAtSecs, prepared.paymentHash), + ) }.getOrElse { throw SendError.Failed(it) } // A wipe that ran meanwhile cleared the store before the note, which would outlive the wiped wallet. if (!isReady() || sparkService.isWiping) { diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt index dfb68f9093..408f3b96f3 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt @@ -10,11 +10,18 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import to.bitkit.wear.data.OwnInvoiceStore import to.bitkit.wear.data.PhoneStateSink import to.bitkit.wear.data.PhoneStateSource +import to.bitkit.wear.data.QuickPaySpendStore +import to.bitkit.wear.data.UncertainSendStore import to.bitkit.wear.di.IoDispatcher import to.bitkit.wear.env.Env import to.bitkit.wear.ext.runSuspendCatching @@ -31,8 +38,11 @@ import to.bitkit.wearlink.LinkKeyStore import to.bitkit.wearlink.LinkPacket import to.bitkit.wearlink.LinkRecord import to.bitkit.wearlink.LinkTransport +import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairingMode import to.bitkit.wearlink.PairingState +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc import to.bitkit.wearlink.SeedPayload import to.bitkit.wearlink.SeedStoreResult import to.bitkit.wearlink.SettingsDoc @@ -53,8 +63,10 @@ import javax.inject.Singleton * * A pairing runs only while the Pair screen asks for it, in this repo's own scope: once a seed has arrived it is * stored and answered even if the screen went away meanwhile. The phone's settings go to the [PhoneStateSink], as - * the backup import's do. The phone's erase command runs the wallet's own wipe, noted on disk before the phone is - * told, so an erase the phone was told about is always finished. + * the backup import's do, and so do its guard documents: its invoices, its QuickPay count and its open sends. The + * watch publishes its own three to the phone when the pairing is made, whenever they change, and again once the + * phone says it noted the pairing, each from its one publisher. The phone's erase command runs the wallet's own + * wipe, noted on disk before the phone is told, so an erase the phone was told about is always finished. */ @Singleton class PhoneLinkRepo internal constructor( @@ -68,6 +80,9 @@ class PhoneLinkRepo internal constructor( private val bip39: Bip39, private val sink: PhoneStateSink, private val deviceLock: DeviceLock, + private val ownInvoiceStore: OwnInvoiceStore, + private val spendStore: QuickPaySpendStore, + private val uncertainSendStore: UncertainSendStore, private val appId: String, private val nowMs: () -> Long, ) { @@ -88,6 +103,9 @@ class PhoneLinkRepo internal constructor( bip39: Bip39, sink: PhoneStateSink, deviceLock: DeviceLock, + ownInvoiceStore: OwnInvoiceStore, + spendStore: QuickPaySpendStore, + uncertainSendStore: UncertainSendStore, ) : this( ioDispatcher = ioDispatcher, transport = transport, @@ -99,11 +117,15 @@ class PhoneLinkRepo internal constructor( bip39 = bip39, sink = sink, deviceLock = deviceLock, + ownInvoiceStore = ownInvoiceStore, + spendStore = spendStore, + uncertainSendStore = uncertainSendStore, appId = context.packageName, nowMs = System::currentTimeMillis, ) private val scope = CoroutineScope(SupervisorJob() + ioDispatcher) + private val republish = MutableStateFlow(0) private val listener = object : WatchLinkListener { override suspend fun applySettings(settings: SettingsDoc) { @@ -133,6 +155,24 @@ class PhoneLinkRepo internal constructor( sink.onPushSourceGone() Logger.info("Ended the pairing with the phone", context = TAG) } + + override suspend fun applyInvoices(invoices: List) { + sink.applyPeerInvoices(invoices) + Logger.debug("Applied '${invoices.size}' invoices of the phone", context = TAG) + } + + override suspend fun applyQuickPay(quickPay: QuickPayDoc) = sink.applyPeerQuickPay(quickPay) + + override suspend fun applySends(sends: List) { + sink.applyPeerSends(sends) + Logger.debug("Applied '${sends.size}' open sends of the phone", context = TAG) + } + + override suspend fun clearPeerState() = runSuspendCatching { sink.clearPeerState() } + .onFailure { Logger.warn("Failed to clear the phone's guard state", it, context = TAG) } + .getOrThrow() + + override fun onPhonePaired() = republish.update { it + 1 } } private val link = WatchLink( @@ -166,6 +206,22 @@ class PhoneLinkRepo internal constructor( runSuspendCatching { if (store.load() == null) keys.clear() } .onFailure { Logger.warn("Failed to delete link keys without a pairing", it, context = TAG) } } + scope.launch { publishOnChange(ownInvoiceStore.remembered) { link.publishInvoices(it) } } + scope.launch { + val spent = spendStore.spent.map { spend -> spend?.let { QuickPayDoc(it.dayKey, it.cents) } } + publishOnChange(spent) { link.publishQuickPay(it) } + } + scope.launch { publishOnChange(uncertainSendStore.open) { link.publishSends(it) } } + } + + private suspend fun publishOnChange(state: Flow, publish: suspend (T) -> Unit) { + val pairing = store.record.map { it?.pairingId }.distinctUntilChanged() + combine(pairing, state.distinctUntilChanged(), republish) { pairingId, current, _ -> pairingId to current } + .collectLatest { (pairingId, current) -> + if (pairingId == null) return@collectLatest + runSuspendCatching { publish(current) } + .onFailure { Logger.warn("Failed to publish a guard document to the phone", it, context = TAG) } + } } /** 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 419668aca6..7c49d40351 100644 --- a/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt +++ b/wear/src/main/java/to/bitkit/wear/repositories/QuickPayRepo.kt @@ -6,6 +6,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.wear.data.PeerGuardStore import to.bitkit.wear.data.QuickPaySpendStore import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.di.IoDispatcher @@ -17,6 +18,7 @@ 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 to.bitkit.wearlink.LinkGuards import java.math.BigDecimal import java.math.RoundingMode import java.time.Instant @@ -29,6 +31,9 @@ import kotlin.time.Duration.Companion.seconds * Decides whether a payment goes out under the phone's QuickPay settings, which the watch imports and never sets, by * the rules of the phone's own `QuickPayRepo`: the same amount, rate, rounding and daily count. It reads the settings * as last imported, however long ago. Everything that is missing or unreadable answers no. + * + * The daily limit is the wallet's: what a paired phone last said it spent under QuickPay on the watch's day counts + * too, so the two together stay within the phone's daily limit (`docs/wear.md`, Pairing › Shared guards). */ @Singleton class QuickPayRepo internal constructor( @@ -36,6 +41,7 @@ class QuickPayRepo internal constructor( private val settingsStore: SettingsStore, private val currencyRepo: CurrencyRepo, private val spendStore: QuickPaySpendStore, + private val peerGuardStore: PeerGuardStore, private val nowMs: () -> Long, private val zone: () -> ZoneId, ) { @@ -53,11 +59,13 @@ class QuickPayRepo internal constructor( settingsStore: SettingsStore, currencyRepo: CurrencyRepo, spendStore: QuickPaySpendStore, + peerGuardStore: PeerGuardStore, ) : this( ioDispatcher, settingsStore, currencyRepo, spendStore, + peerGuardStore, System::currentTimeMillis, ZoneId::systemDefault, ) @@ -82,7 +90,8 @@ class QuickPayRepo internal constructor( * today's limit and returned as what [release] takes back. It may when QuickPay is on in the last import, the * amount is no more than the phone's QuickPay amount, in sats and in unrounded dollars at the dollar rate (the * phone checks the one when it offers QuickPay and the other when it pays), and today's QuickPay payments - * from this watch stay within the phone's daily limit with it. Any failure to read or count answers null. + * from this watch and the paired phone stay within the phone's daily limit with it. Any failure to read or count, + * also of the phone's count, answers null. */ suspend fun reserve(amountSats: ULong): QuickPayReservation? = withContext(ioDispatcher) { runSuspendCatching { mutex.withLock { reserveLocked(amountSats) } } @@ -110,7 +119,9 @@ class QuickPayRepo internal constructor( 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 + val dayKey = spendStore.reserve(today, cents, quickPay.dailyCapCents) { day -> + LinkGuards.peerCents(peerGuardStore.quickPay(), day) + } ?: return null return QuickPayReservation(dayKey, cents) } diff --git a/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt b/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt index babfaf9009..96e4402cc6 100644 --- a/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt +++ b/wear/src/main/java/to/bitkit/wear/services/SelfSendGuard.kt @@ -2,6 +2,9 @@ package to.bitkit.wear.services import breez_sdk_spark.InputType import to.bitkit.wear.data.OwnInvoiceStore +import to.bitkit.wear.data.PeerGuardStore +import to.bitkit.wear.ext.runSuspendCatching +import to.bitkit.wear.utils.Logger import javax.inject.Inject import javax.inject.Singleton @@ -20,20 +23,24 @@ interface SelfSendGuard { * - by the wallet's Spark identity public key, the one thing both devices share and an input can carry: a Spark * address encodes it, and a BOLT11 invoice carries it as the node of a route hint hop with the short channel id * [SPARK_ADDRESS_HINT_SCID], when the wallet that made it asked Spark to include its Spark address; - * - by payment hash, for the invoices in [OwnInvoiceStore]: the ones this device created, and a paired device's once - * they are shared with it. + * - by payment hash, for the invoices in [OwnInvoiceStore], the ones this device created, and in [PeerGuardStore], + * the ones the paired phone told it about. A phone's set that never arrived, or cannot be read, refuses nothing: + * the guard then works as for an unpaired watch. * * The identity alone does not recognise Bitkit's invoices: Bitkit creates them without the Spark address hint (the * SDK's `preferSparkOverLightning` is off), and such an invoice names only Spark's provider node, which every Spark * wallet shares. Verified on the local regtest stack with SDK 0.28.3. So an invoice the phone created is refused on - * the watch only once its hash reached the watch's [OwnInvoiceStore]. + * the watch only once its hash reached the watch's [PeerGuardStore]. */ @Singleton class WalletSelfSendGuard @Inject constructor( private val sparkService: WatchSparkService, private val ownInvoiceStore: OwnInvoiceStore, + private val peerGuardStore: PeerGuardStore, ) : SelfSendGuard { companion object { + private const val TAG = "SelfSendGuard" + /** * The route hint short channel id under which an invoice carries its Spark address, as the SDK's parser * prints it: the phone's `SPARK_ADDRESS_HINT_SCID`, 17592187092992000001, as block x transaction x output. @@ -54,7 +61,15 @@ class WalletSelfSendGuard @Inject constructor( } override suspend fun isOwn(input: InputType): Boolean { - if (input is InputType.Bolt11Invoice && ownInvoiceStore.contains(input.v1.paymentHash)) return true + if (input is InputType.Bolt11Invoice) { + if (ownInvoiceStore.contains(input.v1.paymentHash)) return true + if (isPhoneInvoice(input.v1.paymentHash)) return true + } return namesIdentity(input, sparkService.identityPubkey()) } + + private suspend fun isPhoneInvoice(paymentHash: String): Boolean = + runSuspendCatching { peerGuardStore.containsInvoice(paymentHash) } + .onFailure { Logger.warn("Failed to read the phone's invoices", it, context = TAG) } + .getOrDefault(false) } diff --git a/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt index 2176f896e0..3dc9d2aab3 100644 --- a/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/OwnInvoiceStoreTest.kt @@ -3,11 +3,13 @@ package to.bitkit.wear.data import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.job import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wearlink.PeerInvoice import java.io.File import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -15,6 +17,7 @@ import kotlin.test.assertTrue /** An [OwnInvoiceStore] in memory. */ class FakeOwnInvoiceStore : OwnInvoiceStore { val invoices = mutableMapOf() + override val remembered = MutableStateFlow>(emptyList()) var failure: Throwable? = null override suspend fun add(paymentHash: String, expiresAtSecs: ULong) { diff --git a/wear/src/test/java/to/bitkit/wear/data/PeerGuardStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/PeerGuardStoreTest.kt new file mode 100644 index 0000000000..5d7607773a --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/data/PeerGuardStoreTest.kt @@ -0,0 +1,193 @@ +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.stringPreferencesKey +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.link.WatchLinkStore +import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wearlink.InvoicesDoc +import to.bitkit.wearlink.LinkRecord +import to.bitkit.wearlink.OpenSend +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** A [PeerGuardStore] in memory. [failure] makes every read and write fail, as an unreadable file does. */ +class FakePeerGuardStore : PeerGuardStore { + var invoices = emptyList() + var quickPay: QuickPayDoc? = null + var sends = emptyList() + var failure: Throwable? = null + + override suspend fun setInvoices(invoices: List) = run { this.invoices = invoices } + + override suspend fun containsInvoice(paymentHash: String): Boolean { + failure?.let { throw it } + return invoices.any { it.paymentHash.equals(paymentHash, ignoreCase = true) } + } + + override suspend fun setQuickPay(quickPay: QuickPayDoc) = run { this.quickPay = quickPay } + + override suspend fun quickPay(): QuickPayDoc? { + failure?.let { throw it } + return quickPay + } + + override suspend fun setSends(sends: List) = run { this.sends = sends } + + override suspend fun sends(): List { + failure?.let { throw it } + return sends + } + + override suspend fun clear() { + invoices = emptyList() + quickPay = null + sends = emptyList() + } +} + +/** The store against the real settings file, in a temporary directory. Each [open] is a new process. */ +class PeerGuardStoreTest : BaseUnitTest() { + private companion object { + val HASH = "ab".repeat(32) + } + + @get:Rule + val folder = TemporaryFolder() + + private val settingsFile by lazy { File(folder.root, "datastore/settings.preferences_pb") } + private var scope: CoroutineScope? = null + private var link: WatchLinkStore? = null + private var dataStore: DataStore? = null + private var now = 1_000L + + @Test + fun `the phone's unexpired invoices are known in either case, also after a restart`() = test { + open().first.setInvoices(listOf(PeerInvoice(HASH, 2_000), PeerInvoice("cd".repeat(32), 500))) + close() + val sut = open().first + + assertTrue(sut.containsInvoice(HASH.uppercase())) + assertFalse(sut.containsInvoice("cd".repeat(32))) + now = 2_000 + assertFalse(sut.containsInvoice(HASH)) + close() + } + + @Test + fun `each set of invoices replaces the last, and at most a thousand are kept`() = test { + val sut = open().first + sut.setInvoices(listOf(PeerInvoice(HASH, 2_000))) + val many = List(InvoicesDoc.MAX_INVOICES + 1) { PeerInvoice("%064x".format(it), 5_000L + it) } + + sut.setInvoices(many) + + assertFalse(sut.containsInvoice(HASH)) + assertFalse(sut.containsInvoice(many.first().paymentHash)) + assertTrue(sut.containsInvoice(many.last().paymentHash)) + close() + } + + @Test + fun `the phone's invoices, count and sends are kept, and cleared with the pairing`() = test { + val sut = open().first + val send = OpenSend("key-0", paymentHash = HASH, expiresAtSecs = 2_000, startedAtSecs = 900) + sut.setInvoices(listOf(PeerInvoice(HASH, 2_000))) + sut.setQuickPay(QuickPayDoc("2026-11-28", 300)) + sut.setSends(listOf(send)) + close() + val next = open().first + assertEquals(QuickPayDoc("2026-11-28", 300), next.quickPay()) + assertEquals(listOf(send), next.sends()) + + next.clear() + + assertNull(next.quickPay()) + assertTrue(next.sends().isEmpty()) + assertFalse(next.containsInvoice(HASH)) + close() + } + + @Test + fun `nothing the phone said is read without a pairing`() = test { + val sut = open().first + sut.setInvoices(listOf(PeerInvoice(HASH, 2_000))) + sut.setQuickPay(QuickPayDoc("2026-11-28", 300)) + sut.setSends(listOf(OpenSend("key-0", paymentHash = HASH, startedAtSecs = 900))) + + link?.update { null } + + assertFalse(sut.containsInvoice(HASH)) + assertNull(sut.quickPay()) + assertTrue(sut.sends().isEmpty()) + close() + } + + @Test + fun `a send the phone lists again keeps its earlier start, and a new one takes its own`() = test { + val sut = open().first + sut.setSends(listOf(OpenSend("key-0", paymentHash = HASH, startedAtSecs = 900))) + + sut.setSends( + listOf( + OpenSend("key-0", paymentHash = HASH, startedAtSecs = 1_200), + OpenSend("key-1", paymentHash = HASH, startedAtSecs = 1_200), + ), + ) + + assertEquals(listOf(900L, 1_200L), sut.sends().map { it.startedAtSecs }) + close() + } + + @Test + fun `a stored sends list that cannot be decoded is replaced by the next one`() = test { + val sut = open().first + dataStore?.edit { it[stringPreferencesKey("peer_sends")] = "not json" } + val send = OpenSend("key-0", paymentHash = HASH, startedAtSecs = 900) + + sut.setSends(listOf(send)) + + assertEquals(listOf(send), sut.sends()) + close() + } + + @Test + fun `the wallet's wipe clears everything the phone said`() = test { + val (sut, settings) = open() + sut.setInvoices(listOf(PeerInvoice(HASH, 2_000))) + sut.setQuickPay(QuickPayDoc("2026-11-28", 300)) + + settings.finishWipe() + + assertFalse(sut.containsInvoice(HASH)) + assertNull(sut.quickPay()) + close() + } + + private suspend fun open(): Pair { + val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } + val dataStore = settingsDataStore(opened) { settingsFile }.also { this.dataStore = it } + val settings = SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") })) + val records = WatchLinkStore(dataStore).also { link = it } + if (records.load() == null) records.update { LinkRecord("0102030405060708", "aa", "node", "Pixel 9", 1) } + return SettingsPeerGuardStore(dataStore) { now } to settings + } + + private suspend fun close() { + scope?.coroutineContext?.job?.cancelAndJoin() + scope = null + } +} 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 b2e81f9d82..2b0b4d7337 100644 --- a/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt @@ -1,13 +1,21 @@ package to.bitkit.wear.data +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.job import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import to.bitkit.wear.link.WatchLinkStore import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wearlink.LinkGuards +import to.bitkit.wearlink.LinkRecord +import to.bitkit.wearlink.QuickPayDoc import java.io.File import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -19,20 +27,30 @@ class FakeQuickPaySpendStore : QuickPaySpendStore { var spentCents = 0L var failure: Throwable? = null - override suspend fun reserve(dayKey: String, cents: Long, capCents: Long): String? { + override val spent = MutableStateFlow(null) + + override suspend fun reserve( + dayKey: String, + cents: Long, + capCents: Long, + peerCents: suspend (String) -> Long, + ): String? { failure?.let { throw it } if (cents <= 0 || capCents <= 0) return null val isNewDay = day.let { it == null || dayKey > it } + val counted = if (isNewDay) dayKey else checkNotNull(day) val spent = if (isNewDay) 0L else spentCents - if (cents > capCents - spent) return null + if (cents > capCents - spent - peerCents(counted)) return null if (isNewDay) day = dayKey spentCents = spent + cents + this.spent.value = QuickPaySpend(counted, spentCents) return day } override suspend fun release(dayKey: String, cents: Long) { failure?.let { throw it } if (dayKey == day) spentCents = (spentCents - cents).coerceAtLeast(0L) + day?.let { spent.value = QuickPaySpend(it, spentCents) } } } @@ -48,6 +66,7 @@ class QuickPaySpendStoreTest : BaseUnitTest() { private val settingsFile by lazy { File(folder.root, "datastore/settings.preferences_pb") } private var scope: CoroutineScope? = null + private var dataStore: DataStore? = null @Test fun `a day takes payments up to its cap and not a cent more, also after a restart`() = test { @@ -144,9 +163,59 @@ class QuickPaySpendStoreTest : BaseUnitTest() { close() } + @Test + fun `the phone's spend of the counted day takes room from the cap, and the own count is published`() = test { + val sut = open().first + val days = mutableListOf() + val phone: suspend (String) -> Long = { day -> + days += day + 600 + } + + assertNull(sut.reserve(TODAY, cents = 401, capCents = 1_000, peerCents = phone)) + assertNotNull(sut.reserve(TODAY, cents = 400, capCents = 1_000, peerCents = phone)) + + assertEquals(listOf(TODAY, TODAY), days) + assertEquals(QuickPaySpend(TODAY, 400), sut.spent.first()) + close() + } + + @Test + fun `the phone's spend is asked for the day last counted when the watch's date went back`() = test { + val sut = open().first + assertNotNull(sut.reserve(TOMORROW, cents = 100, capCents = 1_000)) + val days = mutableListOf() + + sut.reserve(TODAY, cents = 100, capCents = 1_000) { day -> + days += day + 0 + } + + assertEquals(listOf(TOMORROW), days) + close() + } + + @Test + fun `the phone's count is read from its store in the same settings file while the watch's is written`() = test { + val sut = open().first + WatchLinkStore(checkNotNull(dataStore)).update { LinkRecord("0102030405060708", "aa", "node", "Pixel 9", 1) } + val peer = SettingsPeerGuardStore(checkNotNull(dataStore)) { 0 } + val phone: suspend (String) -> Long = { day -> LinkGuards.peerCents(peer.quickPay(), day) } + peer.setQuickPay(QuickPayDoc(TODAY, 600)) + + assertNull(sut.reserve(TODAY, cents = 401, capCents = 1_000, peerCents = phone)) + assertEquals(TODAY, sut.reserve(TODAY, cents = 400, capCents = 1_000, peerCents = phone)) + + peer.setQuickPay(QuickPayDoc(TODAY, 0)) + assertEquals(TODAY, sut.reserve(TODAY, cents = 600, capCents = 1_000, peerCents = phone)) + assertEquals(QuickPaySpend(TODAY, 1_000), sut.spent.first()) + assertEquals(QuickPayDoc(TODAY, 0), peer.quickPay()) + close() + } + private fun open(): Pair { val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } - val dataStore = settingsDataStore(opened) { settingsFile } + val dataStore = settingsDataStore(opened) { settingsFile }.also { dataStore = it } val settings = SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") })) return SettingsQuickPaySpendStore(dataStore) to settings } diff --git a/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt b/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt index 2200ba0b7f..1522922cab 100644 --- a/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt @@ -11,6 +11,9 @@ import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay import to.bitkit.wear.models.QuickPayLimits import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wearlink.OpenSend +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.QuickPayDoc import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -31,7 +34,8 @@ class SettingsPhoneStateSinkTest : BaseUnitTest() { val dataStore = settingsDataStore(CoroutineScope(Job())) { File(folder.root, "settings.preferences_pb") } SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") })) } - private val sut by lazy { SettingsPhoneStateSink(store) } + private val sut by lazy { SettingsPhoneStateSink(store, peer) } + private val peer = FakePeerGuardStore() private suspend fun quickPay() = store.data.first().quickPay @@ -132,4 +136,23 @@ class SettingsPhoneStateSinkTest : BaseUnitTest() { assertNull(store.pushedSettingsAtMs()) } + + @Test + fun `the phone's guard documents land in the peer store, and the pairing's end clears them`() = + test { + val send = OpenSend("key-0", paymentHash = "ab".repeat(32)) + sut.applyPeerInvoices(listOf(PeerInvoice("ab".repeat(32), 2_000))) + sut.applyPeerQuickPay(QuickPayDoc("2026-11-28", 300)) + sut.applyPeerSends(listOf(send)) + + assertEquals(listOf(PeerInvoice("ab".repeat(32), 2_000)), peer.invoices) + assertEquals(QuickPayDoc("2026-11-28", 300), peer.quickPay) + assertEquals(listOf(send), peer.sends) + + sut.clearPeerState() + + assertTrue(peer.invoices.isEmpty()) + assertNull(peer.quickPay) + assertTrue(peer.sends.isEmpty()) + } } diff --git a/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt index 0fecb9788e..f50a75314f 100644 --- a/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/UncertainSendStoreTest.kt @@ -1,13 +1,19 @@ package to.bitkit.wear.data +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringSetPreferencesKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update import kotlinx.coroutines.job import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import to.bitkit.wear.test.BaseUnitTest +import to.bitkit.wearlink.OpenSend import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -18,14 +24,21 @@ class FakeUncertainSendStore : UncertainSendStore { val sends = mutableMapOf() var failure: Throwable? = null + override val open = MutableStateFlow>(emptyList()) + override suspend fun begin(send: UncertainSend): Boolean { failure?.let { throw it } - return sends.put(send.key, send.copy(sparkPayee = send.sparkPayee?.lowercase())) != null + return (sends.put(send.key, send.copy(sparkPayee = send.sparkPayee?.lowercase())) != null).also { publish() } } override suspend fun settle(key: String) { failure?.let { throw it } sends.remove(key) + publish() + } + + private fun publish() = open.update { + sends.values.map { OpenSend(it.key, it.paymentHash, it.sparkPayee, it.expiresAtSecs?.toLong()) } } override suspend fun transferKeys(sparkPayee: String): List { @@ -65,6 +78,7 @@ class FakeUncertainSendStore : UncertainSendStore { class UncertainSendStoreTest : BaseUnitTest() { private companion object { const val PAYEE = "03a1b2c3d4e5f60718293a4b5c6d7e8f9001122334455667788990aabbccddeeff" + val HASH = "ab".repeat(32) } @get:Rule @@ -255,6 +269,33 @@ class UncertainSendStoreTest : BaseUnitTest() { close() } + @Test + fun `an invoice's send is noted with its payment hash and listed for the phone, also after a restart`() = test { + open().first.begin(UncertainSend("key-0", expiresAtSecs = 5_000uL, paymentHash = HASH)) + close() + val sut = open().first + + assertEquals( + listOf(OpenSend("key-0", paymentHash = HASH, expiresAtSecs = 5_000, startedAtSecs = 1_000)), + sut.open.first(), + ) + sut.settle("key-0") + assertTrue(sut.open.first().isEmpty()) + close() + } + + @Test + fun `a note written before payment hashes were kept is still read`() = test { + val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } + val dataStore = settingsDataStore(opened) { settingsFile } + dataStore.edit { it[stringSetPreferencesKey("uncertain_sends")] = setOf("key-old||5000|900") } + val sut = SettingsUncertainSendStore(dataStore) { now } + + assertEquals(listOf(OpenSend("key-old", expiresAtSecs = 5_000, startedAtSecs = 900)), sut.open.first()) + assertTrue(sut.begin(UncertainSend("key-old"))) + close() + } + private fun open(): Pair { val opened = CoroutineScope(testDispatcher + Job()).also { scope = it } val dataStore = settingsDataStore(opened) { settingsFile } diff --git a/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt b/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt index 4d6c4745b0..73cf9c393c 100644 --- a/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt @@ -13,10 +13,15 @@ import org.mockito.kotlin.doAnswer import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.data.FakeQuickPaySpendStore +import to.bitkit.wear.data.FakeUncertainSendStore import to.bitkit.wear.data.PhoneStateSink import to.bitkit.wear.data.PhoneStateSource +import to.bitkit.wear.data.UncertainSend import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay @@ -36,12 +41,19 @@ import to.bitkit.wearlink.AttestationPolicy import to.bitkit.wearlink.AttestationVerifier import to.bitkit.wearlink.Handshake import to.bitkit.wearlink.LinkError +import to.bitkit.wearlink.LinkGuards +import to.bitkit.wearlink.LinkPaths +import to.bitkit.wearlink.LinkRole +import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairedLink import to.bitkit.wearlink.PairingState import to.bitkit.wearlink.PairingThrottle +import to.bitkit.wearlink.PeerInvoice +import to.bitkit.wearlink.PeerStateListener import to.bitkit.wearlink.PhoneLink import to.bitkit.wearlink.PhonePairing import to.bitkit.wearlink.PhonePairingEnv +import to.bitkit.wearlink.QuickPayDoc import to.bitkit.wearlink.Removal import to.bitkit.wearlink.SeedPayload import to.bitkit.wearlink.SettingsDoc @@ -68,6 +80,7 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { const val APP_ID = "to.bitkit.dev" const val NOW = 1_800_000_000_000L const val MNEMONIC = "abandon ability able about" + val HASH = "ab".repeat(32) const val PASSPHRASE = "pass" val bip39 = FakeBip39() @@ -85,6 +98,28 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { private val walletRepo = mock() private val sink = mock() private val agreementKey = SoftwareAgreementKey() + private val ownInvoices = FakeOwnInvoiceStore() + private val spend = FakeQuickPaySpendStore() + private val uncertainSends = FakeUncertainSendStore() + + /** What the phone's side holds of the watch's guard documents. */ + private val phonePeer = object : PeerStateListener { + var invoices: List? = null + var quickPay: QuickPayDoc? = null + var sends: List? = null + + override suspend fun applyInvoices(invoices: List) = run { this.invoices = invoices } + + override suspend fun applyQuickPay(quickPay: QuickPayDoc) = run { this.quickPay = quickPay } + + override suspend fun applySends(sends: List) = run { this.sends = sends } + + override suspend fun clearPeerState() { + invoices = null + quickPay = null + sends = null + } + } private lateinit var network: FakeLinkNetwork private lateinit var store: WatchLinkStore @@ -96,7 +131,7 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { private fun TestScope.setUp() { network = FakeLinkNetwork(backgroundScope) store = WatchLinkStore(InMemoryDataStore(emptyPreferences())) - phoneLink = PhoneLink(network.phone, phoneKeys, phoneStore, nowMs = { NOW }) + phoneLink = PhoneLink(network.phone, phoneKeys, phoneStore, phonePeer, nowMs = { NOW }) network.phone.attach { packet -> runCatching { phoneLink.onPacket(packet) } } whenever { walletRepo.restore(any()) }.doAnswer { seedStore.seed = it.getArgument(0) @@ -117,6 +152,9 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { bip39 = bip39, sink = sink, deviceLock = FakeDeviceLock(), + ownInvoiceStore = ownInvoices, + spendStore = spend, + uncertainSendStore = uncertainSends, appId = APP_ID, nowMs = { NOW }, ) @@ -323,6 +361,105 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertNull(store.load()) } + @Test + fun `the phone's invoices, count and open sends go to the sink`() = test { + setUp() + seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) + pair().getOrThrow() + val send = OpenSend("key-0", paymentHash = HASH, expiresAtSecs = 2_000) + + phoneLink.publishInvoices(listOf(PeerInvoice(HASH, 2_000))) + phoneLink.publishQuickPay(QuickPayDoc("2026-11-28", 300)) + phoneLink.publishSends(listOf(send)) + runCurrent() + + verify(sink).applyPeerInvoices(listOf(PeerInvoice(HASH, 2_000))) + verify(sink).applyPeerQuickPay(QuickPayDoc("2026-11-28", 300)) + verify(sink).applyPeerSends(listOf(send)) + } + + @Test + fun `the watch publishes its invoices, count and open sends once paired, and again when they change`() = test { + setUp() + seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) + ownInvoices.remembered.value = listOf(PeerInvoice(HASH, 2_000)) + spend.reserve("2026-11-28", cents = 120, capCents = 1_000) + pair().getOrThrow() + runCurrent() + + assertEquals(listOf(PeerInvoice(HASH, 2_000)), phonePeer.invoices) + assertEquals(QuickPayDoc("2026-11-28", 120), phonePeer.quickPay) + assertEquals(emptyList(), phonePeer.sends) + + uncertainSends.begin(UncertainSend("key-0", expiresAtSecs = 2_000uL, paymentHash = HASH)) + spend.release("2026-11-28", cents = 20) + runCurrent() + + assertEquals(listOf(OpenSend("key-0", HASH, expiresAtSecs = 2_000)), phonePeer.sends) + assertEquals(QuickPayDoc("2026-11-28", 100), phonePeer.quickPay) + } + + @Test + fun `the watch publishes its guard documents again once the phone says it noted the pairing`() = test { + setUp() + seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) + ownInvoices.remembered.value = listOf(PeerInvoice(HASH, NOW / 1_000 + 60)) + spend.reserve("2026-11-28", cents = 120, capCents = 1_000) + uncertainSends.begin(UncertainSend("key-0", paymentHash = HASH)) + + // The watch notes the pairing first, so the phone drops what the watch publishes at once. + pair().getOrThrow() + runCurrent() + + LinkGuards.KINDS.forEach { kind -> + val path = LinkPaths.guard(LinkRole.Watch, kind) + assertEquals(2, network.sent.count { it.isState && it.path.endsWith(path) }, kind) + } + assertEquals(listOf(PeerInvoice(HASH, NOW / 1_000 + 60)), phonePeer.invoices) + assertEquals(QuickPayDoc("2026-11-28", 120), phonePeer.quickPay) + assertEquals(listOf("key-0"), phonePeer.sends?.map { it.key }) + } + + @Test + fun `a new pairing and an unpair each clear what a phone said for the guards`() = test { + setUp() + seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) + pair().getOrThrow() + verify(sink).clearPeerState() + + phoneLink.remove(isErase = false) + runCurrent() + + verify(sink, times(2)).clearPeerState() + } + + @Test + fun `a clear of what a phone said that fails does not stop a new pairing or an unpair`() = test { + setUp() + seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) + whenever { sink.clearPeerState() }.thenThrow(IllegalStateException("disk")) + + pair().getOrThrow() + assertNotNull(store.load()) + + phoneLink.remove(isErase = false) + runCurrent() + + assertNull(store.load()) + verify(sink, times(2)).clearPeerState() + } + + @Test + fun `the watch publishes a count of no day before it spent anything under quickpay`() = test { + setUp() + seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) + + pair().getOrThrow() + runCurrent() + + assertEquals(QuickPayDoc(LinkGuards.NO_DAY, 0), phonePeer.quickPay) + } + @Test fun `the wearer's unpair tells the phone and forgets it`() = test { setUp() 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 10f4a39414..77ebd55add 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -35,6 +35,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.data.FakePeerGuardStore import to.bitkit.wear.data.FakeUncertainSendStore import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.UncertainSend @@ -64,6 +65,8 @@ import to.bitkit.wear.services.WalletSelfSendGuard import to.bitkit.wear.services.WatchSparkService import to.bitkit.wear.test.BaseUnitTest import to.bitkit.wear.ui.LaunchRequest +import to.bitkit.wearlink.LinkGuards +import to.bitkit.wearlink.OpenSend import java.math.BigInteger import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -80,6 +83,9 @@ class PaymentsRepoTest : BaseUnitTest() { const val BALANCE = 10_000uL const val FEE = 4uL val RESERVATION = QuickPayReservation("2026-11-28", cents = 50) + + /** An invoice expiry no test reaches. */ + const val FAR_FUTURE = 4_000_000_000L } private val sparkService = mock() @@ -88,6 +94,7 @@ class PaymentsRepoTest : BaseUnitTest() { private val walletState = MutableStateFlow(WalletState(WalletStatus.Ready, BALANCE, hasSynced = true)) private val ownInvoices = FakeOwnInvoiceStore() private val uncertainSends = FakeUncertainSendStore() + private val phone = FakePeerGuardStore() private val decoder = FakeInputDecoder() private val quickPayRepo = mock() private val sendMonitor = SendMonitor() @@ -119,12 +126,13 @@ class PaymentsRepoTest : BaseUnitTest() { sparkService, walletRepo, decoder, - WalletSelfSendGuard(sparkService, ownInvoices), + WalletSelfSendGuard(sparkService, ownInvoices, phone), ownInvoices, uncertainSends, quickPayRepo, sendMonitor, sendOutcomeRepo, + phone, ) } @@ -143,12 +151,13 @@ class PaymentsRepoTest : BaseUnitTest() { sparkService, walletRepo, decoder, - WalletSelfSendGuard(sparkService, ownInvoices), + WalletSelfSendGuard(sparkService, ownInvoices, phone), ownInvoices, uncertainSends, quickPayRepo, sendMonitor, sendOutcomeRepo, + phone, ) } @@ -1375,7 +1384,11 @@ class PaymentsRepoTest : BaseUnitTest() { error = SdkException.NetworkException("reset") sut.send(preparedSend()) assertEquals( - UncertainSend("key-0", expiresAtSecs = SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY), + UncertainSend( + "key-0", + expiresAtSecs = SparkFixtures.TIMESTAMP + SparkFixtures.EXPIRY, + paymentHash = PAYMENT_HASH, + ), uncertainSends.sends.values.single(), ) } @@ -1768,6 +1781,119 @@ class PaymentsRepoTest : BaseUnitTest() { collecting.cancel() } + // region the paired phone's open sends + + @Test + fun `an invoice the phone has an open send of is pending, before the review and at the send`() = test { + val prepared = preparedSend() + phone.sends = listOf(openByPhone("key-0", paymentHash = PAYMENT_HASH.uppercase())) + + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + assertIs(sut.send(prepared).exceptionOrNull()) + + verify(sparkService, never()).send(any(), any()) + assertTrue(uncertainSends.sends.isEmpty()) + } + + @Test + fun `a phone send whose attempt spark lists failed no longer holds the invoice, which goes out next`() = test { + phone.sends = listOf(openByPhone("key-0")) + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("key-0", PaymentStatus.FAILED))) + whenever(sparkService.send(any(), eq("key-1"))).thenReturn(payment("key-1", PaymentStatus.COMPLETED)) + + sut.send(preparedSend()).getOrThrow() + + verify(sparkService).send(any(), eq("key-1")) + } + + @Test + fun `a phone send of another invoice holds nothing`() = test { + phone.sends = listOf(openByPhone("other", paymentHash = "cc".repeat(32))) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + + sut.send(preparedSend()).getOrThrow() + } + + @Test + fun `a phone send spark never listed stops holding the invoice five minutes after its start`() = test { + val started = System.currentTimeMillis() / 1_000 - LinkGuards.OPEN_SEND_HOLD_SECS + phone.sends = listOf(openByPhone("key-0").copy(startedAtSecs = started + 60)) + assertIs(sut.prepare(SendRequest.Invoice(BOLT11, 500uL, null)).exceptionOrNull()) + + phone.sends = listOf(openByPhone("key-0").copy(startedAtSecs = started)) + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + + sut.send(preparedSend()).getOrThrow() + + verify(sparkService).send(any(), eq("key-0")) + } + + @Test + fun `a phone list that cannot be read holds nothing`() = test { + val prepared = preparedSend() + phone.failure = IllegalStateException("disk") + whenever(sparkService.send(any(), eq("key-0"))).thenReturn(payment("key-0", PaymentStatus.COMPLETED)) + + sut.send(prepared).getOrThrow() + } + + @Test + fun `an invoice send is noted with its payment hash, so the phone learns which invoice it pays`() = test { + var noted: List? = null + whenever(sparkService.send(any(), eq("key-0"))).doSuspendableAnswer { + noted = uncertainSends.open.value + payment("key-0", PaymentStatus.COMPLETED) + } + + sut.send(preparedSend()).getOrThrow() + + assertEquals(PAYMENT_HASH, noted?.single()?.paymentHash) + assertEquals("key-0", noted?.single()?.key) + } + + @Test + fun `a transfer the phone has open to the same payee is told as under way, paid or over`() = test { + stubTransfer() + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + val nowSecs = System.currentTimeMillis() / 1_000 + phone.sends = listOf(OpenSend("phone-key", sparkPayee = OTHER_IDENTITY.uppercase(), startedAtSecs = nowSecs)) + + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("phone-key", PaymentStatus.COMPLETED, paymentHash = null))) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("phone-key", PaymentStatus.FAILED, paymentHash = null))) + sut.prepare(request, 500uL).getOrThrow() + } + + @Test + fun `a phone transfer spark never listed stops holding the payee five minutes after its start`() = test { + stubTransfer() + val request = SendRequest.SparkAddress(SPARK_ADDRESS) + val started = System.currentTimeMillis() / 1_000 - LinkGuards.OPEN_SEND_HOLD_SECS + phone.sends = listOf(OpenSend("phone-key", sparkPayee = OTHER_IDENTITY, startedAtSecs = started)) + + sut.prepare(request, 500uL).getOrThrow() + + // One Spark does list as pending is under way however old its note is. + whenever(sparkService.listPayments(anyOrNull())) + .thenReturn(listOf(payment("phone-key", PaymentStatus.PENDING, paymentHash = null))) + assertIs(sut.prepare(request, 500uL).exceptionOrNull()) + } + + // endregion + + private fun openByPhone(key: String, paymentHash: String = PAYMENT_HASH) = OpenSend( + key = key, + paymentHash = paymentHash, + expiresAtSecs = FAR_FUTURE, + startedAtSecs = System.currentTimeMillis() / 1_000, + ) + private suspend fun stubLnurlInvoice() { decoder.lnurlInvoices[15_000uL] = LNURL_BOLT11 decoder.inputs[LNURL_BOLT11] = lightning(LNURL_BOLT11, amountSats = 15uL) 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 2413efa15d..3e3bba5e63 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -14,12 +14,14 @@ 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.FakePeerGuardStore 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 to.bitkit.wearlink.QuickPayDoc import java.io.IOException import java.time.ZoneId import kotlin.test.assertEquals @@ -44,6 +46,7 @@ class QuickPayRepoTest : BaseUnitTest() { private val settingsStore = mock() private val currencyRepo = mock() private val spend = FakeQuickPaySpendStore() + private val phone = FakePeerGuardStore() 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"))) @@ -56,7 +59,7 @@ class QuickPayRepoTest : BaseUnitTest() { whenever(settingsStore.data).thenReturn(settings) whenever(currencyRepo.rates).thenReturn(rates) whenever { currencyRepo.refresh() }.thenReturn(Result.success(Unit)) - sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, { now }, { zone }) + sut = QuickPayRepo(testDispatcher, settingsStore, currencyRepo, spend, phone, { now }, { zone }) } @Test @@ -287,4 +290,29 @@ class QuickPayRepoTest : BaseUnitTest() { whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) assertNull(sut.reserve(1uL)) } + + @Test + fun `what the phone spent today counts against the one daily limit`() = test { + phone.quickPay = QuickPayDoc("2026-11-28", 1_000) + + assertNotNull(sut.reserve(FIVE_DOLLARS)) + assertNull(sut.reserve(1uL)) + assertEquals(500L, spend.spentCents) + } + + @Test + fun `what the phone spent on another day counts for nothing`() = test { + phone.quickPay = QuickPayDoc("2026-11-27", 1_500) + + repeat(3) { assertNotNull(sut.reserve(FIVE_DOLLARS)) } + assertNull(sut.reserve(1uL)) + } + + @Test + fun `a phone count that cannot be read skips nothing`() = test { + phone.failure = IOException("disk") + + assertNull(sut.reserve(1uL)) + assertEquals(0L, spend.spentCents) + } } 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 e0a79d08f3..270106e4cd 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt @@ -22,6 +22,7 @@ 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.FakePeerGuardStore import to.bitkit.wear.data.SettingsPhoneStateSink import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.models.BitcoinDisplayUnit @@ -90,7 +91,7 @@ class SettingsSyncRepoTest : BaseUnitTest() { seedStore, reader, settingsStore, - SettingsPhoneStateSink(settingsStore), + SettingsPhoneStateSink(settingsStore, FakePeerGuardStore()), sparkService, walletRepo, { elapsedMs }, @@ -262,7 +263,7 @@ class SettingsSyncRepoTest : BaseUnitTest() { BACKUP }, settingsStore, - SettingsPhoneStateSink(settingsStore), + SettingsPhoneStateSink(settingsStore, FakePeerGuardStore()), sparkService, walletRepo, { elapsedMs }, diff --git a/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt b/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt index bfbfca983d..d2b38f9424 100644 --- a/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt +++ b/wear/src/test/java/to/bitkit/wear/services/SelfSendGuardTest.kt @@ -6,6 +6,7 @@ import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.wear.data.FakeOwnInvoiceStore +import to.bitkit.wear.data.FakePeerGuardStore import to.bitkit.wear.services.SparkFixtures.IDENTITY import to.bitkit.wear.services.SparkFixtures.OTHER_IDENTITY import to.bitkit.wear.services.SparkFixtures.PAYMENT_HASH @@ -15,6 +16,7 @@ import to.bitkit.wear.services.SparkFixtures.SPARK_ADDRESS_HINT import to.bitkit.wear.services.SparkFixtures.hint import to.bitkit.wear.services.SparkFixtures.invoiceInput import to.bitkit.wear.services.SparkFixtures.sparkAddressInput +import to.bitkit.wearlink.PeerInvoice import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -22,7 +24,8 @@ import kotlin.test.assertTrue class SelfSendGuardTest { private val sparkService = mock() private val store = FakeOwnInvoiceStore() - private val sut = WalletSelfSendGuard(sparkService, store) + private val phone = FakePeerGuardStore() + private val sut = WalletSelfSendGuard(sparkService, store, phone) @Test fun `a spark address of this wallet's identity is its own, in either case`() = runTest { @@ -90,4 +93,22 @@ class SelfSendGuardTest { assertFailsWith { sut.isOwn(invoiceInput()) } assertFailsWith { sut.isOwn(sparkAddressInput()) } } + + @Test + fun `an invoice the paired phone created is its own`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + phone.invoices = listOf(PeerInvoice(PAYMENT_HASH.uppercase(), Long.MAX_VALUE)) + + assertTrue(sut.isOwn(invoiceInput())) + } + + @Test + fun `a phone set that cannot be read refuses nothing more than an unpaired watch`() = runTest { + whenever(sparkService.identityPubkey()).thenReturn(IDENTITY) + phone.failure = IllegalStateException("disk") + + assertFalse(sut.isOwn(invoiceInput())) + store.add(PAYMENT_HASH, ULong.MAX_VALUE) + assertTrue(sut.isOwn(invoiceInput())) + } } diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt index c7009b7137..7b441ded8d 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt @@ -16,6 +16,8 @@ abstract class LinkEndpoint internal constructor( protected val transport: LinkTransport, protected val keys: LinkKeyStore, protected val store: LinkRecordStore, + private val peer: PeerStateListener, + protected val nowMs: () -> Long, ) { private val mutex = Mutex() private val _pairingPackets = MutableSharedFlow(extraBufferCapacity = PAIRING_BUFFER) @@ -37,7 +39,7 @@ abstract class LinkEndpoint internal constructor( val name = LinkPaths.stateName(record.pairingId, packet.path) ?: throw LinkError.Rejected("another pairing") val channel = channel(record.pairingId) val opened = channel.open(packet.path, packet.payload) - apply(record, name, opened.body, opened.counter) + if (!applyGuard(name, opened.body)) apply(record, name, opened.body, opened.counter) // A document that ended the pairing took its record with it. if (store.load()?.pairingId == record.pairingId) channel.commit(packet.path, opened.counter) } @@ -45,6 +47,41 @@ abstract class LinkEndpoint internal constructor( internal abstract suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long) + private suspend fun applyGuard(name: String, body: ByteArray): Boolean { + val nowSecs = nowMs() / MILLIS_PER_SEC + when (name) { + LinkPaths.guard(role.peer, LinkGuards.INVOICES) -> + peer.applyInvoices(LinkGuards.bounded(InvoicesDoc.decode(body).invoices, nowSecs)) + LinkPaths.guard(role.peer, LinkGuards.QUICKPAY) -> peer.applyQuickPay(decode(body).validated()) + LinkPaths.guard(role.peer, LinkGuards.SENDS) -> + peer.applySends(LinkGuards.boundedSends(decode(body).validated().sends, nowSecs)) + else -> return false + } + return true + } + + /** Publishes this device's own unexpired invoices, so the peer refuses to pay them. */ + suspend fun publishInvoices(invoices: List) = + publishGuard(LinkGuards.INVOICES, InvoicesDoc(invoices).encode()) + + /** + * Publishes what this device spent under QuickPay on its own day, or with null, before it spent anything, a count + * of [LinkGuards.NO_DAY], which replaces whatever an earlier pairing's peer kept. + */ + suspend fun publishQuickPay(quickPay: QuickPayDoc?) = + publishGuard(LinkGuards.QUICKPAY, encode(quickPay ?: QuickPayDoc(LinkGuards.NO_DAY, 0))) + + /** + * Publishes this device's open sends, the newest [SendsDoc.MAX_SENDS]. Like the other guard documents, nothing + * is published without a pairing, or while the phone waits for a removal. + */ + suspend fun publishSends(sends: List) = publishGuard(LinkGuards.SENDS, encode(SendsDoc(sends).newest())) + + private suspend fun publishGuard(kind: String, body: ByteArray): Unit = locked { + val record = store.load()?.takeIf { it.removal == null } ?: return@locked + publish(record, LinkPaths.guard(role, kind), body) + } + protected suspend fun locked(block: suspend () -> T): T = mutex.withLock { block() } /** @@ -59,7 +96,10 @@ abstract class LinkEndpoint internal constructor( return sealed.counter } - /** Replaces the record with the one of a pairing that just finished, dropping the keys of the one before. */ + /** + * Replaces the record with the one of a pairing that just finished, dropping the keys of the one before and + * whatever an earlier pairing's peer said for the guards. + */ protected suspend fun replace(link: PairedLink, nowMs: Long): LinkRecord { val old = store.load() val record = LinkRecord( @@ -74,13 +114,20 @@ abstract class LinkEndpoint internal constructor( lastSeenMs = nowMs, ) store.update { record } - if (old != null && old.pairingId != link.pairingId) deleteKeys(old.pairingId) + if (old?.pairingId != link.pairingId) { + old?.let { deleteKeys(it.pairingId) } + runSuspendCatching { peer.clearPeerState() } + } return record } - /** Deletes the record, then the documents [staleStates] this device published, then the keys. */ - protected suspend fun drop(record: LinkRecord, vararg staleStates: String) { + /** + * Deletes the record, drops what the peer said for the guards, then deletes the documents [staleStates] this + * device published and the keys. Each step runs whether or not the one before it failed. + */ + protected suspend fun drop(record: LinkRecord, staleStates: List = emptyList()) { store.update { if (it?.pairingId == record.pairingId) null else it } + runSuspendCatching { peer.clearPeerState() } staleStates.forEach { name -> runSuspendCatching { transport.deleteState(LinkPaths.state(record.pairingId, name)) } } @@ -94,24 +141,37 @@ abstract class LinkEndpoint internal constructor( private fun channel(pairingId: String) = LinkChannel(role, pairingId, keys, RecordCounters(store, pairingId)) private companion object { + /** How many handshake messages wait for a pairing session that is slow to collect them. */ const val PAIRING_BUFFER = 32 + + /** Milliseconds in a second, for the epoch seconds the guard documents carry. */ + const val MILLIS_PER_SEC = 1_000L } } /** - * The phone's end: it publishes the control and settings documents and reads the watch's status. + * The phone's end: it publishes the control, settings and guard documents and reads the watch's status and guard + * documents. * * [onSettingsMissed] is called, without waiting for it, when the watch reports that it has applied no settings * though some were published: the phone finished pairing and published before the watch had noted the pairing, so - * the watch dropped them. The phone app then publishes its settings again. It happens at most once per pairing. + * the watch dropped them. The phone app then publishes its settings again. + * + * [onWatchPaired] is called, without waiting for it, at the first status of a pairing that says it stands: the watch + * has noted the pairing, so guard documents the phone published before that, which the watch dropped, are published + * again by the phone app. The carrier does not replay them by itself. + * + * [peer] takes the watch's guard documents (see [LinkGuards]). */ class PhoneLink( transport: LinkTransport, keys: LinkKeyStore, store: LinkRecordStore, + peer: PeerStateListener, private val onSettingsMissed: () -> Unit = {}, - private val nowMs: () -> Long, -) : LinkEndpoint(LinkRole.Phone, transport, keys, store) { + private val onWatchPaired: () -> Unit = {}, + nowMs: () -> Long, +) : LinkEndpoint(LinkRole.Phone, transport, keys, store, peer, nowMs) { /** Notes the finished pairing with [link], replacing any earlier watch, and tells the watch it stands. */ suspend fun onPaired(link: PairedLink): LinkRecord = locked { val record = replace(link, nowMs()) @@ -156,14 +216,14 @@ class PhoneLink( if (record.removal == null) { runSuspendCatching { publish(record, LinkPaths.CONTROL, encode(ControlDoc(ControlDoc.State.Revoked))) } } - drop(record, LinkPaths.SETTINGS) + drop(record, listOf(LinkPaths.SETTINGS) + guardStates(LinkRole.Phone)) } override suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long) { if (name != LinkPaths.STATUS) throw LinkError.Rejected("unknown document") val status = decode(body) if (status.state != StatusDoc.State.Paired) { - drop(record, LinkPaths.SETTINGS, LinkPaths.CONTROL) + drop(record, listOf(LinkPaths.SETTINGS, LinkPaths.CONTROL) + guardStates(LinkRole.Phone)) return } store.update { @@ -174,12 +234,13 @@ class PhoneLink( lastSeenMs = nowMs(), ) } + if (LinkPaths.state(record.pairingId, LinkPaths.STATUS) !in record.received) onWatchPaired() if (status.settingsCounter == 0L && record.settingsSent > 0) onSettingsMissed() } } /** What the watch app does with what the phone sends. */ -interface WatchLinkListener { +interface WatchLinkListener : PeerStateListener { /** Adopts the phone's settings, by the same rules as the import of the phone's backup. */ suspend fun applySettings(settings: SettingsDoc) @@ -194,20 +255,27 @@ interface WatchLinkListener { /** The pairing ended; whatever the watch kept of the phone's pushes is dropped. */ suspend fun onUnpaired() + + /** + * The phone said the pairing stands, so it has noted it: guard documents the watch published before that were + * dropped by the phone, and the watch app publishes them again. Called while the link handles a packet, so the + * app publishes from elsewhere, not from inside the call. + */ + fun onPhonePaired() } /** What the watch reports about itself in its status. */ class WatchInfo(val appVersion: String, val isLockSet: Boolean) -/** The watch's end: it reads the control and settings documents and publishes its status. */ +/** The watch's end: it reads the control, settings and guard documents and publishes its status and its guards. */ class WatchLink( transport: LinkTransport, keys: LinkKeyStore, store: LinkRecordStore, private val listener: WatchLinkListener, private val info: suspend () -> WatchInfo, - private val nowMs: () -> Long, -) : LinkEndpoint(LinkRole.Watch, transport, keys, store) { + nowMs: () -> Long, +) : LinkEndpoint(LinkRole.Watch, transport, keys, store, listener, nowMs) { /** Notes the finished pairing with [link]; the watch keeps one phone, so it replaces any earlier one. */ suspend fun onPaired(link: PairedLink): LinkRecord = locked { val record = replace(link, nowMs()) @@ -233,8 +301,9 @@ class WatchLink( if (updated != null) publishStatus(updated, StatusDoc.State.Paired) } LinkPaths.CONTROL -> when (decode(body).state) { - ControlDoc.State.Paired -> store.update { - if (it?.pairingId == record.pairingId) it.copy(lastSeenMs = nowMs()) else it + ControlDoc.State.Paired -> { + store.update { if (it?.pairingId == record.pairingId) it.copy(lastSeenMs = nowMs()) else it } + listener.onPhonePaired() } ControlDoc.State.Revoked -> end(record, StatusDoc.State.Unpaired) ControlDoc.State.Erase -> { @@ -245,7 +314,7 @@ class WatchLink( listener.prepareErase() runSuspendCatching { publishStatus(record, StatusDoc.State.Erased) } listener.erase() - drop(record) + drop(record, guardStates(LinkRole.Watch)) } } else -> throw LinkError.Rejected("unknown document") @@ -254,7 +323,7 @@ class WatchLink( private suspend fun end(record: LinkRecord, state: StatusDoc.State) { runSuspendCatching { publishStatus(record, state) } - drop(record) + drop(record, guardStates(LinkRole.Watch)) listener.onUnpaired() } @@ -265,6 +334,8 @@ class WatchLink( } } +private fun guardStates(writer: LinkRole): List = LinkGuards.KINDS.map { LinkPaths.guard(writer, it) } + private inline fun encode(value: T): ByteArray = linkJson.encodeToString(value).encodeToByteArray() private inline fun decode(body: ByteArray): T = diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkGuards.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkGuards.kt new file mode 100644 index 0000000000..2b38dd1c02 --- /dev/null +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkGuards.kt @@ -0,0 +1,219 @@ +package to.bitkit.wearlink + +import kotlinx.serialization.Serializable + +/** + * The guard documents of a pairing: what each device tells the other so the two do not pay the wallet itself, stay + * within one QuickPay daily limit, and do not pay one invoice twice. Each device writes its own three, as full + * snapshots, and reads the other's. `docs/wear.md`, Pairing › Shared guards, describes the rules. + */ +object LinkGuards { + /** The document of the writer's own unexpired invoices ([InvoicesDoc]). */ + const val INVOICES = "invoices" + + /** The document of the writer's QuickPay count of its day ([QuickPayDoc]). */ + const val QUICKPAY = "quickpay" + + /** The document of the writer's open sends ([SendsDoc]). */ + const val SENDS = "sends" + + /** The kinds of guard document each device writes once. */ + val KINDS = listOf(INVOICES, QUICKPAY, SENDS) + + /** + * The furthest ahead of the reader's clock a peer's invoice expiry is taken, in seconds: 7 days, well above the + * day a phone invoice and the hour a watch invoice live. A later one, as from a peer whose clock runs ahead, is + * cut to it when its document arrives, so nothing a peer says is kept for good. + */ + const val MAX_EXPIRY_AHEAD_SECS = 604_800L + + /** + * How long after its start a peer's open send holds the reader back, in seconds: 5 minutes. Spark lists a send + * it took within moments, and the SDK settles a Lightning payment within about 3 minutes (the watch's + * `SETTLE_HOLD`); the rest is for the document to cross and the two clocks to differ. An older one that Spark + * does not list never reached it, as a send cut off inside the call, and no longer counts: the reader may send, + * under the idempotency key both devices derive for the invoice, which Spark pays once. + */ + const val OPEN_SEND_HOLD_SECS = 300L + + /** Above any day's QuickPay spend, so adding a peer's count to a device's own can never overflow. */ + const val MAX_CENTS = 1_000_000_000_000_000L + + /** + * The day of the count a device publishes before it has spent anything under QuickPay: no reader's day, so it + * counts for nothing and replaces whatever an earlier pairing's peer said. + */ + const val NO_DAY = "" + + /** The cents the peer spent under QuickPay on [dayKey], the reader's own day, or 0 for any other day. */ + fun peerCents(peer: QuickPayDoc?, dayKey: String): Long = + peer?.takeIf { it.dayKey == dayKey }?.spentCents?.coerceIn(0, MAX_CENTS) ?: 0 + + /** + * The peer's open send of the invoice with [paymentHash] that still counts, or null. One counts until the peer + * drops it, unless Spark's own list shows its attempt failed ([failedIds], the ids of failed payments, which are + * the keys they went out under) or it [isStale]. The start bounds every open send, so its invoice's expiry + * decides nothing here. + */ + fun pendingSend(peer: List, paymentHash: String, failedIds: Set, nowSecs: Long): OpenSend? = + peer.firstOrNull { send -> + send.paymentHash.equals(paymentHash, ignoreCase = true) && + send.key !in failedIds && + !isStale(send, nowSecs) + } + + /** The peer's open transfers to the Spark wallet with the identity key [sparkPayee], in either case. */ + fun transfers(peer: List, sparkPayee: String): List = + peer.filter { it.sparkPayee.equals(sparkPayee, ignoreCase = true) } + + /** + * Whether [send] holds only if Spark lists it: it started [OPEN_SEND_HOLD_SECS] or longer before [nowSecs], or + * after it. Starts are cut to the reader's clock on arrival, so a later one means that clock went back since, + * and the send then falls to the shared key, as an unreadable list does. + */ + fun isStale(send: OpenSend, nowSecs: Long): Boolean = + send.startedAtSecs <= nowSecs - OPEN_SEND_HOLD_SECS || send.startedAtSecs > nowSecs + + /** + * The peer's [arrived] sends as the reader stores them over the [stored] ones: a send whose key is already known + * keeps the earlier of its two starts, so a peer whose clock runs ahead, and whose every start is cut to the + * reader's now on arrival, does not renew its sends each time its document arrives again. + */ + fun keptStarts(arrived: List, stored: List): List { + val starts = stored.associate { it.key to it.startedAtSecs } + return arrived.map { send -> + starts[send.key]?.let { send.copy(startedAtSecs = minOf(it, send.startedAtSecs)) } ?: send + } + } + + /** [invoices] as the reader keeps them at [nowSecs]: no expiry further ahead than [MAX_EXPIRY_AHEAD_SECS]. */ + internal fun bounded(invoices: List, nowSecs: Long): List = + invoices.map { it.copy(expiresAtSecs = it.expiresAtSecs.coerceAtMost(nowSecs + MAX_EXPIRY_AHEAD_SECS)) } + + /** + * [sends] as the reader keeps them at [nowSecs]: no start later than now, so a send of a peer whose clock runs + * ahead still goes stale. + */ + internal fun boundedSends(sends: List, nowSecs: Long): List = + sends.map { it.copy(startedAtSecs = it.startedAtSecs.coerceIn(0, nowSecs)) } +} + +/** An unexpired invoice the writer created: its payment hash in lowercase hex and its expiry in epoch seconds. */ +data class PeerInvoice(val paymentHash: String, val expiresAtSecs: Long) + +/** + * The writer's own unexpired invoices, which the reader refuses to pay. In binary: the [FORMAT] byte, the count, then + * 40 bytes an invoice, so the [MAX_INVOICES] that expire last stay well under the carrier's 100 KB. A reader refuses + * another format, and ignores whatever follows the invoices the count declares, which is where a later build adds to + * this format. + */ +class InvoicesDoc(val invoices: List) { + companion object { + /** The most invoices a document carries. */ + const val MAX_INVOICES = 1_000 + + /** The layout this build writes and reads. */ + const val FORMAT = 1 + + fun decode(body: ByteArray): InvoicesDoc { + val reader = WireReader(body) + if (reader.byte() != FORMAT) throw LinkError.Malformed() + val count = reader.int() + if (count !in 0..MAX_INVOICES) throw LinkError.Malformed() + return InvoicesDoc(List(count) { PeerInvoice(reader.fixed(LinkCrypto.HASH_BYTES).toHex(), reader.long()) }) + } + } + + /** The invoices that expire last, at most [MAX_INVOICES]; one whose hash is not 32 bytes of hex is left out. */ + fun encode(): ByteArray { + val kept = invoices + .mapNotNull { invoice -> hashBytes(invoice.paymentHash)?.let { it to invoice.expiresAtSecs } } + .sortedByDescending { it.second } + .take(MAX_INVOICES) + val writer = WireWriter().byte(FORMAT).int(kept.size) + kept.forEach { (hash, expiresAt) -> writer.fixed(hash).long(expiresAt) } + return writer.toByteArray() + } + + private fun hashBytes(hex: String): ByteArray? = + runCatching { hex.lowercase().hexToBytes() }.getOrNull()?.takeIf { it.size == LinkCrypto.HASH_BYTES } +} + +/** + * What the writer spent under QuickPay on [dayKey], an ISO date by its own clock, in US cents. A writer that has + * spent nothing yet publishes [LinkGuards.NO_DAY]. + */ +@Serializable +data class QuickPayDoc(val dayKey: String, val spentCents: Long) { + internal fun validated(): QuickPayDoc { + if (dayKey.length > MAX_DAY_KEY || spentCents < 0) throw LinkError.Malformed() + return this + } +} + +/** An ISO date's length. */ +private const val MAX_DAY_KEY = 10 + +/** + * A send the writer handed to Spark, or is about to, whose outcome it has not learned. [key] is the idempotency key + * it goes out under, which Spark keeps as the payment's id. An invoice's send has its [paymentHash] and + * [expiresAtSecs]; a transfer to a Spark address has the [sparkPayee] identity key it pays, in hex. [startedAtSecs] + * alone bounds how long the reader holds back for it ([LinkGuards.isStale]); no reader uses [expiresAtSecs]. + * + * A transfer's key is random per device, so unlike an invoice's it is not shared: before the phone publishes + * transfers, the watch has to reuse a stale phone transfer's listed key, or hold transfers without the time limit. + * The phone publishes none today. + */ +@Serializable +data class OpenSend( + val key: String, + val paymentHash: String? = null, + val sparkPayee: String? = null, + val expiresAtSecs: Long? = null, + val startedAtSecs: Long = 0, +) + +/** The writer's open sends, at most [MAX_SENDS]: the newest. */ +@Serializable +data class SendsDoc(val sends: List) { + companion object { + /** The most open sends a document carries. */ + const val MAX_SENDS = 200 + } + + internal fun validated(): SendsDoc { + val isMalformed = sends.size > MAX_SENDS || sends.any { send -> + listOfNotNull(send.key, send.paymentHash, send.sparkPayee).any { it.length > MAX_SEND_FIELD } + } + if (isMalformed) throw LinkError.Malformed() + return this + } + + internal fun newest(): SendsDoc = SendsDoc(sends.sortedByDescending { it.startedAtSecs }.take(MAX_SENDS)) +} + +/** + * What a device does with the peer's guard documents. Each replaces what the last one of its kind said, and arrives + * with its invoice expiries and send starts bounded by this device's clock ([LinkGuards.MAX_EXPIRY_AHEAD_SECS]). The + * implementations store them where the device's own guards read them, apart from the device's own state, keep a + * known send's earlier start ([LinkGuards.keptStarts]), and read them only while a pairing exists. + */ +interface PeerStateListener { + /** The peer's unexpired invoices, which this device refuses to pay. */ + suspend fun applyInvoices(invoices: List) + + suspend fun applyQuickPay(quickPay: QuickPayDoc) + + suspend fun applySends(sends: List) + + /** + * The pairing ended or a new one was made: the peer's invoices, count and open sends are dropped. A failure does + * not stop the pairing's end, so the implementation logs it before it rethrows. After an unpair, what stays + * behind is not read. After a re-pair, it holds until the new peer's documents replace it, which they do as the + * pairing is noted, a count included. + */ + suspend fun clearPeerState() +} + +/** Longer than any key, hash or identity key an open send names. */ +private const val MAX_SEND_FIELD = 200 diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt index a4050da49d..e3f796314c 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt @@ -76,6 +76,9 @@ object LinkPaths { const val SETTINGS = "p2w/settings" const val STATUS = "w2p/status" + /** The name of the guard document of [kind] (see [LinkGuards]) that [writer] writes. */ + fun guard(writer: LinkRole, kind: String): String = (if (writer == LinkRole.Phone) "p2w" else "w2p") + "/$kind" + fun isPairing(path: String): Boolean = path.startsWith("$PAIR/") /** The path of the state document [name] of the pairing [pairingId]. */ diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkGuardsTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkGuardsTest.kt new file mode 100644 index 0000000000..13a7304685 --- /dev/null +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkGuardsTest.kt @@ -0,0 +1,450 @@ +package to.bitkit.wearlink + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class LinkGuardsTest { + private companion object { + val HASH_A = "aa".repeat(32) + val HASH_B = "bb".repeat(32) + const val NOW = 1_000_000L + } + + private suspend fun TestScope.paired(harness: LinkHarness = LinkHarness(backgroundScope)): LinkHarness { + val watchSession = harness.watchPairing() + val phoneSession = harness.phonePairing() + val watch = async { watchSession.run() } + val phone = async { phoneSession.run() } + phoneSession.state.first { it is PairingState.Code } + watchSession.state.first { it is PairingState.Code } + watchSession.confirmShown() + phoneSession.confirmShown(isAuthenticated = true) + harness.phoneLink.onPaired(phone.await()) + harness.watchLink.onPaired(watch.await()) + runCurrent() + return harness + } + + // region documents over the link + + @Test + fun `each side's invoices reach the other`() = runTest { + val harness = paired() + + harness.phoneLink.publishInvoices(listOf(PeerInvoice(HASH_A, NOW))) + harness.watchLink.publishInvoices(listOf(PeerInvoice(HASH_B.uppercase(), NOW + 1))) + runCurrent() + + assertEquals(listOf(PeerInvoice(HASH_A, NOW)), harness.watchPeer.invoices) + assertEquals(listOf(PeerInvoice(HASH_B, NOW + 1)), harness.phonePeer.invoices) + } + + @Test + fun `quickpay counts and open sends reach the other side`() = runTest { + val harness = paired() + val send = OpenSend("key-0", paymentHash = HASH_A, expiresAtSecs = NOW, startedAtSecs = NOW - 5) + + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 250)) + harness.watchLink.publishSends(listOf(send)) + harness.phoneLink.publishQuickPay(QuickPayDoc("2026-11-28", 100)) + runCurrent() + + assertEquals(QuickPayDoc("2026-11-28", 250), harness.phonePeer.quickPay) + assertEquals(listOf(send), harness.phonePeer.sends) + assertEquals(QuickPayDoc("2026-11-28", 100), harness.watchPeer.quickPay) + } + + @Test + fun `a lower count replaces a higher one, as a release on the writer publishes`() = runTest { + val harness = paired() + + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 250)) + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 50)) + runCurrent() + + assertEquals(50, harness.phonePeer.quickPay?.spentCents) + } + + @Test + fun `a replayed older count never replaces a newer one`() = runTest { + val harness = paired() + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 500)) + runCurrent() + val older = harness.network.sent.last { it.path.endsWith(LinkPaths.guard(LinkRole.Watch, LinkGuards.QUICKPAY)) } + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 0)) + runCurrent() + + harness.network.replay(older) + runCurrent() + + assertEquals(0, harness.phonePeer.quickPay?.spentCents) + } + + @Test + fun `guard documents are encrypted on the carrier`() = runTest { + val harness = paired() + + harness.watchLink.publishSends(listOf(OpenSend("key-secret-0", paymentHash = HASH_A))) + harness.phoneLink.publishInvoices(listOf(PeerInvoice(HASH_A, NOW))) + runCurrent() + + val key = "key-secret-0".encodeToByteArray().toHex() + assertTrue(harness.network.sent.none { HASH_A in it.payload.toHex() || key in it.payload.toHex() }) + } + + @Test + fun `a document the phone wrote is never taken by the phone as the watch's`() = runTest { + val harness = paired() + harness.phoneLink.publishQuickPay(QuickPayDoc("2026-11-28", 999)) + runCurrent() + val own = harness.network.sent.last { it.path.endsWith(LinkPaths.guard(LinkRole.Phone, LinkGuards.QUICKPAY)) } + val reflected = own.path.replace("p2w/", "w2p/") + + runCatching { harness.phoneLink.onPacket(LinkPacket(harness.network.watch.nodeId, reflected, own.payload)) } + + assertNull(harness.phonePeer.quickPay) + } + + @Test + fun `a watch that noted the pairing first hears when the phone has, to publish its guards again`() = runTest { + val harness = LinkHarness(backgroundScope) + val watchSession = harness.watchPairing() + val phoneSession = harness.phonePairing() + val watch = async { watchSession.run() } + val phone = async { phoneSession.run() } + phoneSession.state.first { it is PairingState.Code } + watchSession.state.first { it is PairingState.Code } + watchSession.confirmShown() + phoneSession.confirmShown(isAuthenticated = true) + harness.watchLink.onPaired(watch.await()) + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 70)) + runCurrent() + assertNull(harness.phonePeer.quickPay) + + harness.phoneLink.onPaired(phone.await()) + runCurrent() + + assertEquals(1, harness.phonePaired) + } + + @Test + fun `the watch's first status of a pairing tells the phone app once, to publish its guards again`() = runTest { + val harness = paired() + assertEquals(1, harness.watchPaired) + assertEquals(0, harness.missedSettings) + + harness.phoneLink.publishSettings(SettingsDoc(changedAtMs = harness.now)) + runCurrent() + + assertEquals(1, harness.appliedSettings.size) + assertEquals(1, harness.watchPaired) + + paired(harness) + + assertEquals(2, harness.watchPaired) + } + + @Test + fun `an invoice expiry far ahead and a send start in the future are cut to the reader's clock on arrival`() = + runTest { + val harness = paired() + val nowSecs = harness.now / 1_000 + val horizon = nowSecs + LinkGuards.MAX_EXPIRY_AHEAD_SECS + val send = OpenSend("key-0", HASH_A, expiresAtSecs = Long.MAX_VALUE, startedAtSecs = nowSecs + 9_000) + + val watchInvoices = listOf(PeerInvoice(HASH_A, Long.MAX_VALUE), PeerInvoice(HASH_B, nowSecs + 60)) + + harness.watchLink.publishInvoices(watchInvoices) + harness.watchLink.publishSends(listOf(send, OpenSend("key-1", HASH_B, startedAtSecs = -5))) + harness.phoneLink.publishInvoices(listOf(PeerInvoice(HASH_A, horizon + 1))) + runCurrent() + + assertEquals( + listOf(PeerInvoice(HASH_A, horizon), PeerInvoice(HASH_B, nowSecs + 60)), + harness.phonePeer.invoices, + ) + assertEquals( + listOf( + OpenSend("key-0", HASH_A, expiresAtSecs = Long.MAX_VALUE, startedAtSecs = nowSecs), + OpenSend("key-1", HASH_B, startedAtSecs = 0), + ), + harness.phonePeer.sends, + ) + assertEquals(listOf(PeerInvoice(HASH_A, horizon)), harness.watchPeer.invoices) + } + + @Test + fun `nothing is published without a pairing`() = runTest { + val harness = LinkHarness(backgroundScope) + + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 1)) + harness.phoneLink.publishSends(emptyList()) + + assertTrue(harness.network.sent.isEmpty()) + } + + @Test + fun `unpair clears the peer's invoices, count and sends on both sides`() = runTest { + val harness = paired() + harness.watchLink.publishInvoices(listOf(PeerInvoice(HASH_A, harness.now / 1_000 + 60))) + harness.phoneLink.publishInvoices(listOf(PeerInvoice(HASH_B, harness.now / 1_000 + 60))) + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 250)) + harness.phoneLink.publishQuickPay(QuickPayDoc("2026-11-28", 100)) + runCurrent() + + harness.watchLink.unpair() + runCurrent() + + assertNull(harness.phonePeer.invoices) + assertNull(harness.watchPeer.invoices) + assertNull(harness.phonePeer.quickPay) + assertNull(harness.watchPeer.quickPay) + assertTrue(harness.phonePeer.clears >= 1) + assertTrue(harness.watchPeer.clears >= 1) + } + + @Test + fun `a peer state that cannot be cleared does not stop the unpair on either side`() = runTest { + val harness = paired() + harness.phonePeer.clearFailure = IllegalStateException("disk") + harness.watchPeer.clearFailure = IllegalStateException("disk") + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 250)) + runCurrent() + + harness.watchLink.unpair() + runCurrent() + + assertNull(harness.watchStore.load()) + assertNull(harness.phoneStore.load()) + assertEquals(1, harness.unpairs) + assertTrue(harness.watchKeys.keys.isEmpty()) + assertTrue(harness.phoneKeys.keys.isEmpty()) + // The carrier delivers what it still stores at a reconnect: the watch's guard document is no longer there. + val guard = LinkPaths.guard(LinkRole.Watch, LinkGuards.QUICKPAY) + val sentBefore = harness.network.sent.count { it.path.endsWith(guard) } + harness.network.reconnect() + runCurrent() + assertEquals(sentBefore, harness.network.sent.count { it.path.endsWith(guard) }) + } + + @Test + fun `a peer state that cannot be cleared does not stop a new pairing, which clears it`() = runTest { + val harness = LinkHarness(backgroundScope) + harness.phonePeer.quickPay = QuickPayDoc("2026-11-28", 250) + harness.watchPeer.clearFailure = IllegalStateException("disk") + + paired(harness) + + assertNull(harness.phonePeer.quickPay) + assertNotNull(harness.watchStore.load()) + } + + @Test + fun `pairing again clears what the earlier pairing's peer said`() = runTest { + val harness = paired() + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", 250)) + runCurrent() + assertNotNull(harness.phonePeer.quickPay) + + paired(harness) + + assertNull(harness.phonePeer.quickPay) + } + + @Test + fun `a device without a count publishes one of no day, which replaces a stale count and counts for nothing`() = + runTest { + val harness = paired() + harness.phonePeer.quickPay = QuickPayDoc("2026-11-28", 250) + + harness.watchLink.publishQuickPay(null) + runCurrent() + + assertEquals(QuickPayDoc(LinkGuards.NO_DAY, 0), harness.phonePeer.quickPay) + assertEquals(0, LinkGuards.peerCents(harness.phonePeer.quickPay, "2026-11-28")) + } + + @Test + fun `a malformed count is refused`() = runTest { + val harness = paired() + + harness.watchLink.publishQuickPay(QuickPayDoc("2026-11-28", -5)) + runCurrent() + + assertNull(harness.phonePeer.quickPay) + assertTrue(harness.phoneErrors.any { it is LinkError.Malformed }) + } + + // endregion + + // region invoices document + + @Test + fun `invoices encode the thousand that expire last in 40 bytes each, and decode back`() { + val invoices = List(InvoicesDoc.MAX_INVOICES + 5) { PeerInvoice("%064x".format(it), it.toLong()) } + + val body = InvoicesDoc(invoices).encode() + val decoded = InvoicesDoc.decode(body).invoices + + assertEquals(1 + 4 + InvoicesDoc.MAX_INVOICES * 40, body.size) + assertEquals(InvoicesDoc.FORMAT, body.first().toInt()) + assertEquals(InvoicesDoc.MAX_INVOICES, decoded.size) + assertEquals(invoices.drop(5).reversed(), decoded) + } + + @Test + fun `an invoice whose hash is not 32 bytes of hex is left out`() { + val doc = InvoicesDoc(listOf(PeerInvoice("abc", 1), PeerInvoice("zz".repeat(32), 1), PeerInvoice(HASH_A, 2))) + + assertEquals(listOf(PeerInvoice(HASH_A, 2)), InvoicesDoc.decode(doc.encode()).invoices) + } + + @Test + fun `an invoices document of another format, with a wrong count or cut short is malformed`() { + val body = InvoicesDoc(listOf(PeerInvoice(HASH_A, 1))).encode() + + assertFailsWith { InvoicesDoc.decode(byteArrayOf(2) + body.drop(1)) } + assertFailsWith { InvoicesDoc.decode(body.copyOf(body.size - 1)) } + assertFailsWith { InvoicesDoc.decode(byteArrayOf(1, 0x7f, 0, 0, 0)) } + assertFailsWith { InvoicesDoc.decode(byteArrayOf()) } + } + + @Test + fun `what a later build adds after the invoices is ignored`() { + val body = InvoicesDoc(listOf(PeerInvoice(HASH_A, 1))).encode() + + assertEquals(listOf(PeerInvoice(HASH_A, 1)), InvoicesDoc.decode(body + byteArrayOf(7, 7, 7)).invoices) + } + + // endregion + + // region sends document + + @Test + fun `a sends document with too many sends or an oversized field is malformed`() { + val sends = List(SendsDoc.MAX_SENDS) { OpenSend("key-$it", HASH_A) } + val long = "a".repeat(201) + + assertEquals(sends, SendsDoc(sends).validated().sends) + assertFailsWith { SendsDoc(sends + OpenSend("one-more")).validated() } + assertFailsWith { SendsDoc(listOf(OpenSend(long))).validated() } + assertFailsWith { SendsDoc(listOf(OpenSend("k", paymentHash = long))).validated() } + assertFailsWith { SendsDoc(listOf(OpenSend("k", sparkPayee = long))).validated() } + } + + @Test + fun `the newest sends are the ones a document carries`() { + val sends = List(SendsDoc.MAX_SENDS + 3) { OpenSend("key-$it", startedAtSecs = it.toLong()) } + + val kept = SendsDoc(sends).newest().sends + + assertEquals(SendsDoc.MAX_SENDS, kept.size) + assertEquals(sends.drop(3).reversed(), kept) + } + + // endregion + + // region rules + + @Test + fun `the peer's cents count only on the reader's own day`() { + val peer = QuickPayDoc("2026-11-28", 300) + + assertEquals(300, LinkGuards.peerCents(peer, "2026-11-28")) + assertEquals(0, LinkGuards.peerCents(peer, "2026-11-29")) + assertEquals(0, LinkGuards.peerCents(null, "2026-11-28")) + assertEquals(LinkGuards.MAX_CENTS, LinkGuards.peerCents(peer.copy(spentCents = Long.MAX_VALUE), peer.dayKey)) + } + + @Test + fun `a peer's open send of the invoice is pending, in either case of its hash`() { + val send = OpenSend("key-0", paymentHash = HASH_A.uppercase(), expiresAtSecs = NOW, startedAtSecs = NOW) + + assertEquals(send, LinkGuards.pendingSend(listOf(send), HASH_A, emptySet(), NOW)) + assertNull(LinkGuards.pendingSend(listOf(send), HASH_B, emptySet(), NOW)) + } + + @Test + fun `a peer's send whose attempt Spark lists failed is not pending`() { + val send = OpenSend("key-0", paymentHash = HASH_A, expiresAtSecs = NOW, startedAtSecs = NOW) + + assertNull(LinkGuards.pendingSend(listOf(send), HASH_A, setOf("key-0"), NOW)) + assertEquals(send, LinkGuards.pendingSend(listOf(send), HASH_A, setOf("key-1"), NOW)) + } + + @Test + fun `a peer's send that Spark never listed stops holding five minutes after its start`() { + val send = OpenSend("key-0", paymentHash = HASH_A, expiresAtSecs = NOW + 3_600, startedAtSecs = NOW) + val held = NOW + LinkGuards.OPEN_SEND_HOLD_SECS + + assertEquals(300, LinkGuards.OPEN_SEND_HOLD_SECS) + assertEquals(send, LinkGuards.pendingSend(listOf(send), HASH_A, emptySet(), held - 1)) + assertNull(LinkGuards.pendingSend(listOf(send), HASH_A, emptySet(), held)) + assertNull(LinkGuards.pendingSend(listOf(send.copy(startedAtSecs = 0)), HASH_A, emptySet(), NOW)) + } + + @Test + fun `a fresh peer's send is pending whatever its invoice's expiry`() { + val open = OpenSend("key-0", paymentHash = HASH_A, expiresAtSecs = null, startedAtSecs = NOW) + + listOf(open, open.copy(expiresAtSecs = Long.MAX_VALUE), open.copy(expiresAtSecs = 0)).forEach { send -> + assertEquals(send, LinkGuards.pendingSend(listOf(send), HASH_A, emptySet(), NOW)) + } + } + + @Test + fun `a peer's send that started after the reader's now, as when its clock went back, is stale`() { + val send = OpenSend("key-0", paymentHash = HASH_A, startedAtSecs = NOW) + + assertFalse(LinkGuards.isStale(send, NOW)) + assertTrue(LinkGuards.isStale(send, NOW - 1)) + assertNull(LinkGuards.pendingSend(listOf(send), HASH_A, emptySet(), NOW - 86_400)) + } + + @Test + fun `a send the peer lists again keeps its earlier start, and a new one takes its own`() { + val stored = listOf(OpenSend("key-0", HASH_A, startedAtSecs = NOW), OpenSend("key-9", HASH_B)) + val arrived = listOf( + OpenSend("key-0", HASH_A, startedAtSecs = NOW + 60), + OpenSend("key-1", HASH_B, startedAtSecs = NOW + 60), + ) + + assertEquals( + listOf(OpenSend("key-0", HASH_A, startedAtSecs = NOW), OpenSend("key-1", HASH_B, startedAtSecs = NOW + 60)), + LinkGuards.keptStarts(arrived, stored), + ) + assertEquals( + listOf(OpenSend("key-0", HASH_A, startedAtSecs = NOW - 5)), + LinkGuards.keptStarts(listOf(OpenSend("key-0", HASH_A, startedAtSecs = NOW - 5)), stored), + ) + } + + @Test + fun `a peer's transfers are found by payee in either case, and go stale like its sends`() { + val sends = listOf( + OpenSend("t-1", sparkPayee = "02ab", startedAtSecs = NOW), + OpenSend("t-2", sparkPayee = "02cd", startedAtSecs = NOW), + OpenSend("i-1", paymentHash = HASH_A, startedAtSecs = NOW), + ) + + val found = LinkGuards.transfers(sends, "02AB") + + assertEquals(listOf("t-1"), found.map { it.key }) + assertFalse(LinkGuards.isStale(found.single(), NOW + LinkGuards.OPEN_SEND_HOLD_SECS - 1)) + assertTrue(LinkGuards.isStale(found.single(), NOW + LinkGuards.OPEN_SEND_HOLD_SECS)) + } + + // endregion +} diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt index 4c0eda5f0b..fcc2b93e13 100644 --- a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt @@ -74,7 +74,26 @@ class LinkHarness(scope: CoroutineScope) { var sentAtErase = emptyList() var missedSettings = 0 - val phoneLink = PhoneLink(network.phone, phoneKeys, phoneStore, onSettingsMissed = { missedSettings++ }) { now } + + /** How often the watch heard that the phone noted the pairing. */ + var phonePaired = 0 + + /** How often the phone heard, from a pairing's first status, that the watch noted it. */ + var watchPaired = 0 + + /** What each side holds of the other's guard documents. */ + val phonePeer = RecordingPeer() + val watchPeer = RecordingPeer() + + val phoneLink = PhoneLink( + transport = network.phone, + keys = phoneKeys, + store = phoneStore, + peer = phonePeer, + onSettingsMissed = { missedSettings++ }, + onWatchPaired = { watchPaired++ }, + nowMs = { now }, + ) val watchLink = WatchLink( transport = network.watch, keys = watchKeys, @@ -100,6 +119,18 @@ class LinkHarness(scope: CoroutineScope) { override suspend fun onUnpaired() { unpairs++ } + + override suspend fun applyInvoices(invoices: List) = watchPeer.applyInvoices(invoices) + + override suspend fun applyQuickPay(quickPay: QuickPayDoc) = watchPeer.applyQuickPay(quickPay) + + override suspend fun applySends(sends: List) = watchPeer.applySends(sends) + + override suspend fun clearPeerState() = watchPeer.clearPeerState() + + override fun onPhonePaired() { + phonePaired++ + } }, info = { WatchInfo("1.0 (1)", isLockSet = true) }, nowMs = { now }, @@ -164,3 +195,28 @@ fun PairingSession.confirmShown(isAuthenticated: Boolean = false) = confirm((state.value as PairingState.Code).code, isAuthenticated) fun statusList(json: String): AttestationStatusList = AttestationStatusList.parse(json.encodeToByteArray()) + +/** A [PeerStateListener] that keeps the last of each guard document, as an app's store does. */ +class RecordingPeer : PeerStateListener { + var invoices: List? = null + var quickPay: QuickPayDoc? = null + var sends: List? = null + var clears = 0 + + /** Makes [clearPeerState] fail, as a store that cannot be written does. */ + var clearFailure: Throwable? = null + + override suspend fun applyInvoices(invoices: List) = run { this.invoices = invoices } + + override suspend fun applyQuickPay(quickPay: QuickPayDoc) = run { this.quickPay = quickPay } + + override suspend fun applySends(sends: List) = run { this.sends = sends } + + override suspend fun clearPeerState() { + clearFailure?.let { throw it } + invoices = null + quickPay = null + sends = null + clears++ + } +}