Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 59 additions & 4 deletions app/src/main/java/to/bitkit/data/WatchLinkStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -25,14 +29,32 @@ private val Context.watchLinkDataStore: DataStore<WatchLinkData> 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<OpenSend>
}

/**
* 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<WatchLinkData>,
) : LinkRecordStore {
) : LinkRecordStore, WatchGuardState {
@Inject
constructor(@ApplicationContext context: Context) : this(context.watchLinkDataStore)

Expand All @@ -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<OpenSend> = paired()?.watchSends.orEmpty()

/** Replaces the watch's invoices with [invoices], leaving out the ones expired at [now]. */
suspend fun setWatchInvoices(invoices: List<PeerInvoice>, 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<OpenSend>) {
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 {
Expand All @@ -70,4 +122,7 @@ data class WatchLinkData(
val installId: String? = null,
val transferAttempts: Int = 0,
val transferLockedUntilMs: Long = 0,
val watchInvoices: Map<String, Long> = emptyMap(),
val watchQuickPay: QuickPayDoc? = null,
val watchSends: List<OpenSend> = emptyList(),
)
6 changes: 6 additions & 0 deletions app/src/main/java/to/bitkit/di/WatchLinkModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -14,4 +16,8 @@ abstract class WatchLinkModule {
@Binds
@Singleton
abstract fun bindLinkKeyStore(keys: KeystoreLinkKeys): LinkKeyStore

@Binds
@Singleton
abstract fun bindWatchGuardState(store: WatchLinkStore): WatchGuardState
}
12 changes: 11 additions & 1 deletion app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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<String, InFlightOp>()
Expand Down Expand Up @@ -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()
Expand Down
21 changes: 16 additions & 5 deletions app/src/main/java/to/bitkit/repositories/QuickPaySpendStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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? {
Expand All @@ -41,12 +47,17 @@ internal class QuickPaySpendStore(
keepHashes: Set<String> = 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(),
Expand Down
47 changes: 39 additions & 8 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -100,6 +102,7 @@ class SparkRepo @Inject constructor(
private val coreService: Provider<CoreService>,
private val settingsStore: SettingsStore,
private val payoutChain: SparkPayoutChain,
private val watchGuards: WatchGuardState,
) {
companion object {
private const val TAG = "SparkRepo"
Expand Down Expand Up @@ -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<ULong> = withContext(bgDispatcher) {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -771,6 +793,15 @@ class SparkRepo @Inject constructor(
}
}

private suspend fun isOpenOnWatch(paymentHash: String, local: List<Payment>?): 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.
Expand Down
Loading