diff --git a/Bitkit/Models/PaykitAllowanceStateBackup.swift b/Bitkit/Models/PaykitAllowanceStateBackup.swift index 74bb18233..5421d110e 100644 --- a/Bitkit/Models/PaykitAllowanceStateBackup.swift +++ b/Bitkit/Models/PaykitAllowanceStateBackup.swift @@ -89,6 +89,17 @@ struct PaykitAllowanceStateBackup: Codable { let unannouncedOfferIds: Set let notifiedRequestIds: Set let lastTrustedTime: String? + let ledgerRevisionFloor: UInt64? + let automaticSpends: [AutomaticSpend]? + let endedAllowanceIds: Set? + + struct AutomaticSpend: Codable { + let attemptId: String + let counterparty: String + let allowanceId: String + let amountSats: UInt64 + let admittedAt: String + } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -98,6 +109,9 @@ struct PaykitAllowanceStateBackup: Codable { try container.encode(unannouncedOfferIds, forKey: .unannouncedOfferIds) try container.encode(notifiedRequestIds, forKey: .notifiedRequestIds) try container.encode(lastTrustedTime, forKey: .lastTrustedTime) + try container.encode(ledgerRevisionFloor, forKey: .ledgerRevisionFloor) + try container.encode(automaticSpends ?? [], forKey: .automaticSpends) + try container.encode(endedAllowanceIds ?? [], forKey: .endedAllowanceIds) } init(_ state: PaykitAllowanceLocalState) { @@ -136,6 +150,17 @@ struct PaykitAllowanceStateBackup: Codable { unannouncedOfferIds = state.unannouncedOfferIds notifiedRequestIds = state.notifiedRequestIds lastTrustedTime = state.lastTrustedTime.map(PaykitAllowanceTime.format) + ledgerRevisionFloor = state.ledgerRevisionFloor + automaticSpends = state.automaticSpends.map { + AutomaticSpend( + attemptId: $0.attemptId, + counterparty: $0.counterparty, + allowanceId: $0.allowanceId, + amountSats: $0.amountSats, + admittedAt: PaykitAllowanceTime.format($0.admittedAt) + ) + } + endedAllowanceIds = state.endedAllowanceIds } func restored() throws -> PaykitAllowanceLocalState { @@ -177,7 +202,18 @@ struct PaykitAllowanceStateBackup: Codable { presentedProposalIds: presentedProposalIds, unannouncedOfferIds: unannouncedOfferIds, notifiedRequestIds: notifiedRequestIds, - lastTrustedTime: lastTrustedTime.map(Self.date) + lastTrustedTime: lastTrustedTime.map(Self.date), + ledgerRevisionFloor: ledgerRevisionFloor, + automaticSpends: (automaticSpends ?? []).map { + try PaykitAllowanceLocalState.AutomaticSpend( + attemptId: $0.attemptId, + counterparty: $0.counterparty, + allowanceId: $0.allowanceId, + amountSats: $0.amountSats, + admittedAt: Self.date($0.admittedAt) + ) + }, + endedAllowanceIds: endedAllowanceIds ?? [] ) } diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 0525ac328..a9c810fe0 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1516,6 +1516,9 @@ "wallet__activity_time" = "الوقت"; "subscriptions__allowances" = "المخصصات"; "subscriptions__allowances_empty_headline" = "أعدّ\nالمخصصات"; +"subscriptions__allowances_paused_description" = "سجلات الميزانيات لديك أقدم من سجلات استخدمتها هذه المحفظة من قبل. ستطلب الطلبات موافقتك حتى تستأنف."; +"subscriptions__allowances_paused_resume" = "استئناف"; +"subscriptions__allowances_paused_title" = "تم إيقاف الدفعات التلقائية مؤقتًا"; "subscriptions__allowances_empty_description" = "يمكنك تعيين حدود إنفاق لتلبية طلبات الدفع من جهات الاتصال الموثوقة تلقائيًا."; "subscriptions__allowance_add" = "إضافة مخصص"; "subscriptions__allowance_title" = "المخصص"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index a26d91ad9..39a720a6f 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1700,6 +1700,9 @@ "wallet__send_error_support" = "Contacta amb el suport"; "subscriptions__allowances" = "Assignacions"; "subscriptions__allowances_empty_headline" = "Configura\nassignacions"; +"subscriptions__allowances_paused_description" = "Els teus registres d'assignacions són més antics que altres que aquest moneder ja ha fet servir. Les sol·licituds demanaran la teva aprovació fins que reprenguis."; +"subscriptions__allowances_paused_resume" = "Reprèn"; +"subscriptions__allowances_paused_title" = "Pagaments automàtics en pausa"; "subscriptions__allowances_empty_description" = "Pots establir límits de despesa per pagar automàticament les sol·licituds de pagament de contactes de confiança."; "subscriptions__allowance_add" = "Afegir assignació"; "subscriptions__allowance_title" = "Assignació"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index a22a92c44..950debb88 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1839,6 +1839,9 @@ "usdt__deposit_refund_address_network" = "Adresa USDT v síti {network}"; "subscriptions__allowances" = "Povolení plateb"; "subscriptions__allowances_empty_headline" = "Nastavte\npovolení plateb"; +"subscriptions__allowances_paused_description" = "Záznamy vašich rozpočtů jsou starší než ty, které tato peněženka už použila. Požadavky budou čekat na vaše schválení, dokud platby neobnovíte."; +"subscriptions__allowances_paused_resume" = "Obnovit"; +"subscriptions__allowances_paused_title" = "Automatické platby pozastaveny"; "subscriptions__allowances_empty_description" = "Můžete nastavit limity útraty a automaticky tak vyřizovat žádosti o platbu od důvěryhodných kontaktů."; "subscriptions__allowance_add" = "Přidat povolení"; "subscriptions__allowance_title" = "Povolení plateb"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 4f2947113..22e5796f9 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1836,6 +1836,9 @@ "usdt__deposit_refund_address_network" = "USDT-Adresse auf {network}"; "subscriptions__allowances" = "Kontingente"; "subscriptions__allowances_empty_headline" = "Kontingente\neinrichten"; +"subscriptions__allowances_paused_description" = "Deine Budgetdaten sind älter als Daten, die diese Wallet bereits verwendet hat. Anfragen warten auf deine Bestätigung, bis du fortsetzt."; +"subscriptions__allowances_paused_resume" = "Fortsetzen"; +"subscriptions__allowances_paused_title" = "Automatische Zahlungen pausiert"; "subscriptions__allowances_empty_description" = "Lege Ausgabenlimits fest, um Zahlungsanforderungen vertrauenswürdiger Kontakte automatisch zu bezahlen."; "subscriptions__allowance_add" = "Kontingent hinzufügen"; "subscriptions__allowance_title" = "Kontingent"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 72e1221af..38324c6f5 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1571,6 +1571,9 @@ "wallet__send_error_support" = "Επικοινωνία με Υποστήριξη"; "subscriptions__allowances" = "Προεγκρίσεις"; "subscriptions__allowances_empty_headline" = "Ρύθμισε\nπροεγκρίσεις"; +"subscriptions__allowances_paused_description" = "Τα αρχεία των προϋπολογισμών σου είναι παλαιότερα από αρχεία που έχει ήδη χρησιμοποιήσει αυτό το πορτοφόλι. Τα αιτήματα θα ζητούν την έγκρισή σου μέχρι να συνεχίσεις."; +"subscriptions__allowances_paused_resume" = "Συνέχεια"; +"subscriptions__allowances_paused_title" = "Οι αυτόματες πληρωμές έχουν παυθεί"; "subscriptions__allowances_empty_description" = "Μπορείς να ορίσεις όρια δαπανών για να εξοφλούνται αυτόματα αιτήματα πληρωμής από αξιόπιστες επαφές."; "subscriptions__allowance_add" = "Προσθήκη προέγκρισης"; "subscriptions__allowance_title" = "Προέγκριση"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 7f9b9086f..d08c23131 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1713,6 +1713,9 @@ "settings__adv__pp_onchain_short" = "On-chain"; "subscriptions__allowances" = "Allowances"; "subscriptions__allowances_empty_headline" = "Set up\nallowances"; +"subscriptions__allowances_paused_description" = "Your allowance records are older than ones this wallet has already used. Requests ask for your approval until you resume."; +"subscriptions__allowances_paused_resume" = "Resume"; +"subscriptions__allowances_paused_title" = "Automatic payments paused"; "subscriptions__allowances_empty_description" = "You can set spending limits to automatically fulfill payment requests from trusted peers."; "subscriptions__allowance_add" = "Add Allowance"; "subscriptions__allowance_title" = "Allowance"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 2aa0720c1..1e80262c4 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1842,6 +1842,9 @@ "usdt__deposit_refund_address_network" = "Dirección USDT en {network}"; "subscriptions__allowances" = "Asignaciones"; "subscriptions__allowances_empty_headline" = "Configure\nasignaciones"; +"subscriptions__allowances_paused_description" = "Tus registros de asignaciones son más antiguos que otros que esta billetera ya usó. Las solicitudes pedirán tu aprobación hasta que reanudes."; +"subscriptions__allowances_paused_resume" = "Reanudar"; +"subscriptions__allowances_paused_title" = "Pagos automáticos en pausa"; "subscriptions__allowances_empty_description" = "Puede establecer límites de gasto para pagar automáticamente las solicitudes de pago de contactos de confianza."; "subscriptions__allowance_add" = "Añadir asignación"; "subscriptions__allowance_title" = "Asignación"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index effab3d04..6b3b23e96 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1720,6 +1720,9 @@ "wallet__send_error_support" = "Contactar con el servicio de asistencia"; "subscriptions__allowances" = "Asignaciones"; "subscriptions__allowances_empty_headline" = "Configure\nasignaciones"; +"subscriptions__allowances_paused_description" = "Tus registros de asignaciones son más antiguos que otros que este monedero ya ha usado. Las solicitudes pedirán tu aprobación hasta que reanudes."; +"subscriptions__allowances_paused_resume" = "Reanudar"; +"subscriptions__allowances_paused_title" = "Pagos automáticos en pausa"; "subscriptions__allowances_empty_description" = "Puede establecer límites de gasto para pagar automáticamente las solicitudes de pago de contactos de confianza."; "subscriptions__allowance_add" = "Añadir asignación"; "subscriptions__allowance_title" = "Asignación"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 25954b7c5..40a10c8da 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1850,6 +1850,9 @@ "usdt__deposit_refund_address_network" = "Adresse USDT sur {network}"; "subscriptions__allowances" = "Allocations"; "subscriptions__allowances_empty_headline" = "Configurez\ndes allocations"; +"subscriptions__allowances_paused_description" = "Vos données d'allocations sont plus anciennes que celles que ce portefeuille a déjà utilisées. Les demandes attendront votre accord jusqu'à la reprise."; +"subscriptions__allowances_paused_resume" = "Reprendre"; +"subscriptions__allowances_paused_title" = "Paiements automatiques en pause"; "subscriptions__allowances_empty_description" = "Vous pouvez définir des limites de dépenses pour régler automatiquement les demandes de paiement de contacts de confiance."; "subscriptions__allowance_add" = "Ajouter une allocation"; "subscriptions__allowance_title" = "Allocation"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 090a83510..bc1c231a9 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1809,6 +1809,9 @@ "usdt__deposit_refund_address_network" = "Indirizzo USDT su {network}"; "subscriptions__allowances" = "Plafond"; "subscriptions__allowances_empty_headline" = "Imposta\ni plafond"; +"subscriptions__allowances_paused_description" = "I dati dei tuoi budget sono più vecchi di quelli che questo wallet ha già usato. Le richieste chiederanno la tua approvazione finché non riprendi."; +"subscriptions__allowances_paused_resume" = "Riprendi"; +"subscriptions__allowances_paused_title" = "Pagamenti automatici in pausa"; "subscriptions__allowances_empty_description" = "Puoi impostare limiti di spesa per pagare automaticamente le richieste di pagamento dei contatti fidati."; "subscriptions__allowance_add" = "Aggiungi Plafond"; "subscriptions__allowance_title" = "Plafond"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 186b8903e..3ad3cc2eb 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1844,6 +1844,9 @@ "usdt__deposit_refund_address_network" = "USDT-adres op {network}"; "subscriptions__allowances" = "Toelagen"; "subscriptions__allowances_empty_headline" = "Stel\ntoelagen in"; +"subscriptions__allowances_paused_description" = "Je toelagengegevens zijn ouder dan gegevens die deze wallet al heeft gebruikt. Verzoeken vragen om je goedkeuring tot je hervat."; +"subscriptions__allowances_paused_resume" = "Hervatten"; +"subscriptions__allowances_paused_title" = "Automatische betalingen gepauzeerd"; "subscriptions__allowances_empty_description" = "U kunt bestedingslimieten instellen om betaalverzoeken van vertrouwde contacten automatisch te voldoen."; "subscriptions__allowance_add" = "Toelage toevoegen"; "subscriptions__allowance_title" = "Toelage"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index cb3d90b3b..202883049 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1849,6 +1849,9 @@ "usdt__deposit_refund_address_network" = "Adres USDT w sieci {network}"; "subscriptions__allowances" = "Przydziały"; "subscriptions__allowances_empty_headline" = "Ustaw\nprzydziały"; +"subscriptions__allowances_paused_description" = "Dane Twoich budżetów są starsze niż te, których ten portfel już użył. Prośby będą czekać na Twoją zgodę, dopóki nie wznowisz."; +"subscriptions__allowances_paused_resume" = "Wznów"; +"subscriptions__allowances_paused_title" = "Płatności automatyczne wstrzymane"; "subscriptions__allowances_empty_description" = "Możesz ustawić limity wydatków, aby automatycznie realizować żądania płatności od zaufanych kontaktów."; "subscriptions__allowance_add" = "Dodaj przydział"; "subscriptions__allowance_title" = "Przydział"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 9efd0eac8..4faf8c030 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1850,6 +1850,9 @@ "usdt__deposit_refund_address_network" = "Endereço USDT na rede {network}"; "subscriptions__allowances" = "Pré-aprovações"; "subscriptions__allowances_empty_headline" = "Configure\npré-aprovações"; +"subscriptions__allowances_paused_description" = "Os registros das suas mesadas são mais antigos do que outros que esta carteira já usou. As solicitações vão pedir sua aprovação até você retomar."; +"subscriptions__allowances_paused_resume" = "Retomar"; +"subscriptions__allowances_paused_title" = "Pagamentos automáticos pausados"; "subscriptions__allowances_empty_description" = "Você pode definir limites de gastos para pagar automaticamente solicitações de pagamento de contatos confiáveis."; "subscriptions__allowance_add" = "Adicionar Pré-aprovação"; "subscriptions__allowance_title" = "Pré-aprovação"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 4755b803d..39517cb3a 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1496,6 +1496,9 @@ "usdt__deposit_refund_address_network" = "Endereço USDT na rede {network}"; "subscriptions__allowances" = "Pré-aprovações"; "subscriptions__allowances_empty_headline" = "Configure\npré-aprovações"; +"subscriptions__allowances_paused_description" = "Os registos das suas mesadas são mais antigos do que outros que esta carteira já usou. Os pedidos vão pedir a sua aprovação até retomar."; +"subscriptions__allowances_paused_resume" = "Retomar"; +"subscriptions__allowances_paused_title" = "Pagamentos automáticos em pausa"; "subscriptions__allowances_empty_description" = "Pode definir limites de gastos para pagar automaticamente pedidos de pagamento de contactos de confiança."; "subscriptions__allowance_add" = "Adicionar pré-aprovação"; "subscriptions__allowance_title" = "Pré-aprovação"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index 958a58888..b5a9162a2 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1830,6 +1830,9 @@ "usdt__deposit_refund_address_network" = "Адрес USDT в сети {network}"; "subscriptions__allowances" = "Лимиты автооплаты"; "subscriptions__allowances_empty_headline" = "Настройте\nлимиты автооплаты"; +"subscriptions__allowances_paused_description" = "Данные ваших бюджетов старше тех, что этот кошелёк уже использовал. Запросы будут ждать вашего подтверждения, пока вы не возобновите платежи."; +"subscriptions__allowances_paused_resume" = "Возобновить"; +"subscriptions__allowances_paused_title" = "Автоматические платежи приостановлены"; "subscriptions__allowances_empty_description" = "Вы можете задать лимиты расходов, чтобы автоматически оплачивать запросы на оплату от доверенных контактов."; "subscriptions__allowance_add" = "Добавить Лимит"; "subscriptions__allowance_title" = "Лимит автооплаты"; diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index e1c2226f4..d5a57eb2c 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -669,7 +669,11 @@ class BackupService { if let paymentState = payload.paykitPaymentState { // VssBackupClient's existing custom backup namespace is explicitly wallet index 0. let backupWallet = try await PaykitPaymentStateBackup.ActiveOnchainAttempt.Wallet.backupNamespace(index: 0) - try await PaykitPaymentProofService.shared.restoreBackup(paymentState, wallet: backupWallet) + try await PaykitPaymentProofService.shared.restoreBackup( + paymentState, + wallet: backupWallet, + hasLedger: payload.paykitSdkBackupState != nil + ) } try TransferStorage.shared.upsertList(payload.transfers) await PrivatePaykitAddressReservationStore.shared.restoreBackup( diff --git a/Bitkit/Services/PaykitAllowance.swift b/Bitkit/Services/PaykitAllowance.swift index f67029fdb..3455e4e7c 100644 --- a/Bitkit/Services/PaykitAllowance.swift +++ b/Bitkit/Services/PaykitAllowance.swift @@ -284,6 +284,7 @@ enum PaykitAllowanceTime { /// Allowance's live automatic attempts in the current month first and keeps an over-cap request on the manual flow. enum PaykitAllowanceCapacity { struct Attempt: Equatable { + let attemptId: String let counterparty: String let allowanceId: String let amountSats: UInt64 @@ -302,7 +303,8 @@ enum PaykitAllowanceCapacity { .reduce(0) { $0 + $1.amountSats } } - static func fits(amountSats: UInt64, allowance: PaykitAllowance, attempts: [Attempt], now: Date) -> Bool { + /// Spending counts the higher of the ledger's `attempts` and this wallet's own `localAttempts`. + static func fits(amountSats: UInt64, allowance: PaykitAllowance, attempts: [Attempt], now: Date, localAttempts: [Attempt] = []) -> Bool { if let perPaymentMaxSats = allowance.perPaymentMaxSats, amountSats > perPaymentMaxSats { return false } @@ -310,10 +312,26 @@ enum PaykitAllowanceCapacity { guard allowance.perPaymentMaxSats != nil, let monthlyLimitSats = allowance.monthlyLimitSats, let anchor = allowance.monthlyAnchor else { return false } - let used = usedSats(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId, attempts: attempts, anchor: anchor, now: now) + // Every attempt of the ledger and of this wallet counts once, so neither side's missing attempts hide the other's. + let ledgerIds = Set(attempts.map(\.attemptId)) + let all = attempts + localAttempts.filter { !ledgerIds.contains($0.attemptId) } + let used = usedSats(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId, attempts: all, anchor: anchor, now: now) return used + amountSats <= monthlyLimitSats } + static func attempts(from spends: [PaykitAllowanceLocalState.AutomaticSpend]) -> [Attempt] { + spends.map { + Attempt( + attemptId: $0.attemptId, + counterparty: $0.counterparty, + allowanceId: $0.allowanceId, + amountSats: $0.amountSats, + admittedAt: $0.admittedAt, + isLive: true + ) + } + } + static func attempts(from history: Paykit.AllowanceAccountingHistory) -> [Attempt] { history.occurrences.flatMap { occurrence in occurrence.attempts.map { (counterparty: occurrence.key.request.counterparty, attempt: $0) } @@ -324,6 +342,7 @@ enum PaykitAllowanceCapacity { let amountSats = PaykitAllowance.sats(fromBitcoinAmount: attempt.amount.value()) else { return nil } return Attempt( + attemptId: attempt.attemptId, counterparty: counterparty, allowanceId: allowanceId, amountSats: amountSats, diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index af9aaeedc..39087cb41 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -94,6 +94,30 @@ struct PaykitAllowanceLocalState: Codable, Equatable { var unannouncedOfferIds: Set = [] var notifiedRequestIds: Set = [] var lastTrustedTime: Date? + /// The highest ledger revision this wallet has read; automatic payments stop while the ledger is below it. + var ledgerRevisionFloor: UInt64? + /// Automatic payments admitted by this wallet, counted against each monthly limit next to the ledger's own. + var automaticSpends: [AutomaticSpend] = [] + /// Scoped ids of allowances seen ended or declined, which never pay automatically again. + var endedAllowanceIds: Set = [] + + struct AutomaticSpend: Codable, Equatable { + let attemptId: String + let counterparty: String + let allowanceId: String + let amountSats: UInt64 + let admittedAt: Date + } + + /// Keeps the higher floor, every spend and every ended allowance of both states, so a restore never lowers them. + func withChecks(from other: PaykitAllowanceLocalState) -> PaykitAllowanceLocalState { + var merged = self + merged.ledgerRevisionFloor = [ledgerRevisionFloor, other.ledgerRevisionFloor].compactMap { $0 }.max() + let knownAttemptIds = Set(automaticSpends.map(\.attemptId)) + merged.automaticSpends += other.automaticSpends.filter { !knownAttemptIds.contains($0.attemptId) } + merged.endedAllowanceIds.formUnion(other.endedAllowanceIds) + return merged + } /// Allowance ids are unique only within one link, so a group also matches its counterparty. func group(containing allowanceId: String, counterparty: String) -> Group? { @@ -101,6 +125,22 @@ struct PaykitAllowanceLocalState: Codable, Equatable { } } +extension PaykitAllowanceLocalState { + /// A record saved by an earlier build may lack newer keys; they start empty instead of discarding the record. + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + groups = try container.decodeIfPresent([Group].self, forKey: .groups) ?? [] + journal = try container.decodeIfPresent([JournalEntry].self, forKey: .journal) ?? [] + presentedProposalIds = try container.decodeIfPresent(Set.self, forKey: .presentedProposalIds) ?? [] + unannouncedOfferIds = try container.decodeIfPresent(Set.self, forKey: .unannouncedOfferIds) ?? [] + notifiedRequestIds = try container.decodeIfPresent(Set.self, forKey: .notifiedRequestIds) ?? [] + lastTrustedTime = try container.decodeIfPresent(Date.self, forKey: .lastTrustedTime) + ledgerRevisionFloor = try container.decodeIfPresent(UInt64.self, forKey: .ledgerRevisionFloor) + automaticSpends = try container.decodeIfPresent([AutomaticSpend].self, forKey: .automaticSpends) ?? [] + endedAllowanceIds = try container.decodeIfPresent(Set.self, forKey: .endedAllowanceIds) ?? [] + } +} + protocol PaykitAllowanceStoring: Sendable { func load(identity: String) throws -> PaykitAllowanceLocalState func save(_ state: PaykitAllowanceLocalState, identity: String) throws @@ -145,13 +185,19 @@ struct PaykitAllowanceKeychainStore: PaykitAllowanceStoring { } } - /// Restores each identity's state it can read over the local one; identities the backup lacks keep theirs. A failure - /// here never stops the rest of the wallet restore. - func restoreBackup(_ snapshot: PaykitAllowanceStateBackups) { + /// Restores each identity's state it can read over the local one; identities the backup lacks keep theirs. The automatic + /// payment checks merge with the local ones, so a restore never weakens them. A failure here never stops the rest of the + /// wallet restore. A ledger revision floor only holds next to the ledger it was read from, so a backup without one drops it. + func restoreBackup(_ snapshot: PaykitAllowanceStateBackups, keepsLedgerFloors: Bool = true) { var all = (try? loadAll()) ?? [:] for (identity, backup) in snapshot.byIdentity { do { - all[PubkyPublicKeyFormat.normalized(identity) ?? identity] = try backup.restored() + let key = PubkyPublicKeyFormat.normalized(identity) ?? identity + var restored = try backup.restored() + if !keepsLedgerFloors { + restored.ledgerRevisionFloor = nil + } + all[key] = all[key].map(restored.withChecks(from:)) ?? restored } catch { Logger.warn("Skipped an unreadable allowance state in a backup: \(error)", context: "PaykitAllowance") } @@ -168,8 +214,9 @@ struct PaykitAllowanceKeychainStore: PaykitAllowanceStoring { do { return try JSONDecoder().decode(Stored.self, from: data) } catch { - Logger.warn("Discarding invalid Paykit allowance state: \(error)", context: "PaykitAllowance") - return [:] + // Never replaced by a save: a record this build can't read keeps every identity's journal for a later one. + Logger.warn("Failed to read Paykit allowance state: \(error)", context: "PaykitAllowance") + throw error } } } @@ -367,6 +414,10 @@ enum PaykitAllowanceManualPaymentError: LocalizedError { actor PaykitAllowanceExecutor { static let shared = PaykitAllowanceExecutor() + /// Spends kept for the monthly limit: two of the longest windows. + private static let spendRetention: TimeInterval = 62 * 24 * 60 * 60 + private static let sentStages: Set = [.submitted, .sending, .sent, .succeeded, .unknown] + private static let eventSubject = PassthroughSubject() nonisolated static var eventPublisher: AnyPublisher { @@ -378,6 +429,8 @@ actor PaykitAllowanceExecutor { private let payer: any PaykitAllowancePaying private let lightningLookup: any PaykitLightningPaymentProofLookingUp private let now: @Sendable () -> Date + /// Held from an automatic payment's ended check to its handoff, and from saving an End to the SDK's End. + private let handoffLock = PaykitAllowanceHandoffLock() private var inFlightRequestIds = Set() private(set) var activeIdentity: String? @@ -442,6 +495,52 @@ actor PaykitAllowanceExecutor { try store.save(state, identity: identity) } + /// Remembers every ended or declined allowance in `allowances`, so it never pays automatically again. + func rememberEndedAllowances(identity: String, allowances: [PaykitAllowance]) { + let ended = Set(allowances.filter { [.ended, .rejected].contains($0.lifecycleState) }.map(\.scopedId)) + guard !ended.isSubset(of: localState(identity: identity).endedAllowanceIds) else { return } + updateLocalState(identity: identity) { $0.endedAllowanceIds.formUnion(ended) } + } + + /// Like `rememberEndedAllowances`, then `send` hands the End to the SDK, while no automatic payment sits between its + /// ended check and its handoff. A failed save throws, so the End is not sent. + func rememberEnding(identity: String, allowances: [PaykitAllowance], send: () async throws -> Void) async throws { + try await handoffLock.withLock { + try checkedUpdateLocalState(identity: identity) { $0.endedAllowanceIds.formUnion(allowances.map(\.scopedId)) } + try await send() + } + } + + /// False when `ledger` is older than one this wallet has read, or missing after one was read; otherwise raises the floor to it. + /// A floor that cannot be saved throws, so nothing acts on that ledger. + private func acceptsLedger(_ ledger: Paykit.AllowanceAccountingState?, identity: String) throws -> Bool { + let floor = try store.load(identity: identity).ledgerRevisionFloor + guard let ledger else { return floor == nil } + if let floor, ledger.revision <= floor { + return ledger.revision == floor + } + try checkedUpdateLocalState(identity: identity) { $0.ledgerRevisionFloor = max($0.ledgerRevisionFloor ?? 0, ledger.revision) } + return true + } + + /// True while the ledger read is older than one this wallet has read, which keeps automatic payments paused. + func isLedgerBehind(identity: String) async -> Bool { + guard let floor = localState(identity: identity).ledgerRevisionFloor else { return false } + do { + guard let ledger = try await sdk.allowanceAccountingState() else { return true } + return ledger.revision < floor + } catch { + return false + } + } + + /// Takes the ledger read now as current, so automatic payments resume from it. This wallet's own spends, paid requests and + /// ended allowances still apply, so the limits it already used stay used. + func acceptCurrentLedger(identity: String) async throws { + let ledger = try await sdk.allowanceAccountingState() + try checkedUpdateLocalState(identity: identity) { $0.ledgerRevisionFloor = ledger?.revision } + } + func isHandling(_ requestId: PaykitPaymentRequest.ID) -> Bool { inFlightRequestIds.contains(requestId) } @@ -462,10 +561,12 @@ actor PaykitAllowanceExecutor { // MARK: Ledger /// Brings the SDK ledger to a reconciled state. A wallet with no ledger attests an empty history: it has never - /// paid through an Allowance. After a restore, outcomes come from the journal and the node. + /// paid through an Allowance. After a restore, outcomes come from the journal and the node. Throws `ledgerBehind`, writing + /// nothing, when the ledger is behind one this wallet has read. @discardableResult func ensureReconciled(identity: String) async throws -> Paykit.AllowanceAccountingState { let current = try await sdk.allowanceAccountingState() + guard try acceptsLedger(current, identity: identity) else { throw PaykitAllowanceError.ledgerBehind } if let current, !current.requiresReconciliation { return current } @@ -487,6 +588,7 @@ actor PaykitAllowanceExecutor { ) ) Logger.info("Reconciled Paykit allowance accounting with \(outcomes.count) verified outcomes", context: "PaykitAllowance") + guard try acceptsLedger(reconciled, identity: identity) else { throw PaykitAllowanceError.ledgerBehind } return reconciled } @@ -499,6 +601,11 @@ actor PaykitAllowanceExecutor { // Needs no node, so it runs before reconciliation, which waits for the node's payment history. await retryPaymentListReleases(identity: identity) let state = try await ensureReconciled(identity: identity) + // A failed attempt paid nothing, so it stops counting, also when the journal no longer holds it. + let failedIds = Set(state.history.occurrences.flatMap(\.attempts).filter { $0.status == .failed }.map(\.attemptId)) + if localState(identity: identity).automaticSpends.contains(where: { failedIds.contains($0.attemptId) }) { + updateLocalState(identity: identity) { $0.automaticSpends.removeAll { failedIds.contains($0.attemptId) } } + } // One journal read for the whole pass: each attempt appears once, so a stage changed below is never read again. let journalStages = Dictionary( localState(identity: identity).journal.map { ($0.attemptId, $0.stage) }, @@ -514,7 +621,9 @@ actor PaykitAllowanceExecutor { for attempt in occurrence.attempts { switch attempt.status { case .prepared: - guard attempt.epoch == state.epoch else { continue } + // A ledger saved before the handoff still says prepared; the journal knows it was sent. + guard attempt.epoch == state.epoch, !(journalStages[attempt.attemptId].map(Self.sentStages.contains) ?? false) + else { continue } try await record(attemptId: attempt.attemptId, outcome: .failed, identity: identity) case .submitted, .unknown: let verified: Paykit.PaymentOutcome? @@ -566,9 +675,24 @@ actor PaykitAllowanceExecutor { $0.isAllower && $0.status(at: now()) == .active && PubkyPublicKeyFormat.matches($0.counterparty, request.counterparty) } guard !covering.isEmpty else { return false } - let attempts = await automaticAttempts() + var attempts: [PaykitAllowanceCapacity.Attempt] = [] + do { + let ledger = try await sdk.allowanceAccountingState() + // A ledger behind this wallet keeps the request manual, without waiting for the node. + guard (try? acceptsLedger(ledger, identity: identity)) == true else { return true } + attempts = ledger.map { PaykitAllowanceCapacity.attempts(from: $0.history) } ?? [] + } catch { + Logger.warn("Failed to read allowance accounting for the limit check: \(error)", context: "PaykitAllowance") + } + let localAttempts = PaykitAllowanceCapacity.attempts(from: localState(identity: identity).automaticSpends) guard !covering.contains(where: { - PaykitAllowanceCapacity.fits(amountSats: request.allowanceAmountSats, allowance: $0, attempts: attempts, now: now()) + PaykitAllowanceCapacity.fits( + amountSats: request.allowanceAmountSats, + allowance: $0, + attempts: attempts, + now: now(), + localAttempts: localAttempts + ) }) else { return false } notifyLimitReached(request, identity: identity) return true @@ -675,6 +799,12 @@ actor PaykitAllowanceExecutor { var settledEntry: PaykitAllowanceLocalState.JournalEntry? do { var state = try store.load(identity: identity) + var isChanged = false + // A failed attempt paid nothing, so it no longer counts against its limit. + if outcome == .failed, state.automaticSpends.contains(where: { $0.attemptId == attemptId }) { + state.automaticSpends.removeAll { $0.attemptId == attemptId } + isChanged = true + } if let index = state.journal.firstIndex(where: { $0.attemptId == attemptId }), !onlyIfOpen || !state.journal[index].stage.isTerminal { @@ -687,6 +817,9 @@ actor PaykitAllowanceExecutor { case .failed: state.journal[index].stage = .failed case .unknown: state.journal[index].stage = .unknown } + isChanged = true + } + if isChanged { try store.save(state, identity: identity) } } catch { @@ -703,11 +836,6 @@ actor PaykitAllowanceExecutor { return entry } - func automaticAttempts() async -> [PaykitAllowanceCapacity.Attempt] { - guard let state = try? await sdk.allowanceAccountingState() else { return [] } - return PaykitAllowanceCapacity.attempts(from: state.history) - } - struct AutomaticPayment: Equatable { let requestId: PaykitPaymentRequest.ID let allowanceId: String @@ -780,13 +908,29 @@ actor PaykitAllowanceExecutor { identity: String, activation: String? ) async throws -> PaykitAllowanceAutoPayResult { + if localState(identity: identity).journal.contains(where: { + $0.stage != .failed && $0.requestId.paymentRequestId == request.paymentRequestId && + PubkyPublicKeyFormat.matches($0.requestId.counterparty, request.counterparty) + }) { + Logger.info("Kept an incoming request manual: this wallet already paid it", context: "PaykitAllowance") + return .manual + } let scope = Paykit.PaymentRequestScope( counterparty: request.counterparty, paymentRequestId: request.paymentRequestId ) let selectionTime = trustedTime(identity: identity) let candidates = try await sdk.evaluateAllowanceCandidates(scope: scope, trustedTime: selectionTime) - guard let candidate = candidates.first(where: { $0.blocked == nil }), + let local = localState(identity: identity) + let unblocked = candidates.filter { $0.blocked == nil } + let unended = unblocked.filter { + !local.endedAllowanceIds.contains(PaykitAllowance.scopedId(counterparty: request.counterparty, allowanceId: $0.allowanceId)) + } + if unended.isEmpty, !unblocked.isEmpty { + Logger.info("Kept an incoming request manual: its allowance has ended", context: "PaykitAllowance") + return .manual + } + guard let candidate = unended.first, let allowance = allowances.first(where: { $0.allowanceId == candidate.allowanceId && PubkyPublicKeyFormat.matches($0.counterparty, request.counterparty) }) @@ -803,8 +947,18 @@ actor PaykitAllowanceExecutor { return .manual } - let attempts = await automaticAttempts() - guard PaykitAllowanceCapacity.fits(amountSats: request.allowanceAmountSats, allowance: allowance, attempts: attempts, now: now()) else { + let ledger = try await sdk.allowanceAccountingState() + guard try acceptsLedger(ledger, identity: identity) else { + Logger.info("Kept an incoming request manual: the ledger is behind this wallet", context: "PaykitAllowance") + return .manual + } + guard PaykitAllowanceCapacity.fits( + amountSats: request.allowanceAmountSats, + allowance: allowance, + attempts: ledger.map { PaykitAllowanceCapacity.attempts(from: $0.history) } ?? [], + now: now(), + localAttempts: PaykitAllowanceCapacity.attempts(from: local.automaticSpends) + ) else { Logger.info("Allowance monthly limit reached; the request stays on the manual flow", context: "PaykitAllowance") notifyLimitReached(request, identity: identity) return .manual @@ -882,6 +1036,22 @@ actor PaykitAllowanceExecutor { return .manual } + do { + try rememberSpend( + PaykitAllowanceLocalState.AutomaticSpend( + attemptId: prepared.attemptId, + counterparty: request.counterparty, + allowanceId: prepared.allowanceId ?? candidate.allowanceId, + amountSats: request.allowanceAmountSats, + admittedAt: PaykitAllowanceTime.parse(prepared.admittedAt) ?? now() + ), + identity: identity + ) + } catch { + try? await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) + throw error + } + journal( PaykitAllowanceLocalState.JournalEntry( attemptId: prepared.attemptId, @@ -901,16 +1071,27 @@ actor PaykitAllowanceExecutor { // Begin fetches nothing, so pull the link first: an End or a cancellation must be seen before the handoff. _ = try? await sdk.receivePrivateMessages(counterparty: request.counterparty) - let handoff: Paykit.PaymentAttemptDecision - do { - handoff = try await sdk.beginPaymentExecution( - attemptId: prepared.attemptId, - checks: checks(request, endpointIdentifier: endpointIdentifier, trustedTime: trustedTime(identity: identity)) - ) - } catch { - // Nothing left the wallet, so release the reservation before the request goes back to manual payment. - try? await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) - throw error + // An End saved while this attempt was admitted stops it; one saved later reaches the SDK after this handoff. + let scopedId = PaykitAllowance.scopedId(counterparty: request.counterparty, allowanceId: prepared.allowanceId ?? candidate.allowanceId) + let decision: Paykit.PaymentAttemptDecision? = try await handoffLock.withLock { + if localState(identity: identity).endedAllowanceIds.contains(scopedId) { + return nil + } + do { + return try await sdk.beginPaymentExecution( + attemptId: prepared.attemptId, + checks: checks(request, endpointIdentifier: endpointIdentifier, trustedTime: trustedTime(identity: identity)) + ) + } catch { + // Nothing left the wallet, so release the reservation before the request goes back to manual payment. + try? await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) + throw error + } + } + guard let handoff = decision else { + Logger.info("Kept an incoming request manual: its allowance has ended", context: "PaykitAllowance") + try await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) + return .manual } guard case let .ready(submitted) = handoff else { try await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) @@ -1147,6 +1328,15 @@ actor PaykitAllowanceExecutor { private struct JournalEntryMissing: Error {} + /// Saved before the handoff: a failed save throws, so no automatic payment leaves uncounted. + private func rememberSpend(_ spend: PaykitAllowanceLocalState.AutomaticSpend, identity: String) throws { + let retainedSince = now().addingTimeInterval(-Self.spendRetention) + try checkedUpdateLocalState(identity: identity) { state in + state.automaticSpends.removeAll { $0.admittedAt < retainedSince || $0.attemptId == spend.attemptId } + state.automaticSpends.append(spend) + } + } + private func journal(_ entry: PaykitAllowanceLocalState.JournalEntry, identity: String) { updateLocalState(identity: identity) { state in state.journal.removeAll { $0.attemptId == entry.attemptId } @@ -1191,3 +1381,25 @@ actor PaykitAllowanceExecutor { } } } + +/// A first-come lock an actor can hold across suspensions, which actor isolation alone does not give. +private actor PaykitAllowanceHandoffLock { + private var isLocked = false + private var waiters: [CheckedContinuation] = [] + + func withLock(_ operation: () async throws -> T) async rethrows -> T { + if isLocked { + await withCheckedContinuation { waiters.append($0) } + } else { + isLocked = true + } + defer { + if waiters.isEmpty { + isLocked = false + } else { + waiters.removeFirst().resume() + } + } + return try await operation() + } +} diff --git a/Bitkit/Services/PaykitAllowanceManager.swift b/Bitkit/Services/PaykitAllowanceManager.swift index fa14fbd90..f983011ee 100644 --- a/Bitkit/Services/PaykitAllowanceManager.swift +++ b/Bitkit/Services/PaykitAllowanceManager.swift @@ -44,11 +44,12 @@ enum PaykitAllowanceError: LocalizedError { case contactNotLinked case unavailable case paymentListPending + case ledgerBehind var errorDescription: String? { switch self { case .contactNotLinked: t("subscriptions__allowance_error_not_linked") - case .unavailable, .paymentListPending: t("subscriptions__allowance_error_unavailable") + case .unavailable, .paymentListPending, .ledgerBehind: t("subscriptions__allowance_error_unavailable") } } } @@ -59,6 +60,8 @@ final class PaykitAllowanceManager { private(set) var allowances: [PaykitAllowance] = [] private(set) var localState = PaykitAllowanceLocalState() private(set) var isWorking = false + /// True while the allowance ledger is behind one this wallet has read, until `resumeAutomaticPayments()`. + private(set) var isAutomaticPaymentPaused = false private(set) var autoPaidRequestIds: Set = [] /// Keyed by `PaykitAllowance.scopedId`, since another contact can reuse an allowance id. private(set) var autoPaidSatsByScopedId: [String: UInt64] = [:] @@ -169,6 +172,7 @@ final class PaykitAllowanceManager { localState = PaykitAllowanceLocalState() autoPaidRequestIds = [] autoPaidSatsByScopedId = [:] + isAutomaticPaymentPaused = false manualRequestIds = [:] announcedOfferIds = [] } @@ -186,12 +190,15 @@ final class PaykitAllowanceManager { allowances = records .filter { $0.historyStatus == .consistent || $0.historyStatus == .unresolvedReferences } .compactMap(PaykitAllowance.init(record:)) + await executor.rememberEndedAllowances(identity: identity, allowances: allowances) } catch { Logger.warn("Failed to list Paykit allowances: \(error)", context: "PaykitAllowance") } let state = await executor.localState(identity: identity) + let isPaused = await executor.isLedgerBehind(identity: identity) guard activation == refreshActivation else { return } localState = state + isAutomaticPaymentPaused = isPaused guard let paid = await executor.succeededAutomaticPayments(identity: identity), activation == refreshActivation else { return } autoPaidRequestIds = Set(paid.map(\.requestId)) autoPaidSatsByScopedId = paid.reduce(into: [:]) { totals, payment in @@ -276,16 +283,31 @@ final class PaykitAllowanceManager { } } + /// Resumes automatic payments from the ledger read now; see `PaykitAllowanceExecutor.acceptCurrentLedger(identity:)`. + func resumeAutomaticPayments() async throws { + isWorking = true + defer { isWorking = false } + guard let identity else { throw PaykitAllowanceError.unavailable } + try await executor.acceptCurrentLedger(identity: identity) + await executor.recover(identity: identity) + await refresh() + } + func end(_ entry: PaykitAllowanceEntry) async throws { isWorking = true defer { isWorking = false } - var endedAny = false - for allowance in entry.allowances where allowance.canEnd { - _ = try await sdk.endAllowance(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId) - endedAny = true + guard let identity else { throw PaykitAllowanceError.unavailable } + let endable = entry.allowances.filter(\.canEnd) + guard !endable.isEmpty else { throw PaykitAllowanceError.unavailable } + let sdk = sdk + try await executor.rememberEnding(identity: identity, allowances: endable) { + for allowance in endable { + _ = try await sdk.endAllowance(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId) + } + } + for allowance in endable { _ = try? await sdk.processOutboundPrivateMessages(counterparty: allowance.counterparty) } - guard endedAny else { throw PaykitAllowanceError.unavailable } await refresh() } diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index f3483f49e..94037be5f 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -306,7 +306,11 @@ actor PaykitPaymentProofService { } } - func restoreBackup(_ state: PaykitPaymentStateBackup, wallet: PaykitPaymentStateBackup.ActiveOnchainAttempt.Wallet) async throws { + func restoreBackup( + _ state: PaykitPaymentStateBackup, + wallet: PaykitPaymentStateBackup.ActiveOnchainAttempt.Wallet, + hasLedger: Bool = true + ) async throws { let proofs = try state.pendingProofs.map { try $0.restored() } let restored = try state.activeOnchainAttempt.map { try $0.restored(wallet: wallet, proofs: proofs) } // Persist the block first. A later proof/SDK restore failure leaves the original guard intact. @@ -315,7 +319,7 @@ actor PaykitPaymentProofService { try PaykitSubscriptionStateStore().restoreBackup(state.subscriptions) try PaykitPaymentRequestIdStore(key: .paykitAcceptedPaymentRequests).restoreBackup(state.acceptedOneTimeRequests ?? [:]) if let allowances = state.allowances { - PaykitAllowanceKeychainStore().restoreBackup(allowances) + PaykitAllowanceKeychainStore().restoreBackup(allowances, keepsLedgerFloors: hasLedger) } } diff --git a/Bitkit/Views/Subscriptions/AllowancesView.swift b/Bitkit/Views/Subscriptions/AllowancesView.swift index 666bdc4a5..10e67444d 100644 --- a/Bitkit/Views/Subscriptions/AllowancesView.swift +++ b/Bitkit/Views/Subscriptions/AllowancesView.swift @@ -5,6 +5,9 @@ import SwiftUI struct AllowancesTab: View { @Environment(PaykitAllowanceManager.self) private var allowances @EnvironmentObject private var sheets: SheetViewModel + @EnvironmentObject private var app: AppViewModel + @EnvironmentObject private var settings: SettingsViewModel + @State private var authorization = PaymentAuthorization(pinMessage: t("security__pin_allowance")) var body: some View { Group { @@ -14,6 +17,7 @@ struct AllowancesTab: View { list } } + .paymentAuthorization(authorization) .task { await allowances.refresh() } @@ -22,6 +26,9 @@ struct AllowancesTab: View { private var list: some View { TimelineView(.periodic(from: .now, by: 60)) { context in LazyVStack(spacing: 12) { + if allowances.isAutomaticPaymentPaused { + pausedNotice + } ForEach(allowances.entries) { entry in Button { // An allower's offer is accepted in the background, so only an ask opens the review sheet. @@ -39,6 +46,36 @@ struct AllowancesTab: View { } } + private var pausedNotice: some View { + VStack(alignment: .leading, spacing: 0) { + BodyMSBText(t("subscriptions__allowances_paused_title")) + BodySText(t("subscriptions__allowances_paused_description"), textColor: .white64) + .padding(.top, 4) + CustomButton( + title: t("subscriptions__allowances_paused_resume"), + variant: .secondary, + size: .small, + isLoading: allowances.isWorking + ) { + // Resuming turns automatic payments back on, so it asks like the payer's other allowance actions. + guard await authorization.authorize(settings: settings) else { return } + do { + try await allowances.resumeAutomaticPayments() + } catch { + app.toast(error) + } + } + .accessibilityIdentifier("AllowancesResume") + .padding(.top, 16) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(16) + .background(Color.gray6) + .clipShape(RoundedRectangle(cornerRadius: 16)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("AllowancesPaused") + } + private var emptyState: some View { VStack(alignment: .leading, spacing: 0) { Spacer() diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 1141d9887..47e0e65fe 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -343,6 +343,287 @@ final class PaykitAllowanceExecutorTests: XCTestCase { XCTAssertEqual(limitEvents.count, 1) } + func testALedgerOlderThanOneAlreadyReadKeepsTheRequestManual() async throws { + let harness = AllowanceHarness() + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5), identity: Fixtures.identityKey) + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 4)) + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + let floor = await harness.executor.localState(identity: Fixtures.identityKey).ledgerRevisionFloor + XCTAssertEqual(floor, 5) + } + + func testResumingTakesTheLedgerReadNowWhileThisWalletsOwnSpendingStillCounts() async throws { + let harness = AllowanceHarness() + await harness.executor.activate(identity: Fixtures.identityKey) + let spend = PaykitAllowanceLocalState.AutomaticSpend( + attemptId: "local-1", + counterparty: Fixtures.counterpartyKey, + allowanceId: Fixtures.walletAllowanceId, + amountSats: 49500, + admittedAt: Fixtures.now + ) + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5, automaticSpends: [spend]), identity: Fixtures.identityKey) + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 4)) + + let pausedBefore = await harness.executor.isLedgerBehind(identity: Fixtures.identityKey) + try await harness.executor.acceptCurrentLedger(identity: Fixtures.identityKey) + let pausedAfter = await harness.executor.isLedgerBehind(identity: Fixtures.identityKey) + let overLimit = try await harness.executor.autoPay( + Fixtures.paymentRequest(), + allowances: [Fixtures.allowance()], + identity: Fixtures.identityKey + ) + await harness.executor.updateLocalState(identity: Fixtures.identityKey) { $0.automaticSpends = [] } + let underLimit = try await harness.executor.autoPay( + Fixtures.paymentRequest(), + allowances: [Fixtures.allowance()], + identity: Fixtures.identityKey + ) + + XCTAssertTrue(pausedBefore) + XCTAssertFalse(pausedAfter) + XCTAssertEqual(overLimit, .manual) + XCTAssertEqual(underLimit, .started) + } + + func testALedgerThatGoesBehindThisWalletDuringAdmissionKeepsTheRequestManual() async throws { + let harness = AllowanceHarness() + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5), identity: Fixtures.identityKey) + await harness.sdk.queueAccountingStates([Fixtures.accountingState(revision: 5), Fixtures.accountingState(revision: 3)]) + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + } + + func testRecoveryLeavesALedgerBehindTheFloorUnwritten() async { + let harness = AllowanceHarness() + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5), identity: Fixtures.identityKey) + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 4, requiresReconciliation: true)) + + await harness.executor.recover(identity: Fixtures.identityKey) + + XCTAssertFalse(harness.log.entries.contains("reconcileAllowanceAccounting")) + let floor = await harness.executor.localState(identity: Fixtures.identityKey).ledgerRevisionFloor + XCTAssertEqual(floor, 5) + } + + func testAMissingLedgerAfterOneWasReadKeepsTheRequestManual() async throws { + let harness = AllowanceHarness() + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5), identity: Fixtures.identityKey) + await harness.sdk.setAccountingState(nil) + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("reconcileAllowanceAccounting")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + } + + func testAFloorThatCannotBeSavedKeepsTheRequestManual() async throws { + let harness = AllowanceHarness() + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 7)) + harness.store.failSaves() + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + } + + func testLimitCheckHandsBackARequestWhileTheLedgerIsBehind() async throws { + let harness = AllowanceHarness() + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5), identity: Fixtures.identityKey) + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 4)) + let events = AllowanceEventRecorder() + + let request = try Fixtures.paymentRequest() + let isManual = await harness.executor.exceedsLimits(request, allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertTrue(isManual) + XCTAssertTrue(events.events.isEmpty, "A ledger behind the wallet raises no Limit Reached") + } + + func testAnAutomaticPaymentRaisesTheLedgerFloor() async throws { + let harness = AllowanceHarness() + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 7)) + + _ = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + let floor = await harness.executor.localState(identity: Fixtures.identityKey).ledgerRevisionFloor + XCTAssertEqual(floor, 7) + } + + func testLocalSpendingAboveTheLedgersKeepsTheRequestManual() async throws { + let harness = AllowanceHarness() + let spend = try PaykitAllowanceLocalState.AutomaticSpend( + attemptId: "local-1", + counterparty: Fixtures.counterpartyKey, + allowanceId: Fixtures.walletAllowanceId, + amountSats: 49500, + admittedAt: XCTUnwrap(PaykitAllowanceTime.parse("2026-09-20T10:00:00Z")) + ) + harness.store.seed(PaykitAllowanceLocalState(automaticSpends: [spend]), identity: Fixtures.identityKey) + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + } + + func testAnAutomaticPaymentCountsLocallyUntilItFails() async throws { + let harness = AllowanceHarness() + await harness.executor.activate(identity: Fixtures.identityKey) + + _ = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + let spends = await harness.executor.localState(identity: Fixtures.identityKey).automaticSpends + await harness.executor.lightningPaymentSettled(paymentHash: AllowanceHarness.paymentHash, succeeded: false) + + XCTAssertEqual(spends.map(\.attemptId), [AllowanceSdkMock.automaticAttemptId]) + XCTAssertEqual(spends.map(\.amountSats), [1000]) + let remaining = await harness.executor.localState(identity: Fixtures.identityKey).automaticSpends + XCTAssertTrue(remaining.isEmpty) + } + + func testRecoveryDropsTheSpendOfAFailedAttemptTheJournalNoLongerHolds() async throws { + let harness = AllowanceHarness() + let spend = PaykitAllowanceLocalState.AutomaticSpend( + attemptId: "trimmed-1", + counterparty: Fixtures.counterpartyKey, + allowanceId: Fixtures.walletAllowanceId, + amountSats: 1000, + admittedAt: Fixtures.now + ) + harness.store.seed(PaykitAllowanceLocalState(automaticSpends: [spend]), identity: Fixtures.identityKey) + try await harness.sdk.setAccountingState(Fixtures.accountingState(occurrences: [ + Fixtures.occurrence(requestId: "trimmed-1", attempts: [Fixtures.attemptRecord(id: "trimmed-1", status: .failed)]), + ])) + + await harness.executor.recover(identity: Fixtures.identityKey) + + let spends = await harness.executor.localState(identity: Fixtures.identityKey).automaticSpends + XCTAssertTrue(spends.isEmpty) + } + + func testSpendingTheLedgerLacksAddsToTheLedgersOwn() async throws { + let harness = AllowanceHarness() + let spend = PaykitAllowanceLocalState.AutomaticSpend( + attemptId: "local-1", + counterparty: Fixtures.counterpartyKey, + allowanceId: Fixtures.walletAllowanceId, + amountSats: 25000, + admittedAt: Fixtures.now + ) + harness.store.seed(PaykitAllowanceLocalState(automaticSpends: [spend]), identity: Fixtures.identityKey) + try await harness.sdk.setAccountingState(Fixtures.accountingState(occurrences: [ + Fixtures.occurrence(requestId: "other-install", attempts: [ + Fixtures.attemptRecord(id: "other-1", amount: "0.00025", status: .succeeded), + ]), + ])) + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + } + + func testARequestThisWalletAlreadyPaidNeverPaysAutomaticallyAgain() async throws { + let harness = AllowanceHarness() + let request = try Fixtures.paymentRequest() + harness.store.seed( + PaykitAllowanceLocalState(journal: [Self.journalEntry( + attemptId: AllowanceSdkMock.automaticAttemptId, request: request, stage: .sent, paymentHash: AllowanceHarness.paymentHash + )]), + identity: Fixtures.identityKey + ) + + let result = await harness.executor.autoPay(request, allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + } + + func testRecoveryKeepsASentAttemptTheLedgerStillHoldsAsPrepared() async throws { + let harness = AllowanceHarness() + let request = try Fixtures.paymentRequest() + let spend = PaykitAllowanceLocalState.AutomaticSpend( + attemptId: AllowanceSdkMock.automaticAttemptId, + counterparty: Fixtures.counterpartyKey, + allowanceId: Fixtures.walletAllowanceId, + amountSats: 1000, + admittedAt: Fixtures.now + ) + harness.store.seed( + PaykitAllowanceLocalState( + journal: [Self.journalEntry( + attemptId: AllowanceSdkMock.automaticAttemptId, request: request, stage: .sent, paymentHash: AllowanceHarness.paymentHash + )], + automaticSpends: [spend] + ), + identity: Fixtures.identityKey + ) + try await harness.sdk.setAccountingState(Fixtures.accountingState(occurrences: [ + Fixtures.occurrence(requestId: request.paymentRequestId, attempts: [ + Fixtures.attemptRecord(id: AllowanceSdkMock.automaticAttemptId, status: .prepared), + ]), + ])) + + await harness.executor.recover(identity: Fixtures.identityKey) + + let outcomes = await harness.sdk.recordedOutcomes + XCTAssertTrue(outcomes.isEmpty) + let local = await harness.executor.localState(identity: Fixtures.identityKey) + XCTAssertEqual(local.automaticSpends, [spend]) + XCTAssertEqual(local.journal.map(\.stage), [.sent]) + } + + func testAnAllowanceSeenEndedNeverPaysAutomaticallyAgain() async throws { + let harness = AllowanceHarness() + await harness.executor.rememberEndedAllowances(identity: Fixtures.identityKey, allowances: [Fixtures.allowance(state: .ended)]) + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("acceptPaymentRequestAutomatically")) + XCTAssertFalse(harness.log.entries.contains("resolve")) + } + + func testAnEndSavedDuringAHandoffReachesTheSdkAfterIt() async throws { + let harness = AllowanceHarness() + let gate = await harness.sdk.holdNextBegin() + let payment = Task { + try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + } + await Self.waitUntil { harness.log.entries.contains("beginPaymentExecution") } + + let end = Task { + try await harness.executor.rememberEnding(identity: Fixtures.identityKey, allowances: [Fixtures.allowance()]) { + harness.log.append("endAllowance") + } + } + try await Task.sleep(nanoseconds: 50_000_000) + + XCTAssertFalse(harness.log.entries.contains("endAllowance")) + let during = await harness.executor.localState(identity: Fixtures.identityKey) + XCTAssertTrue(during.endedAllowanceIds.isEmpty) + gate.open() + _ = try await payment.value + try await end.value + XCTAssertTrue(harness.log.entries.contains("endAllowance")) + let after = await harness.executor.localState(identity: Fixtures.identityKey) + XCTAssertEqual(after.endedAllowanceIds, [Fixtures.allowance().scopedId]) + } + func testRequestAbovePerPaymentLimitNotifiesOnceWhenTheSdkBlocksIt() async throws { let harness = AllowanceHarness() await harness.sdk.setCandidates([AllowanceHarness.candidate(blocked: .sharedRule(code: "per_payment_amount_exceeded"))]) @@ -359,9 +640,23 @@ final class PaykitAllowanceExecutorTests: XCTestCase { XCTAssertEqual(limitEvents.count, 1) } - func testPaymentIsNotSentWhenTheSendingStageCannotBeSaved() async throws { + func testAnUnsavedSpendStopsTheAttemptBeforeAnythingIsConsumed() async throws { let harness = AllowanceHarness() + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 1), identity: Fixtures.identityKey) harness.store.failSaves() + + let result = try await harness.executor.autoPay(Fixtures.paymentRequest(), allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) + + XCTAssertEqual(result, .manual) + XCTAssertFalse(harness.log.entries.contains("beginPaymentExecution")) + XCTAssertFalse(harness.log.entries.contains("consumePaymentList")) + let outcomes = await harness.sdk.recordedOutcomes + XCTAssertEqual(outcomes, [Paykit.PaymentOutcomeReport(attemptId: AllowanceSdkMock.automaticAttemptId, outcome: .failed)]) + } + + func testPaymentIsNotSentWhenTheSendingStageCannotBeSaved() async throws { + let harness = AllowanceHarness() + harness.store.failSavesOnceSpent() let request = try Fixtures.paymentRequest() let result = await harness.executor.autoPay(request, allowances: [Fixtures.allowance()], identity: Fixtures.identityKey) @@ -1118,6 +1413,21 @@ final class PaykitAllowanceExecutorTests: XCTestCase { XCTAssertEqual(journal, []) } + func testAManualPaymentIsNotReportedToALedgerBehindThisWallet() async throws { + let harness = AllowanceHarness() + await harness.executor.activate(identity: Fixtures.identityKey) + harness.store.seed(PaykitAllowanceLocalState(ledgerRevisionFloor: 5), identity: Fixtures.identityKey) + await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 4)) + + let request = try Fixtures.paymentRequest() + + let attemptId = try await harness.executor.beginManualPayment(request, paymentEndpointIdentifier: Fixtures.lightningIdentifier) + + XCTAssertNil(attemptId) + XCTAssertFalse(harness.log.entries.contains("reconcileAllowanceAccounting")) + XCTAssertFalse(harness.log.entries.contains("reserveManualPayment")) + } + func testManualPaymentIsJournaledAndSubmittedWhenReady() async throws { let harness = AllowanceHarness() await harness.executor.activate(identity: Fixtures.identityKey) @@ -1989,6 +2299,7 @@ private final class AllowanceMemoryStore: PaykitAllowanceStoring, @unchecked Sen private let lock = NSLock() private var states: [String: PaykitAllowanceLocalState] = [:] private var savesFail = false + private var savesFailOnceSpent = false private var failingSaves = 0 func load(identity: String) throws -> PaykitAllowanceLocalState { @@ -1997,7 +2308,7 @@ private final class AllowanceMemoryStore: PaykitAllowanceStoring, @unchecked Sen func save(_ state: PaykitAllowanceLocalState, identity: String) throws { try lock.withLock { - if savesFail { + if savesFail || (savesFailOnceSpent && states[identity]?.automaticSpends.isEmpty == false) { throw AllowanceMockError.unsupported } if failingSaves > 0 { @@ -2012,6 +2323,11 @@ private final class AllowanceMemoryStore: PaykitAllowanceStoring, @unchecked Sen lock.withLock { savesFail = true } } + /// Saves fail once an automatic spend is stored, so an attempt gets past its admission. + func failSavesOnceSpent() { + lock.withLock { savesFailOnceSpent = true } + } + func restoreSaves() { lock.withLock { savesFail = false } } @@ -2361,6 +2677,7 @@ private actor AllowanceSdkMock: PaykitAllowanceSdkHandling { private var records: [Paykit.AllowanceRecord] = [] private var peers: [LinkedPeerRecord] = [] private var accountingState: Paykit.AllowanceAccountingState? = PaykitAllowanceFixtures.accountingState() + private var queuedAccountingStates: [Paykit.AllowanceAccountingState?] = [] private var candidates: [Paykit.AllowanceCandidate] = [AllowanceHarness.candidate()] private var automaticReservation: Paykit.PaymentAttemptDecision? private var manualReservation: Paykit.PaymentAttemptDecision? @@ -2396,6 +2713,11 @@ private actor AllowanceSdkMock: PaykitAllowanceSdkHandling { accountingState = state } + /// Served one per read, then the last one stays. + func queueAccountingStates(_ states: [Paykit.AllowanceAccountingState?]) { + queuedAccountingStates = states + } + func setCandidates(_ candidates: [Paykit.AllowanceCandidate]) { self.candidates = candidates } @@ -2516,6 +2838,9 @@ private actor AllowanceSdkMock: PaykitAllowanceSdkHandling { func allowanceAccountingState() async throws -> Paykit.AllowanceAccountingState? { log.append("allowanceAccountingState") + if !queuedAccountingStates.isEmpty { + accountingState = queuedAccountingStates.removeFirst() + } return accountingState } @@ -2615,8 +2940,20 @@ private actor AllowanceSdkMock: PaykitAllowanceSdkHandling { )) } + private var beginGate: AllowanceGate? + + func holdNextBegin() -> AllowanceGate { + let gate = AllowanceGate() + beginGate = gate + return gate + } + func beginPaymentExecution(attemptId: String, checks: Paykit.PaymentExecutionChecks) async throws -> Paykit.PaymentAttemptDecision { log.append("beginPaymentExecution") + if let gate = beginGate { + beginGate = nil + await gate.wait() + } if let beginError { throw beginError } diff --git a/BitkitTests/PaykitAllowanceTests.swift b/BitkitTests/PaykitAllowanceTests.swift index e63f1ffbc..4ad7e4559 100644 --- a/BitkitTests/PaykitAllowanceTests.swift +++ b/BitkitTests/PaykitAllowanceTests.swift @@ -42,7 +42,16 @@ final class PaykitAllowanceTests: XCTestCase { presentedProposalIds: ["presented"], unannouncedOfferIds: ["unannounced"], notifiedRequestIds: ["notified"], - lastTrustedTime: Fixtures.now + lastTrustedTime: Fixtures.now, + ledgerRevisionFloor: 12, + automaticSpends: [.init( + attemptId: "attempt-1", + counterparty: Fixtures.counterpartyKey, + allowanceId: Fixtures.walletAllowanceId, + amountSats: 1000, + admittedAt: Fixtures.now + )], + endedAllowanceIds: ["\(Fixtures.counterpartyKey)/ended"] ) let data = try JSONEncoder().encode(PaykitAllowanceStateBackup(state)) @@ -59,6 +68,11 @@ final class PaykitAllowanceTests: XCTestCase { XCTAssertEqual(json["lastTrustedTime"] as? String, "2026-09-24T12:00:00.000Z") XCTAssertTrue(entry["onchainAddress"] is NSNull, "Android requires every key, so an absent value is written as null") XCTAssertTrue(entry["transactionId"] is NSNull) + XCTAssertEqual(json["ledgerRevisionFloor"] as? Int, 12) + let spend = try XCTUnwrap((json["automaticSpends"] as? [[String: Any]])?.first) + XCTAssertEqual(spend["admittedAt"] as? String, "2026-09-24T12:00:00.000Z") + XCTAssertEqual(spend["amountSats"] as? Int, 1000) + XCTAssertEqual(json["endedAllowanceIds"] as? [String], ["\(Fixtures.counterpartyKey)/ended"]) let restored = try JSONDecoder().decode(PaykitAllowanceStateBackup.self, from: data).restored() XCTAssertEqual(restored, state) @@ -90,6 +104,102 @@ final class PaykitAllowanceTests: XCTestCase { XCTAssertTrue(json["lastTrustedTime"] is NSNull) } + func testStateSavedBeforeTheAutomaticPaymentChecksStillDecodes() throws { + let earlier = PaykitAllowanceLocalState( + groups: [.init( + id: "group-1", + counterparty: Fixtures.counterpartyKey, + limits: Fixtures.limits, + allowanceIds: [Fixtures.walletAllowanceId], + createdAt: Fixtures.now + )], + journal: [.init( + attemptId: "attempt-1", + isAutomatic: true, + requestId: PaykitPaymentRequest.ID(paymentRequestId: "req-1", counterparty: Fixtures.counterpartyKey), + allowanceId: Fixtures.walletAllowanceId, + amountSats: 1000, + paymentEndpointIdentifier: Fixtures.lightningIdentifier, + paymentHash: "hash-1", + stage: .sending, + createdAt: Fixtures.now, + paymentListVersion: 4, + previousPaymentListVersion: 3 + )], + presentedProposalIds: ["presented"], + unannouncedOfferIds: ["contact/offer"], + notifiedRequestIds: ["notified"], + lastTrustedTime: Fixtures.now + ) + var current = try JSONSerialization.jsonObject(with: JSONEncoder().encode(earlier)) as? [String: Any] ?? [:] + for key in ["ledgerRevisionFloor", "automaticSpends", "endedAllowanceIds"] { + current.removeValue(forKey: key) + } + let previous = try JSONSerialization.data(withJSONObject: current) + + let state = try JSONDecoder().decode(PaykitAllowanceLocalState.self, from: previous) + let reloaded = try JSONDecoder().decode(PaykitAllowanceLocalState.self, from: JSONEncoder().encode(state)) + + XCTAssertEqual(state, earlier) + XCTAssertEqual(reloaded, earlier) + } + + func testABackupWrittenBeforeTheAutomaticPaymentChecksStillRestores() throws { + let state = PaykitAllowanceLocalState(notifiedRequestIds: ["notified"], ledgerRevisionFloor: 3, endedAllowanceIds: ["contact/a"]) + var current = try JSONSerialization.jsonObject(with: JSONEncoder().encode(PaykitAllowanceStateBackup(state))) as? [String: Any] ?? [:] + for key in ["ledgerRevisionFloor", "automaticSpends", "endedAllowanceIds"] { + current.removeValue(forKey: key) + } + let previous = try JSONSerialization.data(withJSONObject: current) + + let restored = try JSONDecoder().decode(PaykitAllowanceStateBackup.self, from: previous).restored() + + XCTAssertEqual(restored.notifiedRequestIds, ["notified"]) + XCTAssertNil(restored.ledgerRevisionFloor) + XCTAssertTrue(restored.endedAllowanceIds.isEmpty) + } + + func testARestoreWithoutTheLedgerDropsTheLedgerFloor() throws { + try? Keychain.delete(key: .paykitAllowanceState) + defer { try? Keychain.delete(key: .paykitAllowanceState) } + let store = PaykitAllowanceKeychainStore() + let backup = PaykitAllowanceStateBackups([ + Fixtures.identityKey: PaykitAllowanceStateBackup( + PaykitAllowanceLocalState(ledgerRevisionFloor: 5, endedAllowanceIds: ["contact/ended"]) + ), + ]) + + store.restoreBackup(backup, keepsLedgerFloors: false) + let withoutLedger = try store.load(identity: Fixtures.identityKey) + store.restoreBackup(backup) + let withLedger = try store.load(identity: Fixtures.identityKey) + + XCTAssertNil(withoutLedger.ledgerRevisionFloor) + XCTAssertEqual(withoutLedger.endedAllowanceIds, ["contact/ended"]) + XCTAssertEqual(withLedger.ledgerRevisionFloor, 5) + } + + func testRestoreNeverLowersTheAutomaticPaymentChecksAlreadyStored() { + let spend = PaykitAllowanceLocalState.AutomaticSpend( + attemptId: "attempt-1", counterparty: "contact", allowanceId: "allowance-1", amountSats: 1000, admittedAt: Fixtures.now + ) + let restoredSpend = PaykitAllowanceLocalState.AutomaticSpend( + attemptId: "attempt-2", counterparty: "contact", allowanceId: "allowance-1", amountSats: 1000, admittedAt: Fixtures.now + ) + let stored = PaykitAllowanceLocalState(ledgerRevisionFloor: 9, automaticSpends: [spend], endedAllowanceIds: ["contact/allowance-1"]) + let restored = PaykitAllowanceLocalState( + ledgerRevisionFloor: 4, + automaticSpends: [restoredSpend, spend], + endedAllowanceIds: ["contact/allowance-2"] + ) + + let merged = restored.withChecks(from: stored) + + XCTAssertEqual(merged.ledgerRevisionFloor, 9) + XCTAssertEqual(merged.automaticSpends, [restoredSpend, spend]) + XCTAssertEqual(merged.endedAllowanceIds, ["contact/allowance-1", "contact/allowance-2"]) + } + func testAnUnreadableAllowanceStateLeavesTheRestOfTheBackupReadable() throws { let json = Data(#""" { @@ -265,6 +375,7 @@ final class PaykitAllowanceTests: XCTestCase { let beforeMarchAnchor = PaykitAllowanceTime.monthlyWindow(anchor: marchAnchor, containing: Fixtures.utc("2026-01-15T00:00:00Z")) let allowance = Fixtures.allowance(monthlyAnchor: anchor) let lateMarchAttempt = PaykitAllowanceCapacity.Attempt( + attemptId: "late-march", counterparty: Fixtures.counterpartyKey, allowanceId: allowance.allowanceId, amountSats: 50000, @@ -402,6 +513,48 @@ final class PaykitAllowanceTests: XCTestCase { )) } + func testCapacityCountsTheLedgersAndThisWalletsOwnPaymentsTogether() { + let ledger = [Fixtures.capacityAttempt(sats: 25000, at: "2026-09-05T10:00:00Z", attemptId: "a")] + let local = [Fixtures.capacityAttempt(sats: 21000, at: "2026-09-12T10:00:00Z", attemptId: "b")] + + XCTAssertTrue(PaykitAllowanceCapacity.fits( + amountSats: 4000, + allowance: Fixtures.allowance(), + attempts: ledger, + now: Fixtures.now, + localAttempts: local + )) + XCTAssertFalse(PaykitAllowanceCapacity.fits( + amountSats: 4001, + allowance: Fixtures.allowance(), + attempts: ledger, + now: Fixtures.now, + localAttempts: local + )) + } + + func testCapacityCountsAPaymentBothSidesHoldOnce() { + let ledger = [Fixtures.capacityAttempt(sats: 45000, at: "2026-09-05T10:00:00Z", attemptId: "a")] + let local = [Fixtures.capacityAttempt(sats: 45000, at: "2026-09-05T10:00:00Z", attemptId: "a")] + + XCTAssertTrue(PaykitAllowanceCapacity.fits( + amountSats: 5000, + allowance: Fixtures.allowance(), + attempts: ledger, + now: Fixtures.now, + localAttempts: local + )) + } + + func testASaveNeverReplacesStateThisBuildCannotRead() throws { + let unreadable = Data(#"{"other":{"journal":[{"stage":"from-a-newer-build"}]}}"#.utf8) + try Keychain.upsert(key: .paykitAllowanceState, data: unreadable) + defer { try? Keychain.delete(key: .paykitAllowanceState) } + + XCTAssertThrowsError(try PaykitAllowanceKeychainStore().save(PaykitAllowanceLocalState(), identity: Fixtures.identityKey)) + XCTAssertEqual(try Keychain.load(key: .paykitAllowanceState), unreadable) + } + func testAttemptsFromHistoryKeepAutomaticAllowanceAttempts() throws { let history = try Paykit.AllowanceAccountingHistory( associations: [], @@ -423,6 +576,7 @@ final class PaykitAllowanceTests: XCTestCase { XCTAssertEqual(attempts, [ PaykitAllowanceCapacity.Attempt( + attemptId: "failed", counterparty: Fixtures.counterpartyKey, allowanceId: Fixtures.walletAllowanceId, amountSats: 10000, @@ -430,6 +584,7 @@ final class PaykitAllowanceTests: XCTestCase { isLive: false ), PaykitAllowanceCapacity.Attempt( + attemptId: "paid", counterparty: Fixtures.counterpartyKey, allowanceId: Fixtures.walletAllowanceId, amountSats: 10000, @@ -437,6 +592,7 @@ final class PaykitAllowanceTests: XCTestCase { isLive: true ), PaykitAllowanceCapacity.Attempt( + attemptId: "open", counterparty: Fixtures.counterpartyKey, allowanceId: Fixtures.walletAllowanceId, amountSats: 2000, @@ -625,10 +781,16 @@ enum PaykitAllowanceFixtures { counterparty: String = counterpartyKey, sats: UInt64, at timestamp: String, - isLive: Bool = true + isLive: Bool = true, + attemptId: String = UUID().uuidString ) -> PaykitAllowanceCapacity.Attempt { PaykitAllowanceCapacity.Attempt( - counterparty: counterparty, allowanceId: allowanceId, amountSats: sats, admittedAt: utc(timestamp), isLive: isLive + attemptId: attemptId, + counterparty: counterparty, + allowanceId: allowanceId, + amountSats: sats, + admittedAt: utc(timestamp), + isLive: isLive ) } diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index e7fdcb7c2..e78b9ca58 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -405,13 +405,13 @@ final class PaykitPaymentProofServiceTests: XCTestCase { func testSpentElsewhereCancelCutShortAfterItsProofWasRemovedCanFinish() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let month = currentMonth() let recurrence = PaymentRequestRecurrence( - every: 1, unit: "month", startsAt: "2026-10-01T08:00:00.123456789Z", - anchor: "2026-10-01T08:00:00.123456789Z", endsAt: nil + every: 1, unit: "month", startsAt: month.startsAt, anchor: month.startsAt, endsAt: nil ) var record = try paymentRequestRecord(endpoints: [endpoint], state: .activeRecurring, recurrence: recurrence) record.terms?.conversion = .perPeriod - let quotePeriod = BillingPeriod(startsAt: recurrence.startsAt, endsAt: "2026-11-01T08:00:00.123456789Z") + let quotePeriod = BillingPeriod(startsAt: recurrence.startsAt, endsAt: month.endsAt) record.conversionQuotes = [PaymentConversionQuoteRecord( eventId: "original", billingPeriod: quotePeriod, rates: [ConversionRate(asset: "usdt", value: "100000")], validFrom: recurrence.startsAt, @@ -565,13 +565,13 @@ final class PaykitPaymentProofServiceTests: XCTestCase { func testExpiredQuoteEndsAnActiveSubscriptionPeriod() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let month = currentMonth() let recurrence = PaymentRequestRecurrence( - every: 1, unit: "month", startsAt: "2026-10-01T08:00:00.123456789Z", - anchor: "2026-10-01T08:00:00.123456789Z", endsAt: nil + every: 1, unit: "month", startsAt: month.startsAt, anchor: month.startsAt, endsAt: nil ) var record = try paymentRequestRecord(endpoints: [endpoint], state: .activeRecurring, recurrence: recurrence) record.terms?.conversion = .perPeriod - let quotePeriod = BillingPeriod(startsAt: recurrence.startsAt, endsAt: "2026-11-01T08:00:00.123456789Z") + let quotePeriod = BillingPeriod(startsAt: recurrence.startsAt, endsAt: month.endsAt) let quote = { (expiresAt: Date) in PaymentConversionQuoteRecord( eventId: "original", billingPeriod: quotePeriod, rates: [ConversionRate(asset: "usdt", value: "100000")], validFrom: recurrence.startsAt, @@ -610,15 +610,15 @@ final class PaykitPaymentProofServiceTests: XCTestCase { func testRecurringRecoveryKeepsOriginalUnpaidBillingPeriod() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let month = currentMonth() let recurrence = PaymentRequestRecurrence( - every: 1, unit: "month", startsAt: "2026-10-01T08:00:00.123456789Z", - anchor: "2026-10-01T08:00:00.123456789Z", endsAt: nil + every: 1, unit: "month", startsAt: month.startsAt, anchor: month.startsAt, endsAt: nil ) var record = try paymentRequestRecord(endpoints: [endpoint], state: .activeRecurring, recurrence: recurrence) let quoteExpiry = PaykitPreciseInstant(date: Date().addingTimeInterval(3600)) record.terms?.conversion = .perPeriod record.conversionQuotes = [PaymentConversionQuoteRecord( - eventId: "original", billingPeriod: BillingPeriod(startsAt: recurrence.startsAt, endsAt: "2026-11-01T08:00:00.123456789Z"), + eventId: "original", billingPeriod: BillingPeriod(startsAt: recurrence.startsAt, endsAt: month.endsAt), rates: [ConversionRate(asset: "usdt", value: "100000")], validFrom: recurrence.startsAt, expiresAt: quoteExpiry.timestamp, outboundStatus: nil )] @@ -3383,6 +3383,16 @@ final class PaykitPaymentProofServiceTests: XCTestCase { try await attempts.record(.accepted(txid: txid), attemptId: id) } + /// The current UTC month as a billing period, so a test's first period always holds now. + private func currentMonth() -> (startsAt: String, endsAt: String) { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + let start = calendar.dateComponents([.year, .month], from: Date()) + let end = calendar.dateComponents([.year, .month], from: calendar.date(byAdding: .month, value: 1, to: calendar.date(from: start)!)!) + let format = { (month: DateComponents) in String(format: "%04d-%02d-01T00:00:00.123456789Z", month.year!, month.month!) } + return (format(start), format(end)) + } + private func paymentProofService( sdk: PaymentProofSdkMock, store: PaymentProofMemoryStore, diff --git a/changelog.d/next/1175.fixed.md b/changelog.d/next/1175.fixed.md new file mode 100644 index 000000000..e769b5a64 --- /dev/null +++ b/changelog.d/next/1175.fixed.md @@ -0,0 +1 @@ +Automatic allowance payments also check spending, paid requests and ended allowances recorded in the wallet and its backup, and pause with a Resume option when allowance records are older than ones the wallet already used.