taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit a3eba277d80712f98fb5c080b4721bda973fdfaa
parent bda042bcaa05eecbca8fcc9f3636420bd2c02108
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 18:49:31 +0100

wallet-core: reprice payment change at the withdrawal cutoff

A denomination stops being usable for refresh five minutes before it
expires. Keep the next eligibility change with the cached refresh cost
so an open payment review can update its estimate at that cutoff.

Issue: https://bugs.taler.net/n/11794

Diffstat:
Mdoc/wallet-observations.md | 22++++++++++------------
Mpackages/taler-wallet-core/src/denominations.ts | 15++++++++++++++-
Mpackages/taler-wallet-core/src/exchanges.ts | 10+++++++++-
Mpackages/taler-wallet-core/src/observation-deadlines.ts | 9++++++---
Mpackages/taler-wallet-core/src/observe-transaction.test.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mpackages/taler-wallet-core/src/observe-transaction.ts | 2++
Mpackages/taler-wallet-core/src/pay-merchant.ts | 4++++
Mpackages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts | 7++++++-
Mpackages/taler-wallet-core/src/refresh.test.ts | 7++++++-
Mpackages/taler-wallet-core/src/refresh.ts | 18++++++++++++++----
Mpackages/taler-wallet-core/src/wallet.ts | 2+-
11 files changed, 132 insertions(+), 26 deletions(-)

diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md @@ -119,18 +119,16 @@ are request errors. Retry uses a fresh observation ID. Register before reading the initial snapshot. Assemble transaction, choices, exchange and prerequisite data in one database transaction, without network -requests or persistent writes. Committed writes to all snapshot inputs invalidate -observations; rolled-back writes do not. Reads are serialized per observation; -a change during a read schedules another read. Unchanged snapshots are suppressed. - -Invalidation includes all transaction records and their withdrawal/refresh/recovery -dependencies, coin availability/history, tokens/slates, retries, reserves, exchange -and currency data, contract terms, configuration, and settled amount inputs. -It does not rely on public state-transition notifications. Snapshot readers -register purse and payment expiry explicitly. Payment choice reads additionally -track typed denomination, token and exchange-fee records for validity boundaries. -`ObservationDeadlines` selects the next future boundary; there is no recursive -field-name scan, and these deadlines do not enter the wire payload. +requests or persistent writes. Each observation reads committed state and runs +one read at a time. A change during a read schedules another read. The registry +publishes a revision only when the snapshot changes. + +Transaction, exchange, balance and Donau change notifications invalidate +transaction views. Token writes also invalidate them after commit. Snapshot +readers track purse and payment expiry, token and fee validity, and the effective +withdrawal cutoff for denominations used to give change. A cached refresh cost +retains its next eligibility boundary so a second view can schedule the same +update. Bank preparation initializes cached bank presentation. Existing withdrawal tasks update it from both status reads and reserve-registration responses; observations diff --git a/packages/taler-wallet-core/src/denominations.ts b/packages/taler-wallet-core/src/denominations.ts @@ -388,6 +388,7 @@ export function isCandidateWithdrawableDenomRec( d: WalletDenomination, now = AbsoluteTime.now(), marginMs = 300_000, + onEligibilityChange?: (deadline: number) => void, ): boolean { const start = AbsoluteTime.fromProtocolTimestamp( timestampProtocolFromDb(d.stampStart), @@ -410,9 +411,21 @@ export function isCandidateWithdrawableDenomRec( withdrawExpire, Duration.fromMilliseconds(marginMs), ); + if (d.isRevoked || !d.isOffered || d.isLost) return false; + if ( + onEligibilityChange && + AbsoluteTime.cmp(start, lastPossibleWithdraw) < 0 + ) { + const boundary = started ? lastPossibleWithdraw : start; + if ( + typeof boundary.t_ms === "number" && + AbsoluteTime.cmp(now, boundary) < 0 + ) + onEligibilityChange(boundary.t_ms); + } const remaining = Duration.getRemaining(lastPossibleWithdraw, now); const stillOkay = remaining.d_ms !== 0; - return started && stillOkay && !d.isRevoked && d.isOffered && !d.isLost; + return started && stillOkay; } export async function isValidDenomRecord( diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -1562,6 +1562,7 @@ async function checkExchangeEntryOutdated( tx: WalletDbTransaction, exchangeBaseUrl: string, exchangeMasterPub: string | undefined, + onEligibilityChange?: (deadline: number) => void, ): Promise<boolean> { // We currently consider the exchange outdated when no // denominations can be used for withdrawal. @@ -1576,7 +1577,12 @@ async function checkExchangeEntryOutdated( : await getAllDenominationsForExchange(tx, exchangeBaseUrl); logger.trace(`exchange entry has ${denoms.length} denominations`); for (const denom of denoms) { - const denomOkay = isCandidateWithdrawableDenomRec(denom); + const denomOkay = isCandidateWithdrawableDenomRec( + denom, + undefined, + undefined, + onEligibilityChange, + ); if (denomOkay) { numOkay++; } @@ -1895,6 +1901,7 @@ export async function requireExchangeReadyTx( wex: WalletExecutionContext, tx: WalletDbTransaction, exchangeBaseUrl: string, + onEligibilityChange?: (deadline: number) => void, ): Promise<void> { const exchange = await tx.getExchange(exchangeBaseUrl); if (!exchange) { @@ -1906,6 +1913,7 @@ export async function requireExchangeReadyTx( tx, exchangeBaseUrl, exchange.detailsPointer?.masterPublicKey, + onEligibilityChange, ); if (isOutdated) { logger.warn(`exchange ${exchangeBaseUrl} outdated`); diff --git a/packages/taler-wallet-core/src/observation-deadlines.ts b/packages/taler-wallet-core/src/observation-deadlines.ts @@ -19,11 +19,14 @@ export class ObservationDeadlines { nextRefreshAt: number | undefined; addProtocolTimestamp(timestamp: TalerProtocolTimestamp | undefined): void { - if (typeof timestamp?.t_s !== "number" || typeof this.now !== "number") - return; + if (typeof timestamp?.t_s !== "number") return; // Refresh just after the boundary, including checks with inclusive endpoints. - const deadline = timestamp.t_s * 1000 + 1; + this.addDeadline(timestamp.t_s * 1000 + 1); + } + + addDeadline(deadline: number): void { if ( + typeof this.now === "number" && deadline > this.now && (this.nextRefreshAt === undefined || deadline < this.nextRefreshAt) ) diff --git a/packages/taler-wallet-core/src/observe-transaction.test.ts b/packages/taler-wallet-core/src/observe-transaction.test.ts @@ -72,6 +72,7 @@ import { stopObservation, readTransactionSnapshot, } from "./observe-transaction.js"; +import { ObservationDeadlines } from "./observation-deadlines.js"; import { PeerPushCreditTransactionContext } from "./pay-peer-push-credit.js"; import { dispatchRequestInternal } from "./requests.js"; import { handleSetDonau } from "./donau.js"; @@ -1116,7 +1117,7 @@ for (const makeRunner of runnerFactories) { for (const makeRunner of runnerFactories) { test( `${makeRunner.name}: generic snapshots cover every transaction type without writes or network`, - { timeout: 15000 }, + { timeout: 20000 }, async () => { const f = await fixture(makeRunner); try { @@ -1404,7 +1405,7 @@ for (const makeRunner of runnerFactories) { const ct = await tx.getContractTerms(master); assert.ok(ct); ct.contractTermsRaw.pay_deadline = { t_s: now + 300 }; - ct.contractTermsRaw.amount = "TESTKUDOS:5"; + ct.contractTermsRaw.amount = "TESTKUDOS:4"; ct.contractTermsRaw.exchanges = [ { url: exchangeUrl, master_pub: master, priority: 0 }, ]; @@ -1443,6 +1444,7 @@ for (const makeRunner of runnerFactories) { unpaid.payment?.choices[0].status, U.ChoiceSelectionDetailType.InsufficientBalance, ); + const changeCutoff = Math.floor(Date.now() / 1000) + 3; nextPayment = f.nextSnapshot("txn:payment:payment"); await f.wex.runWalletDbTx(async (tx) => { await tx.upsertDenomination({ @@ -1472,6 +1474,28 @@ for (const makeRunner of runnerFactories) { masterSig: master, verificationStatus: R.DenominationVerificationStatus.VerifiedGood, }); + const coinDenom = await tx.getDenomination({ + exchangeMasterPub: master, + denomPubHash: master, + }); + assert.ok(coinDenom); + const family = await tx.upsertDenominationFamily({ + familyParams: { + exchangeBaseUrl: exchangeUrl, + exchangeMasterPub: master, + value: "TESTKUDOS:1", + ...coinDenom.fees, + }, + }); + await tx.upsertDenomination({ + ...coinDenom, + denomPubHash: oldMaster, + denominationFamilySerial: family, + value: "TESTKUDOS:1", + stampExpireWithdraw: R.timestampProtocolToDb({ + t_s: changeCutoff + 300, + }), + }); await tx.upsertCoin({ coinPub: master, coinPriv: master, @@ -1517,6 +1541,40 @@ for (const makeRunner of runnerFactories) { U.ChoiceSelectionDetailType.PaymentPossible, JSON.stringify(affordable.payment), ); + // A second view gets the cached change cost. It must wake at the + // five-minute withdrawal margin even without another database write. + const warmDeadlines = new ObservationDeadlines(); + const id = affordable.transaction.transactionId; + const warm = await f.wex.runWalletDbTx((tx) => + readTransactionSnapshot(f.wex, tx, id, warmDeadlines), + ); + assert.ok(warm?.type === TransactionType.Payment); + const choice = warm.payment?.choices[0]; + assert.ok( + choice?.status === U.ChoiceSelectionDetailType.PaymentPossible, + ); + assert.equal(choice.amountEffective, "TESTKUDOS:4"); + assert.equal(warmDeadlines.nextRefreshAt, changeCutoff * 1000); + const repriced = f.nextSnapshot("warm-change", 2); + await observeTransaction(f.wex, { + transactionId: id, + observationId: "warm-change", + }); + // Core deadline timers are unreferenced in Node. + await new Promise((resolve) => + setTimeout( + resolve, + Math.max(0, changeCutoff * 1000 - Date.now()) + 50, + ), + ); + const updated: GenericTransactionSnapshotNotification = await repriced; + assert.ok(updated.snapshot?.type === TransactionType.Payment); + const newChoice = updated.snapshot.payment?.choices[0]; + assert.ok( + newChoice?.status === U.ChoiceSelectionDetailType.PaymentPossible, + ); + assert.equal(newChoice.amountEffective, "TESTKUDOS:5"); + await stopObservation(f.wex, { observationId: "warm-change" }); // Validity changes must refresh choices even when the task loop is idle. const depositExpiry = Math.floor(Date.now() / 1000) + 2; await f.wex.runWalletDbTx(async (tx) => { diff --git a/packages/taler-wallet-core/src/observe-transaction.ts b/packages/taler-wallet-core/src/observe-transaction.ts @@ -350,6 +350,8 @@ async function readPaymentSnapshot( wex, trackPaymentChoiceDeadlines(tx, deadlines), transaction.transactionId, + undefined, + (deadline) => deadlines.addDeadline(deadline), ) : undefined; const reasons: TransactionConfirmationUnavailableReason[] = []; diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -1080,6 +1080,7 @@ export async function getTotalPaymentCostInTx( tx: WalletDbTransaction, currency: string, pcs: SelectedProspectiveCoin[], + onEligibilityChange?: (deadline: number) => void, ): Promise<AmountJson> { const costs: AmountJson[] = []; const loadedDenoms = await tx.getDenominationsByRefs(pcs); @@ -1102,6 +1103,7 @@ export async function getTotalPaymentCostInTx( refreshedDenom: WalletDenomination.toDenomInfo(denom), amountLeft: Amounts.sub(denom.value, pcs[i].contribution).amount, })), + onEligibilityChange, ); for (let i = 0; i < pcs.length; i++) { costs.push(Amounts.parseOrThrow(pcs[i].contribution)); @@ -3215,6 +3217,7 @@ export async function getChoicesForPaymentInTx( tx: WalletDbTransaction, transactionId: string, forcedCoinSel?: ForcedCoinSel, + onEligibilityChange?: (deadline: number) => void, ): Promise<GetChoicesForPaymentResult> { const parsedTx = parseTransactionIdentifier(transactionId); if (parsedTx?.tag !== TransactionType.Payment) { @@ -3343,6 +3346,7 @@ export async function getChoicesForPaymentInTx( tx, currency, selectCoinsResult.coinSel.coins, + onEligibilityChange, ); selectCoinsResult.coinSel.coins.forEach((x) => { exchanges.add(x.exchangeBaseUrl); diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts @@ -169,7 +169,12 @@ function coinHistoryContext( cancellationToken: CancellationToken.CONTINUE, ws: { longpollQueue: new LongpollQueue(), - refreshCostCache: { get: () => Amounts.zeroOfCurrency("TESTKUDOS") }, + refreshCostCache: { + get: () => ({ + cost: Amounts.zeroOfCurrency("TESTKUDOS"), + validUntil: Infinity, + }), + }, denomInfoCache: { get() { return { diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts @@ -853,7 +853,12 @@ test("a corrected melt keeps the recouped sibling's output at zero", async (t) = cancellationToken: U.CancellationToken.CONTINUE, ws: { denomInfoCache: { get: () => old, getOrPut: async () => old }, - refreshCostCache: { get: () => Amounts.parseOrThrow("TESTKUDOS:1") }, + refreshCostCache: { + get: () => ({ + cost: Amounts.parseOrThrow("TESTKUDOS:1"), + validUntil: Infinity, + }), + }, }, cryptoApi: { signCoinHistoryRequest: async () => ({ sig: "signature" }), diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -438,7 +438,9 @@ export async function getTotalRefreshCosts( refreshedDenom: DenominationInfo; amountLeft: AmountJson; }>, + onEligibilityChange?: (deadline: number) => void, ): Promise<AmountJson[]> { + const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); const results: Array<AmountJson | undefined> = new Array(requests.length); const groups = new Map<string, number[]>(); for (let i = 0; i < requests.length; i++) { @@ -450,8 +452,10 @@ export async function getTotalRefreshCosts( const cached = wex.ws.refreshCostCache.get( refreshCostCacheKey(request.refreshedDenom, request.amountLeft), ); - if (cached) { - results[i] = cached; + if (cached && now < cached.validUntil) { + if (Number.isFinite(cached.validUntil)) + onEligibilityChange?.(cached.validUntil); + results[i] = cached.cost; continue; } const groupKey = `${request.refreshedDenom.exchangeBaseUrl}\0${Amounts.currencyOf( @@ -465,7 +469,13 @@ export async function getTotalRefreshCosts( const first = requests[indices[0]]; const exchangeBaseUrl = first.refreshedDenom.exchangeBaseUrl; const currency = Amounts.currencyOf(first.amountLeft); - await requireExchangeReadyTx(wex, tx, exchangeBaseUrl); + // The readiness check visits every denomination of the accepted key set, + // including alternatives that have not started yet. + let validUntil = Infinity; + await requireExchangeReadyTx(wex, tx, exchangeBaseUrl, (boundary) => { + validUntil = Math.min(validUntil, boundary); + }); + if (Number.isFinite(validUntil)) onEligibilityChange?.(validUntil); const allDenoms = await getWithdrawableDenomsTx( wex, tx, @@ -482,7 +492,7 @@ export async function getTotalRefreshCosts( ); wex.ws.refreshCostCache.put( refreshCostCacheKey(request.refreshedDenom, request.amountLeft), - cost, + { cost, validUntil }, ); results[index] = cost; } diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -1359,7 +1359,7 @@ export class InternalWalletState { */ readonly leftoverClaims = new Set<string>(); - refreshCostCache: Cache<AmountJson> = new Cache( + refreshCostCache: Cache<{ cost: AmountJson; validUntil: number }> = new Cache( 1000, Duration.fromSpec({ minutes: 1 }), );