From d207cdf4dd1fffa95fcd2ea24763dc9f4ed0cdef Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 14:57:15 +0100 Subject: [PATCH 01/13] fix: harden automatic allowance payments --- .../Models/PaykitAllowanceStateBackup.swift | 38 ++++- Bitkit/Services/PaykitAllowance.swift | 13 +- Bitkit/Services/PaykitAllowanceExecutor.swift | 154 +++++++++++++++++- Bitkit/Services/PaykitAllowanceManager.swift | 3 + .../PaykitAllowanceExecutorTests.swift | 123 +++++++++++++- BitkitTests/PaykitAllowanceTests.swift | 37 ++++- changelog.d/next/1175.fixed.md | 1 + 7 files changed, 354 insertions(+), 15 deletions(-) create mode 100644 changelog.d/next/1175.fixed.md 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/Services/PaykitAllowance.swift b/Bitkit/Services/PaykitAllowance.swift index f67029fdb..d8ca0f6c9 100644 --- a/Bitkit/Services/PaykitAllowance.swift +++ b/Bitkit/Services/PaykitAllowance.swift @@ -302,7 +302,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 +311,18 @@ 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) + let used = [attempts, localAttempts].map { + usedSats(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId, attempts: $0, anchor: anchor, now: now) + }.max() ?? 0 return used + amountSats <= monthlyLimitSats } + static func attempts(from spends: [PaykitAllowanceLocalState.AutomaticSpend]) -> [Attempt] { + spends.map { + Attempt(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) } diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 5e53b02ab..4d364d01b 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -91,6 +91,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? { @@ -142,13 +166,16 @@ 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. + /// 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. func restoreBackup(_ snapshot: PaykitAllowanceStateBackups) { 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 + let restored = try backup.restored() + all[key] = all[key].map(restored.withChecks(from:)) ?? restored } catch { Logger.warn("Skipped an unreadable allowance state in a backup: \(error)", context: "PaykitAllowance") } @@ -364,6 +391,9 @@ 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 eventSubject = PassthroughSubject() nonisolated static var eventPublisher: AnyPublisher { @@ -418,6 +448,30 @@ 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`, before the End is sent; a failed save throws, so the End is not sent. + func rememberEnding(identity: String, allowances: [PaykitAllowance]) throws { + try checkedUpdateLocalState(identity: identity) { $0.endedAllowanceIds.formUnion(allowances.map(\.scopedId)) } + } + + /// False when `ledger` is older than one this wallet has read, or missing after one was read; otherwise raises the floor to it. + @discardableResult + private func acceptsLedger(_ ledger: Paykit.AllowanceAccountingState?, identity: String) -> Bool { + let floor = localState(identity: identity).ledgerRevisionFloor + guard let ledger else { return floor == nil } + if let floor, ledger.revision <= floor { + return ledger.revision == floor + } + updateLocalState(identity: identity) { $0.ledgerRevisionFloor = max($0.ledgerRevisionFloor ?? 0, ledger.revision) } + return true + } + func isHandling(_ requestId: PaykitPaymentRequest.ID) -> Bool { inFlightRequestIds.contains(requestId) } @@ -471,10 +525,16 @@ actor PaykitAllowanceExecutor { func recover(identity: String) async { do { // No ledger means nothing was ever admitted, so there is nothing to recover and no reason to create one at launch. - guard try await sdk.allowanceAccountingState() != nil else { return } + guard let current = try await sdk.allowanceAccountingState() else { return } + // A ledger behind this wallet stays as it is until it catches up; recovery would write over it. + guard acceptsLedger(current, identity: identity) else { + Logger.info("Skipped allowance recovery: the ledger is behind this wallet", context: "PaykitAllowance") + return + } // 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) + guard acceptsLedger(state, identity: identity) else { return } // 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) }, @@ -543,8 +603,15 @@ actor PaykitAllowanceExecutor { } guard !covering.isEmpty else { return false } let attempts = await automaticAttempts() + 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 @@ -651,6 +718,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 { @@ -663,6 +736,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 { @@ -739,7 +815,15 @@ actor PaykitAllowanceExecutor { defer { inFlightRequestIds.remove(request.id) } do { - try await ensureReconciled(identity: identity) + var isLedgerCurrent = try await acceptsLedger(sdk.allowanceAccountingState(), identity: identity) + if isLedgerCurrent { + let reconciled = try await ensureReconciled(identity: identity) + isLedgerCurrent = acceptsLedger(reconciled, identity: identity) + } + guard isLedgerCurrent else { + Logger.info("Kept an incoming request manual: the ledger is behind this wallet", context: "PaykitAllowance") + return .manual + } // An unstructured task survives a cancelled caller: stopping after the acceptance would leave the request unpaid. let payment = Task { try await admitAndPay(request, allowances: allowances, identity: identity) } return try await payment.value @@ -760,7 +844,16 @@ actor PaykitAllowanceExecutor { ) 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) }) @@ -777,8 +870,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 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 @@ -847,6 +950,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, @@ -864,6 +983,14 @@ actor PaykitAllowanceExecutor { identity: identity ) + // An End saved while this attempt was admitted stops it before the handoff. + let scopedId = PaykitAllowance.scopedId(counterparty: request.counterparty, allowanceId: prepared.allowanceId ?? candidate.allowanceId) + if localState(identity: identity).endedAllowanceIds.contains(scopedId) { + 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 + } + // 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 @@ -1112,6 +1239,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 } diff --git a/Bitkit/Services/PaykitAllowanceManager.swift b/Bitkit/Services/PaykitAllowanceManager.swift index 3f28e8976..6138123c9 100644 --- a/Bitkit/Services/PaykitAllowanceManager.swift +++ b/Bitkit/Services/PaykitAllowanceManager.swift @@ -167,6 +167,7 @@ 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") } @@ -258,6 +259,8 @@ final class PaykitAllowanceManager { func end(_ entry: PaykitAllowanceEntry) async throws { isWorking = true defer { isWorking = false } + guard let identity else { throw PaykitAllowanceError.unavailable } + try await executor.rememberEnding(identity: identity, allowances: entry.allowances.filter(\.canEnd)) var endedAny = false for allowance in entry.allowances where allowance.canEnd { _ = try await sdk.endAllowance(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId) diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index b4707a6de..77b7441d7 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -276,6 +276,97 @@ 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 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 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 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 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 testRequestAbovePerPaymentLimitNotifiesOnceWhenTheSdkBlocksIt() async throws { let harness = AllowanceHarness() await harness.sdk.setCandidates([AllowanceHarness.candidate(blocked: .sharedRule(code: "per_payment_amount_exceeded"))]) @@ -292,9 +383,22 @@ final class PaykitAllowanceExecutorTests: XCTestCase { XCTAssertEqual(limitEvents.count, 1) } - func testPaymentIsNotSentWhenTheSendingStageCannotBeSaved() async throws { + func testAnUnsavedSpendStopsTheAttemptBeforeAnythingIsConsumed() async throws { let harness = AllowanceHarness() 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) @@ -1873,6 +1977,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 { @@ -1881,7 +1986,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 { @@ -1896,6 +2001,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 } } @@ -2219,6 +2329,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? @@ -2254,6 +2365,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 } @@ -2361,6 +2477,9 @@ private actor AllowanceSdkMock: PaykitAllowanceSdkHandling { func allowanceAccountingState() async throws -> Paykit.AllowanceAccountingState? { log.append("allowanceAccountingState") + if !queuedAccountingStates.isEmpty { + accountingState = queuedAccountingStates.removeFirst() + } return accountingState } diff --git a/BitkitTests/PaykitAllowanceTests.swift b/BitkitTests/PaykitAllowanceTests.swift index e63f1ffbc..a88433ae1 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,27 @@ final class PaykitAllowanceTests: XCTestCase { XCTAssertTrue(json["lastTrustedTime"] is NSNull) } + 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(#""" { diff --git a/changelog.d/next/1175.fixed.md b/changelog.d/next/1175.fixed.md new file mode 100644 index 000000000..27215995b --- /dev/null +++ b/changelog.d/next/1175.fixed.md @@ -0,0 +1 @@ +Automatic allowance payments also check spending and ended allowances recorded in the wallet and its backup. From 91d69ef1f04fa6afa2f4a853122d76af3a2e336e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 15:07:37 +0100 Subject: [PATCH 02/13] fix: drop failed spends the journal no longer holds --- Bitkit/Services/PaykitAllowanceExecutor.swift | 9 +++++++++ .../PaykitAllowanceExecutorTests.swift | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 4d364d01b..134ab2bfe 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -578,6 +578,10 @@ actor PaykitAllowanceExecutor { { await releaseConsumedPaymentList(of: entry, identity: identity) } + // The journal is trimmed, but a failed attempt's spend must not keep counting. + if outcome == .failed, journalStages[attempt.attemptId] == nil { + forgetSpend(attemptId: attempt.attemptId, identity: identity) + } } } } @@ -1239,6 +1243,11 @@ actor PaykitAllowanceExecutor { private struct JournalEntryMissing: Error {} + private func forgetSpend(attemptId: String, identity: String) { + guard localState(identity: identity).automaticSpends.contains(where: { $0.attemptId == attemptId }) else { return } + updateLocalState(identity: identity) { $0.automaticSpends.removeAll { $0.attemptId == attemptId } } + } + /// 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) diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 77b7441d7..4ec3acf35 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -356,6 +356,26 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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 testAnAllowanceSeenEndedNeverPaysAutomaticallyAgain() async throws { let harness = AllowanceHarness() await harness.executor.rememberEndedAllowances(identity: Fixtures.identityKey, allowances: [Fixtures.allowance(state: .ended)]) From 0e18333a3245d8078bd4b758067a95dc5394d513 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 15:28:17 +0100 Subject: [PATCH 03/13] fix: check the ledger before any reconcile write --- Bitkit/Services/PaykitAllowanceExecutor.swift | 52 +++++++------------ Bitkit/Services/PaykitAllowanceManager.swift | 3 +- .../PaykitAllowanceExecutorTests.swift | 13 +++++ 3 files changed, 33 insertions(+), 35 deletions(-) diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 134ab2bfe..90d5d6a70 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -461,14 +461,14 @@ actor PaykitAllowanceExecutor { } /// False when `ledger` is older than one this wallet has read, or missing after one was read; otherwise raises the floor to it. - @discardableResult - private func acceptsLedger(_ ledger: Paykit.AllowanceAccountingState?, identity: String) -> Bool { - let floor = localState(identity: identity).ledgerRevisionFloor + /// 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 } - updateLocalState(identity: identity) { $0.ledgerRevisionFloor = max($0.ledgerRevisionFloor ?? 0, ledger.revision) } + try checkedUpdateLocalState(identity: identity) { $0.ledgerRevisionFloor = max($0.ledgerRevisionFloor ?? 0, ledger.revision) } return true } @@ -492,10 +492,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 } @@ -517,6 +519,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 } @@ -525,16 +528,15 @@ actor PaykitAllowanceExecutor { func recover(identity: String) async { do { // No ledger means nothing was ever admitted, so there is nothing to recover and no reason to create one at launch. - guard let current = try await sdk.allowanceAccountingState() else { return } - // A ledger behind this wallet stays as it is until it catches up; recovery would write over it. - guard acceptsLedger(current, identity: identity) else { - Logger.info("Skipped allowance recovery: the ledger is behind this wallet", context: "PaykitAllowance") - return - } + guard try await sdk.allowanceAccountingState() != nil else { return } // 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) - guard acceptsLedger(state, identity: identity) else { return } + // 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) }, @@ -578,10 +580,6 @@ actor PaykitAllowanceExecutor { { await releaseConsumedPaymentList(of: entry, identity: identity) } - // The journal is trimmed, but a failed attempt's spend must not keep counting. - if outcome == .failed, journalStages[attempt.attemptId] == nil { - forgetSpend(attemptId: attempt.attemptId, identity: identity) - } } } } @@ -819,15 +817,7 @@ actor PaykitAllowanceExecutor { defer { inFlightRequestIds.remove(request.id) } do { - var isLedgerCurrent = try await acceptsLedger(sdk.allowanceAccountingState(), identity: identity) - if isLedgerCurrent { - let reconciled = try await ensureReconciled(identity: identity) - isLedgerCurrent = acceptsLedger(reconciled, identity: identity) - } - guard isLedgerCurrent else { - Logger.info("Kept an incoming request manual: the ledger is behind this wallet", context: "PaykitAllowance") - return .manual - } + try await ensureReconciled(identity: identity) // An unstructured task survives a cancelled caller: stopping after the acceptance would leave the request unpaid. let payment = Task { try await admitAndPay(request, allowances: allowances, identity: identity) } return try await payment.value @@ -875,7 +865,7 @@ actor PaykitAllowanceExecutor { } let ledger = try await sdk.allowanceAccountingState() - guard acceptsLedger(ledger, identity: identity) else { + guard try acceptsLedger(ledger, identity: identity) else { Logger.info("Kept an incoming request manual: the ledger is behind this wallet", context: "PaykitAllowance") return .manual } @@ -987,6 +977,8 @@ actor PaykitAllowanceExecutor { identity: identity ) + // 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) // An End saved while this attempt was admitted stops it before the handoff. let scopedId = PaykitAllowance.scopedId(counterparty: request.counterparty, allowanceId: prepared.allowanceId ?? candidate.allowanceId) if localState(identity: identity).endedAllowanceIds.contains(scopedId) { @@ -994,9 +986,6 @@ actor PaykitAllowanceExecutor { try await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) return .manual } - - // 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( @@ -1243,11 +1232,6 @@ actor PaykitAllowanceExecutor { private struct JournalEntryMissing: Error {} - private func forgetSpend(attemptId: String, identity: String) { - guard localState(identity: identity).automaticSpends.contains(where: { $0.attemptId == attemptId }) else { return } - updateLocalState(identity: identity) { $0.automaticSpends.removeAll { $0.attemptId == attemptId } } - } - /// 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) diff --git a/Bitkit/Services/PaykitAllowanceManager.swift b/Bitkit/Services/PaykitAllowanceManager.swift index 6138123c9..70463f13b 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") } } } diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 4ec3acf35..5cd17bd36 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -314,6 +314,18 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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 testAnAutomaticPaymentRaisesTheLedgerFloor() async throws { let harness = AllowanceHarness() await harness.sdk.setAccountingState(Fixtures.accountingState(revision: 7)) @@ -405,6 +417,7 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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) From e503eb7fda31f7b713bae1e40ef6599f4ee466df Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 15:37:12 +0100 Subject: [PATCH 04/13] fix: hand back a request while the ledger is behind --- Bitkit/Services/PaykitAllowanceExecutor.swift | 15 +++++++++------ BitkitTests/PaykitAllowanceExecutorTests.swift | 13 +++++++++++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 90d5d6a70..4baaf9437 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -604,7 +604,15 @@ 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( @@ -757,11 +765,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 diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 5cd17bd36..b2599f88d 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -326,6 +326,19 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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)) From 9190ac17f5b7e0c2b69512189a02a87ad2ecb7ff Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 16:21:23 +0100 Subject: [PATCH 05/13] test: recovery leaves a stale ledger unwritten --- BitkitTests/PaykitAllowanceExecutorTests.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index b2599f88d..982f1e858 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -302,6 +302,18 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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) From d9265ab4a3628c6cc677bb5de7f8e9e496bb8af5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 16:31:31 +0100 Subject: [PATCH 06/13] test: manual payments skip a stale ledger --- BitkitTests/PaykitAllowanceExecutorTests.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 982f1e858..611313b30 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -1164,6 +1164,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) From 9dbb10a723ccb8779b0e30ec98217a3b611a54f3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 17:09:36 +0100 Subject: [PATCH 07/13] fix: keep allowance state saved by earlier builds --- Bitkit/Services/PaykitAllowanceExecutor.swift | 16 +++++++++ BitkitTests/PaykitAllowanceTests.swift | 35 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 4baaf9437..e35044ead 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -122,6 +122,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 diff --git a/BitkitTests/PaykitAllowanceTests.swift b/BitkitTests/PaykitAllowanceTests.swift index a88433ae1..1baa0fc22 100644 --- a/BitkitTests/PaykitAllowanceTests.swift +++ b/BitkitTests/PaykitAllowanceTests.swift @@ -104,6 +104,41 @@ final class PaykitAllowanceTests: XCTestCase { XCTAssertTrue(json["lastTrustedTime"] is NSNull) } + func testStateSavedBeforeTheAutomaticPaymentChecksStillDecodes() throws { + var current = try JSONSerialization.jsonObject(with: JSONEncoder().encode(PaykitAllowanceLocalState( + journal: [], + presentedProposalIds: ["presented"], + notifiedRequestIds: ["notified"] + ))) 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) + + XCTAssertEqual(state.presentedProposalIds, ["presented"]) + XCTAssertEqual(state.notifiedRequestIds, ["notified"]) + XCTAssertNil(state.ledgerRevisionFloor) + XCTAssertTrue(state.automaticSpends.isEmpty) + XCTAssertTrue(state.endedAllowanceIds.isEmpty) + } + + 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 testRestoreNeverLowersTheAutomaticPaymentChecksAlreadyStored() { let spend = PaykitAllowanceLocalState.AutomaticSpend( attemptId: "attempt-1", counterparty: "contact", allowanceId: "allowance-1", amountSats: 1000, admittedAt: Fixtures.now From f63b0693849115706cca50e895550379214e4290 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 19:51:43 +0100 Subject: [PATCH 08/13] test: reload allowance state saved by earlier builds --- BitkitTests/PaykitAllowanceTests.swift | 38 ++++++++++++++++++++------ 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/BitkitTests/PaykitAllowanceTests.swift b/BitkitTests/PaykitAllowanceTests.swift index 1baa0fc22..05b76fb2b 100644 --- a/BitkitTests/PaykitAllowanceTests.swift +++ b/BitkitTests/PaykitAllowanceTests.swift @@ -105,23 +105,43 @@ final class PaykitAllowanceTests: XCTestCase { } func testStateSavedBeforeTheAutomaticPaymentChecksStillDecodes() throws { - var current = try JSONSerialization.jsonObject(with: JSONEncoder().encode(PaykitAllowanceLocalState( - journal: [], + 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"], - notifiedRequestIds: ["notified"] - ))) as? [String: Any] ?? [:] + 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.presentedProposalIds, ["presented"]) - XCTAssertEqual(state.notifiedRequestIds, ["notified"]) - XCTAssertNil(state.ledgerRevisionFloor) - XCTAssertTrue(state.automaticSpends.isEmpty) - XCTAssertTrue(state.endedAllowanceIds.isEmpty) + XCTAssertEqual(state, earlier) + XCTAssertEqual(reloaded, earlier) } func testABackupWrittenBeforeTheAutomaticPaymentChecksStillRestores() throws { From c671bd5be528637902824c134d7d5cbb2a797f3d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 30 Oct 2026 23:11:24 +0100 Subject: [PATCH 09/13] fix: resume auto-pay after a restore without paykit state --- Bitkit/Services/BackupService.swift | 6 +++++- Bitkit/Services/PaykitAllowanceExecutor.swift | 9 ++++++--- .../Services/PaykitPaymentProofService.swift | 8 ++++++-- BitkitTests/PaykitAllowanceTests.swift | 20 +++++++++++++++++++ 4 files changed, 37 insertions(+), 6 deletions(-) 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/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index e35044ead..151ff5355 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -184,13 +184,16 @@ struct PaykitAllowanceKeychainStore: PaykitAllowanceStoring { /// 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. - func restoreBackup(_ snapshot: PaykitAllowanceStateBackups) { + /// 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 { let key = PubkyPublicKeyFormat.normalized(identity) ?? identity - let restored = try backup.restored() + 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") 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/BitkitTests/PaykitAllowanceTests.swift b/BitkitTests/PaykitAllowanceTests.swift index 05b76fb2b..77541fcb7 100644 --- a/BitkitTests/PaykitAllowanceTests.swift +++ b/BitkitTests/PaykitAllowanceTests.swift @@ -159,6 +159,26 @@ final class PaykitAllowanceTests: XCTestCase { 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 From 314adde65f0a6875cb64c21ca974a57d464cfea7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 31 Oct 2026 21:27:36 +0100 Subject: [PATCH 10/13] fix: count local allowance payments and resume paused ones --- .../Localization/ar.lproj/Localizable.strings | 3 + .../Localization/ca.lproj/Localizable.strings | 3 + .../Localization/cs.lproj/Localizable.strings | 3 + .../Localization/de.lproj/Localizable.strings | 3 + .../Localization/el.lproj/Localizable.strings | 3 + .../Localization/en.lproj/Localizable.strings | 3 + .../es-419.lproj/Localizable.strings | 3 + .../Localization/es.lproj/Localizable.strings | 3 + .../Localization/fr.lproj/Localizable.strings | 3 + .../Localization/it.lproj/Localizable.strings | 3 + .../Localization/nl.lproj/Localizable.strings | 3 + .../Localization/pl.lproj/Localizable.strings | 3 + .../pt-BR.lproj/Localizable.strings | 3 + .../Localization/pt.lproj/Localizable.strings | 3 + .../Localization/ru.lproj/Localizable.strings | 3 + Bitkit/Services/PaykitAllowance.swift | 18 ++- Bitkit/Services/PaykitAllowanceExecutor.swift | 35 +++++- Bitkit/Services/PaykitAllowanceManager.swift | 15 +++ .../Views/Subscriptions/AllowancesView.swift | 32 ++++++ .../PaykitAllowanceExecutorTests.swift | 107 ++++++++++++++++++ BitkitTests/PaykitAllowanceTests.swift | 56 ++++++++- changelog.d/next/1175.fixed.md | 2 +- 22 files changed, 300 insertions(+), 10 deletions(-) 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/PaykitAllowance.swift b/Bitkit/Services/PaykitAllowance.swift index d8ca0f6c9..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 @@ -311,15 +312,23 @@ enum PaykitAllowanceCapacity { guard allowance.perPaymentMaxSats != nil, let monthlyLimitSats = allowance.monthlyLimitSats, let anchor = allowance.monthlyAnchor else { return false } - let used = [attempts, localAttempts].map { - usedSats(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId, attempts: $0, anchor: anchor, now: now) - }.max() ?? 0 + // 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(counterparty: $0.counterparty, allowanceId: $0.allowanceId, amountSats: $0.amountSats, admittedAt: $0.admittedAt, isLive: true) + Attempt( + attemptId: $0.attemptId, + counterparty: $0.counterparty, + allowanceId: $0.allowanceId, + amountSats: $0.amountSats, + admittedAt: $0.admittedAt, + isLive: true + ) } } @@ -333,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 62f80ab82..df8b5f227 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -214,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 } } } @@ -415,6 +416,7 @@ actor 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() @@ -515,6 +517,24 @@ actor PaykitAllowanceExecutor { 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) } @@ -595,7 +615,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? @@ -880,6 +902,13 @@ 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 diff --git a/Bitkit/Services/PaykitAllowanceManager.swift b/Bitkit/Services/PaykitAllowanceManager.swift index 9d8ab95e0..9de83ce33 100644 --- a/Bitkit/Services/PaykitAllowanceManager.swift +++ b/Bitkit/Services/PaykitAllowanceManager.swift @@ -60,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] = [:] @@ -170,6 +172,7 @@ final class PaykitAllowanceManager { localState = PaykitAllowanceLocalState() autoPaidRequestIds = [] autoPaidSatsByScopedId = [:] + isAutomaticPaymentPaused = false manualRequestIds = [:] announcedOfferIds = [] } @@ -192,8 +195,10 @@ final class PaykitAllowanceManager { 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 @@ -278,6 +283,16 @@ 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 } diff --git a/Bitkit/Views/Subscriptions/AllowancesView.swift b/Bitkit/Views/Subscriptions/AllowancesView.swift index 666bdc4a5..77271f8af 100644 --- a/Bitkit/Views/Subscriptions/AllowancesView.swift +++ b/Bitkit/Views/Subscriptions/AllowancesView.swift @@ -5,6 +5,7 @@ import SwiftUI struct AllowancesTab: View { @Environment(PaykitAllowanceManager.self) private var allowances @EnvironmentObject private var sheets: SheetViewModel + @EnvironmentObject private var app: AppViewModel var body: some View { Group { @@ -22,6 +23,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 +43,34 @@ 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 + ) { + 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 d3dae07fc..073a37a53 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -357,6 +357,40 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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) @@ -480,6 +514,79 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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)]) diff --git a/BitkitTests/PaykitAllowanceTests.swift b/BitkitTests/PaykitAllowanceTests.swift index 77541fcb7..4ad7e4559 100644 --- a/BitkitTests/PaykitAllowanceTests.swift +++ b/BitkitTests/PaykitAllowanceTests.swift @@ -375,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, @@ -512,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: [], @@ -533,6 +576,7 @@ final class PaykitAllowanceTests: XCTestCase { XCTAssertEqual(attempts, [ PaykitAllowanceCapacity.Attempt( + attemptId: "failed", counterparty: Fixtures.counterpartyKey, allowanceId: Fixtures.walletAllowanceId, amountSats: 10000, @@ -540,6 +584,7 @@ final class PaykitAllowanceTests: XCTestCase { isLive: false ), PaykitAllowanceCapacity.Attempt( + attemptId: "paid", counterparty: Fixtures.counterpartyKey, allowanceId: Fixtures.walletAllowanceId, amountSats: 10000, @@ -547,6 +592,7 @@ final class PaykitAllowanceTests: XCTestCase { isLive: true ), PaykitAllowanceCapacity.Attempt( + attemptId: "open", counterparty: Fixtures.counterpartyKey, allowanceId: Fixtures.walletAllowanceId, amountSats: 2000, @@ -735,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/changelog.d/next/1175.fixed.md b/changelog.d/next/1175.fixed.md index 27215995b..e769b5a64 100644 --- a/changelog.d/next/1175.fixed.md +++ b/changelog.d/next/1175.fixed.md @@ -1 +1 @@ -Automatic allowance payments also check spending and ended allowances recorded in the wallet and its backup. +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. From 93dbf6664f2ca9f0ed78b87df8ede1552c2e6d21 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sun, 1 Nov 2026 10:20:06 +0100 Subject: [PATCH 11/13] fix: ask for the pin before resuming automatic payments --- Bitkit/Views/Subscriptions/AllowancesView.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Bitkit/Views/Subscriptions/AllowancesView.swift b/Bitkit/Views/Subscriptions/AllowancesView.swift index 77271f8af..10e67444d 100644 --- a/Bitkit/Views/Subscriptions/AllowancesView.swift +++ b/Bitkit/Views/Subscriptions/AllowancesView.swift @@ -6,6 +6,8 @@ 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 { @@ -15,6 +17,7 @@ struct AllowancesTab: View { list } } + .paymentAuthorization(authorization) .task { await allowances.refresh() } @@ -54,6 +57,8 @@ struct AllowancesTab: View { 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 { From c8830f12b715085f312d65d8d8e6c5e635c70492 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sun, 1 Nov 2026 11:39:42 +0100 Subject: [PATCH 12/13] test: keep proof billing periods in the current month --- .../PaykitPaymentProofServiceTests.swift | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) 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, From 7d699c76da0e87e1f04835015c1f744611c1c25c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sun, 1 Nov 2026 23:32:14 +0100 Subject: [PATCH 13/13] fix: an end saved during a payment handoff waits for it --- Bitkit/Services/PaykitAllowanceExecutor.swift | 64 ++++++++++++++----- Bitkit/Services/PaykitAllowanceManager.swift | 15 +++-- .../PaykitAllowanceExecutorTests.swift | 38 +++++++++++ 3 files changed, 95 insertions(+), 22 deletions(-) diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index df8b5f227..39087cb41 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -429,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? @@ -500,9 +502,13 @@ actor PaykitAllowanceExecutor { updateLocalState(identity: identity) { $0.endedAllowanceIds.formUnion(ended) } } - /// Like `rememberEndedAllowances`, before the End is sent; a failed save throws, so the End is not sent. - func rememberEnding(identity: String, allowances: [PaykitAllowance]) throws { - try checkedUpdateLocalState(identity: identity) { $0.endedAllowanceIds.formUnion(allowances.map(\.scopedId)) } + /// 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. @@ -1065,24 +1071,28 @@ 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) - // An End saved while this attempt was admitted stops it before the handoff. + // 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) - if localState(identity: identity).endedAllowanceIds.contains(scopedId) { + 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 } - 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 - } guard case let .ready(submitted) = handoff else { try await record(attemptId: prepared.attemptId, outcome: .failed, identity: identity) return .manual @@ -1371,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 9de83ce33..f983011ee 100644 --- a/Bitkit/Services/PaykitAllowanceManager.swift +++ b/Bitkit/Services/PaykitAllowanceManager.swift @@ -297,14 +297,17 @@ final class PaykitAllowanceManager { isWorking = true defer { isWorking = false } guard let identity else { throw PaykitAllowanceError.unavailable } - try await executor.rememberEnding(identity: identity, allowances: entry.allowances.filter(\.canEnd)) - var endedAny = false - for allowance in entry.allowances where allowance.canEnd { - _ = try await sdk.endAllowance(counterparty: allowance.counterparty, allowanceId: allowance.allowanceId) - endedAny = true + 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/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 073a37a53..47e0e65fe 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -598,6 +598,32 @@ final class PaykitAllowanceExecutorTests: XCTestCase { 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"))]) @@ -2914,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 }