taler-typescript-core

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

commit 54869f69e15b44a4c52cbff6b8de549915170738
parent 3a4a31f13d1600a6e29e3ffa1820080538e9deb5
Author: Florian Dold <dold@taler.net>
Date:   Thu, 24 Sep 2026 22:28:10 +0200

wallet-core: collect fountain grants and resume pending withdrawals

Journal envelopes before asking the merchant to sign. Recover pending
batches before polling again, and coordinate stocking across fountains
sharing an issue key so retries, quotas and partial grants preserve the
wallet’s token supply.

Diffstat:
Mpackages/taler-util/src/notifications.ts | 8++++++++
Mpackages/taler-wallet-core/src/common.ts | 6++++++
Apackages/taler-wallet-core/src/fountains.ts | 506+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/shepherd.test.ts | 20++++++++++++++++++++
Mpackages/taler-wallet-core/src/shepherd.ts | 14++++++++++++++
Mpackages/wallet-webui/src/api/notifications.ts | 2++
6 files changed, 556 insertions(+), 0 deletions(-)

diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts @@ -48,6 +48,7 @@ export enum NotificationType { ObservationSnapshot = "observation-snapshot", ObservationEnded = "observation-ended", ObservationError = "observation-error", + FountainChanged = "fountain-changed", CoinRecoveryProgress = "coin-recovery-progress", BalanceChange = "balance-change", BankAccountChange = "bank-account-change", @@ -500,6 +501,12 @@ export interface CoinRecoveryProgressNotification { numIssues: number; } +/** Only public local identity; never include the fountain credential. */ +export interface FountainChangedNotification { + type: NotificationType.FountainChanged; + fountainId: string; +} + export type WalletNotification = | { type: NotificationType.DonauConfigChanged } | { type: NotificationType.BalanceRefreshInfoChanged } @@ -507,6 +514,7 @@ export type WalletNotification = | ObservationSnapshotNotification | ObservationEndedNotification | ObservationErrorNotification + | FountainChangedNotification | CoinRecoveryProgressNotification | BalanceChangeNotification | BankAccountChangeNotification diff --git a/packages/taler-wallet-core/src/common.ts b/packages/taler-wallet-core/src/common.ts @@ -686,6 +686,7 @@ export function getAutoRefreshExecuteThreshold(d: { * Pending task types. */ export enum PendingTaskType { + Fountain = "fountain", ExchangeUpdate = "exchange-update", ExchangeAutoRefresh = "exchange-auto-refresh", ExchangeWalletKyc = "exchange-wallet-kyc", @@ -707,6 +708,7 @@ export enum PendingTaskType { * Parsed representation of task identifiers. */ export type ParsedTaskIdentifier = + | { tag: PendingTaskType.Fountain; fountainId: string } | { tag: PendingTaskType.Withdraw; withdrawalGroupId: string; @@ -735,6 +737,8 @@ export function parseTaskIdentifier(x: string): ParsedTaskIdentifier { const [type, ...rest] = task; switch (type) { + case PendingTaskType.Fountain: + return { tag: type, fountainId: rest[0] }; case PendingTaskType.Deposit: return { tag: type, depositGroupId: rest[0] }; case PendingTaskType.ExchangeUpdate: @@ -771,6 +775,8 @@ export function parseTaskIdentifier(x: string): ParsedTaskIdentifier { export function constructTaskIdentifier(p: ParsedTaskIdentifier): TaskIdStr { switch (p.tag) { + case PendingTaskType.Fountain: + return `${p.tag}:${p.fountainId}` as TaskIdStr; case PendingTaskType.Deposit: return `${p.tag}:${p.depositGroupId}` as TaskIdStr; case PendingTaskType.ExchangeUpdate: diff --git a/packages/taler-wallet-core/src/fountains.ts b/packages/taler-wallet-core/src/fountains.ts @@ -0,0 +1,506 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import { + AbsoluteTime, + CancellationToken, + DenomKeyType, + encodeCrock, + FountainInfoResponse, + FountainWalletGrant, + getRandomBytes, + hashTokenIssuePub, + MerchantContractTokenKind, + NotificationType, + OperationFail, + TalerError, + TalerErrorCode, + TalerMerchantInstanceHttpClient, + TalerProtocolTimestamp, +} from "@gnu-taler/taler-util"; +import { getHttpResponseErrorDetails } from "@gnu-taler/taler-util/http"; +import { TaskRunResult } from "./common.js"; +import { + timestampProtocolToDb, + WalletFountain, + WalletSlate, + WalletToken, +} from "./db/records.js"; +import { validateToken } from "./tokens.js"; +import { walletMerchantClient, WalletExecutionContext } from "./wallet.js"; + +const NEVER = Number.MAX_SAFE_INTEGER; +// Only errors created here are safe to expose without remote request details. +const safeErrors = new WeakSet<TalerError>(); +const now = () => AbsoluteTime.toStampMs(AbsoluteTime.now()); +const millis = (t: TalerProtocolTimestamp) => + t.t_s === "never" ? NEVER : t.t_s * 1000; +const stamp = (t: number): TalerProtocolTimestamp => ({ + t_s: t === NEVER ? "never" : Math.floor(t / 1000), +}); +function safeError(error: TalerError): TalerError { + safeErrors.add(error); + return error; +} +function failure( + hint: string, + code: TalerErrorCode = TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, +): TalerError { + return safeError(TalerError.fromUncheckedDetail({ code, hint })); +} + +function initializeReceipts( + r: WalletFountain, + historyComplete = false, +): boolean { + if (r.receipts) return false; + r.receipts = { trackingSince: stamp(now()), historyComplete, families: [] }; + return true; +} + +/** Validate quantities before using remote values as loop bounds or allocations. */ +export function validateFountainInfo(info: FountainInfoResponse): void { + if ( + info.poll_freq.d_us !== "forever" && + (!Number.isSafeInteger(info.poll_freq.d_us) || info.poll_freq.d_us < 0) + ) + throw failure("Invalid fountain polling frequency"); + const slugs = new Set<string>(); + for (const g of info.grants) { + if (slugs.has(g.token_family_slug)) + throw failure("Duplicate fountain grant"); + slugs.add(g.token_family_slug); + if ( + ![ + g.tokens_per_period_limit, + g.tokens_per_period_stash, + g.key_window_size, + ].every((n) => Number.isSafeInteger(n) && n >= 0) || + g.key_window_size > 12 || + g.tokens_per_period_stash > g.tokens_per_period_limit || + g.token_family.keys.length > g.key_window_size + 1 + ) + throw failure("Invalid fountain grant limits"); + if ( + g.token_family.details.class !== MerchantContractTokenKind.Discount && + g.token_family.details.class !== MerchantContractTokenKind.Subscription + ) + throw failure("Unsupported fountain token family"); + const hashes = new Set<string>(); + for (const key of g.token_family.keys) { + if ( + key.cipher !== DenomKeyType.Rsa || + key.signature_validity_start.t_s === "never" || + millis(key.signature_validity_start) >= + millis(key.signature_validity_end) + ) + throw failure("Unsupported fountain issue key"); + const h = encodeCrock(hashTokenIssuePub(key)); + if (hashes.has(h)) throw failure("Duplicate fountain issue key"); + hashes.add(h); + } + } +} + +function responseFailure({ + response, + detail, +}: OperationFail<number>): TalerError { + // The merchant's numeric code is diagnostic. Its hints and body may echo the credential. + return safeError( + TalerError.fromDetail( + TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR, + { + ...getHttpResponseErrorDetails(response), + errorResponse: + detail && Number.isSafeInteger(detail.code) + ? { code: detail.code } + : undefined, + }, + `Fountain request failed (HTTP ${response.status})`, + ), + ); +} + +function handleFountainRequestError( + e: unknown, + merchantBaseUrl: string, + endpoint: "info" | "withdraw", +): never { + if (e instanceof TalerError) { + const request = { + requestUrl: new URL(`fountain/${endpoint}`, merchantBaseUrl).href, + requestMethod: endpoint === "info" ? "GET" : "POST", + }; + if ( + e.hasErrorCode(TalerErrorCode.WALLET_NETWORK_ERROR) || + e.hasErrorCode(TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT) + ) { + throw safeError( + TalerError.fromDetail(TalerErrorCode.WALLET_NETWORK_ERROR, request), + ); + } + if (e.hasErrorCode(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE)) { + throw safeError( + TalerError.fromDetail( + TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, + { + ...request, + httpStatusCode: e.errorDetail.httpStatusCode, + }, + ), + ); + } + } + throw e; +} + +async function save( + wex: WalletExecutionContext, + r: WalletFountain, +): Promise<void> { + await wex.runWalletDbTx(async (tx) => { + await tx.upsertFountain(r); + tx.notify({ + type: NotificationType.FountainChanged, + fountainId: r.fountainId, + }); + }); +} + +/** Recover one journal entry before considering new grants, even if metadata changed. */ +async function finishPending( + wex: WalletExecutionContext, + api: TalerMerchantInstanceHttpClient, + r: WalletFountain, +): Promise<"ok" | "partial" | "refresh" | "revoked"> { + const pending = r.pending; + if (!pending) return "ok"; + if (pending.expires <= now()) { + delete r.pending; + await save(wex, r); + return "ok"; + } + wex.cancellationToken.throwIfCancelled(); + const response = await api + .withdrawFountain({ + fountain_secret: r.secret, + grants: [pending.request], + }) + .catch((e) => handleFountainRequestError(e, r.merchantBaseUrl, "withdraw")); + if (response.case !== "ok") { + const quota = + response.response.status === 429 && + response.detail?.code === + TalerErrorCode.MERCHANT_POST_FOUNTAIN_WITHDRAW_LIMIT_EXCEEDED; + const e = responseFailure(response); + if (!quota) r.lastError = e.errorDetail; + if (response.response.status === 401) { + r.status = "revoked"; + r.nextPoll = NEVER; + delete r.pending; + await save(wex, r); + return "revoked"; + } + if (quota || [400, 404, 409].includes(response.response.status)) { + // These responses definitively reject the atomic batch; no envelopes were signed. + const h = pending.slates[0].tokenIssuePubHash; + const g = r.info?.grants.find( + (g) => g.token_family_slug === pending.request.token_family_slug, + ); + const slot = (r.slots[h] ??= { issued: 0, expires: pending.expires }); + if (quota && pending.slates.length > 1) { + const count = Math.floor(pending.slates.length / 2); + // A removal confirmed for the rejected batch cannot discard its replacement. + pending.id = encodeCrock(getRandomBytes(32)); + pending.slates = pending.slates.slice(0, count); + pending.request.envelopes = pending.request.envelopes.slice(0, count); + await save(wex, r); + const result = await finishPending(wex, api, r); + return result === "ok" ? "partial" : result; + } + if (quota) slot.blockedAtLimit = g?.tokens_per_period_limit ?? 0; + else slot.rejectedGrant = JSON.stringify(g ?? null); + delete r.pending; + await save(wex, r); + return "refresh"; + } + throw e; + } + const results = response.body.grants; + const expectedHash = pending.slates[0].tokenIssuePubHash; + if ( + results.length !== 1 || + results[0].token_family_slug !== pending.request.token_family_slug || + results[0].h_issue !== expectedHash || + results[0].token_sigs.length !== pending.slates.length + ) + throw failure( + "Fountain withdrawal response does not match the saved request", + ); + const tokens: WalletToken[] = []; + for (let i = 0; i < pending.slates.length; i++) + tokens.push( + await validateToken(wex, pending.slates[i], results[0].token_sigs[i]), + ); + const slot = (r.slots[expectedHash] ??= { + issued: 0, + expires: pending.expires, + }); + slot.issued += tokens.length; + initializeReceipts(r); + const first = pending.slates[0]; + let receipt = r.receipts!.families.find( + (f) => f.tokenFamilySlug === first.slug && f.kind === first.kind, + ); + if (!receipt) { + receipt = { + tokenFamilySlug: first.slug, + kind: first.kind as "discount" | "subscription", + name: first.name, + received: 0, + }; + r.receipts!.families.push(receipt); + } + receipt.name = first.name; + receipt.received += tokens.length; + delete r.pending; + await wex.runWalletDbTx(async (tx) => { + // Store the entire validated batch and quota count together. + for (const token of tokens) await tx.upsertToken(token); + await tx.upsertFountain(r); + tx.notify({ + type: NotificationType.FountainChanged, + fountainId: r.fountainId, + }); + }); + return "ok"; +} + +async function fetchInfo( + wex: WalletExecutionContext, + api: TalerMerchantInstanceHttpClient, + r: WalletFountain, +): Promise<boolean> { + wex.cancellationToken.throwIfCancelled(); + const response = await api + .getFountainInfo(r.secret) + .catch((e) => handleFountainRequestError(e, r.merchantBaseUrl, "info")); + if (response.case !== "ok") { + const e = responseFailure(response); + if (response.response.status !== 401) throw e; + r.status = "revoked"; + r.nextPoll = NEVER; + r.lastError = e.errorDetail; + await save(wex, r); + return false; + } + validateFountainInfo(response.body); + r.info = response.body; + r.needsStocking = true; + r.lastPoll = now(); + // Avoid a hot loop for a zero advertised delay. + r.nextPoll = + response.body.poll_freq.d_us === "forever" + ? NEVER + : Math.min( + NEVER, + r.lastPoll + Math.max(1000, response.body.poll_freq.d_us / 1000), + ); + for (const [h, slot] of Object.entries(r.slots)) + if (slot.expires <= now()) delete r.slots[h]; + await save(wex, r); + return true; +} + +async function preparePending( + wex: WalletExecutionContext, + r: WalletFountain, + grant: FountainWalletGrant, + keyIndex: number, +): Promise<"more" | "last" | undefined> { + const family = grant.token_family; + const key = family.keys[keyIndex]; + if (millis(key.signature_validity_end) <= now()) return undefined; + const h = encodeCrock(hashTokenIssuePub(key)); + const slot = r.slots[h]; + if ( + slot?.blockedAtLimit !== undefined && + grant.tokens_per_period_limit <= slot.blockedAtLimit + ) + return undefined; + if (slot?.rejectedGrant === JSON.stringify(grant)) return undefined; + const held = await wex.runWalletDbTx(async (tx) => { + const tokens = (await tx.getTokensByIssuePubHash(h)).filter( + (t) => t.merchantBaseUrl === r.merchantBaseUrl, + ); + // Count journaled requests too. Their merchant may have already signed them. + const reservations = (await tx.listFountains()).filter( + (f) => + f.merchantBaseUrl === r.merchantBaseUrl && + f.pending?.slates[0].tokenIssuePubHash === h, + ); + return ( + tokens.length + + reservations.reduce((n, f) => n + f.pending!.slates.length, 0) + ); + }); + const remaining = Math.min( + grant.tokens_per_period_stash - held, + grant.tokens_per_period_limit - (slot?.issued ?? 0), + ); + if (remaining <= 0) return undefined; + const count = Math.min(64, remaining); + const seed = encodeCrock(getRandomBytes(32)); + const slates: WalletSlate[] = []; + for (let i = 0; i < count; i++) { + wex.cancellationToken.throwIfCancelled(); + const p = await wex.cryptoApi.createTokenPlanchet({ + secretSeed: seed, + outputIndex: 0, + repeatIndex: i, + tokenIssuePub: key, + purpose: "fountain", + }); + const slate: WalletSlate = { + fountainId: r.fountainId, + merchantBaseUrl: r.merchantBaseUrl, + kind: family.details.class, + slug: grant.token_family_slug, + name: family.name, + description: family.description, + descriptionI18n: family.description_i18n, + extraData: family.details, + tokenIssuePub: key, + validAfter: timestampProtocolToDb(key.signature_validity_start), + validBefore: timestampProtocolToDb(key.signature_validity_end), + tokenIssuePubHash: p.tokenIssuePubHash, + tokenUsePub: p.tokenPub, + tokenUsePriv: p.tokenPriv, + tokenEv: p.tokenEv, + tokenEvHash: p.tokenEvHash, + blindingKey: p.blindingKey, + }; + slate.tokenFamilyHash = WalletToken.hashInfo(slate); + slates.push(slate); + } + r.needsStocking = true; + r.pending = { + id: encodeCrock(getRandomBytes(32)), + slates, + expires: millis(key.signature_validity_end), + request: { + token_family_slug: grant.token_family_slug, + valid_at: key.signature_validity_start, + envelopes: slates.map((s) => s.tokenEv), + }, + }; + await save(wex, r); + return remaining > count ? "more" : "last"; +} + +async function synchronizeFountain( + wex: WalletExecutionContext, + id: string, + force: boolean, +): Promise<void> { + await wex.ws.runSequentialized([`fountain:${id}`], async () => { + const r = await wex.runWalletDbTx(async (tx) => { + const record = await tx.getFountain(id); + if (record && initializeReceipts(record)) await tx.upsertFountain(record); + return record; + }); + if ( + !r || + r.status === "revoked" || + (!force && !r.pending && !r.needsStocking && r.nextPoll > now()) + ) + return; + if (!wex.ws.networkAvailable) + throw failure("Network unavailable", TalerErrorCode.WALLET_NETWORK_ERROR); + const api = walletMerchantClient(r.merchantBaseUrl, wex); + try { + delete r.lastError; + const recovery = await finishPending(wex, api, r); + if (recovery === "revoked") return; + if (force || !r.info || r.nextPoll <= now() || recovery === "refresh") { + if (!(await fetchInfo(wex, api, r))) return; + } + const work = r + .info!.grants.flatMap((g) => + g.token_family.keys.map((key, keyIndex) => ({ g, key, keyIndex })), + ) + .sort( + (a, b) => + millis(a.key.signature_validity_start) - + millis(b.key.signature_validity_start), + ); + // Bound each run, then continue stocking without re-polling metadata early. + let metadataChanged = false; + let needsStocking = false; + for (const { g, keyIndex } of work) { + const hash = encodeCrock( + hashTokenIssuePub(g.token_family.keys[keyIndex]), + ); + const batch = await wex.ws.runSequentialized( + [`fountain-stock:${r.merchantBaseUrl}:${hash}`], + () => preparePending(wex, r, g, keyIndex), + ); + if (!batch) continue; + const outcome = await finishPending(wex, api, r); + if (outcome === "revoked") return; + if (outcome === "refresh") metadataChanged = true; + if (outcome === "partial" || (outcome === "ok" && batch === "more")) + needsStocking = true; + } + if (metadataChanged && !(await fetchInfo(wex, api, r))) return; + r.needsStocking = needsStocking || metadataChanged; + await save(wex, r); + } catch (e) { + if (e instanceof CancellationToken.CancellationError) throw e; + // Reread: a failed DB commit must not erase the durable pending batch. + const saved = await wex.runWalletDbTx((tx) => tx.getFountain(id)); + const error = + e instanceof TalerError && safeErrors.has(e) + ? e + : failure( + "Fountain synchronization failed; the saved request can be retried", + TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION, + ); + if (saved) { + saved.lastError = error.errorDetail; + await save(wex, saved); + } + throw error; + } + }); +} + +export async function processFountain( + wex: WalletExecutionContext, + fountainId: string, +): Promise<TaskRunResult> { + if (!wex.ws.networkAvailable) return TaskRunResult.networkRequired(); + await synchronizeFountain(wex, fountainId, false); + const record = await wex.runWalletDbTx((tx) => tx.getFountain(fountainId)); + if (!record || record.status === "revoked") return TaskRunResult.finished(); + if (record.needsStocking) return TaskRunResult.runAgainAfter({ seconds: 1 }); + return TaskRunResult.runAgainAt( + record.nextPoll === NEVER + ? AbsoluteTime.never() + : AbsoluteTime.fromMilliseconds(record.nextPoll), + ); +} diff --git a/packages/taler-wallet-core/src/shepherd.test.ts b/packages/taler-wallet-core/src/shepherd.test.ts @@ -27,6 +27,10 @@ test("expired-transaction cleanup is always scheduled", async () => { getActivePeerPullCredits: empty, getActiveRecoupGroups: empty, getExchanges: empty, + listFountains: async () => [ + { fountainId: "active", status: "active" }, + { fountainId: "revoked", status: "revoked" }, + ], } as unknown as WalletDbTransaction; const ws = { async runStandaloneWalletDbTx<T>( @@ -37,6 +41,22 @@ test("expired-transaction cleanup is always scheduled", async () => { } as unknown as InternalWalletState; const result = await getActiveTaskIds(ws); + assert.ok( + result.taskIds.includes( + constructTaskIdentifier({ + tag: PendingTaskType.Fountain, + fountainId: "active", + }), + ), + ); + assert.ok( + !result.taskIds.includes( + constructTaskIdentifier({ + tag: PendingTaskType.Fountain, + fountainId: "revoked", + }), + ), + ); assert.ok( result.taskIds.includes( diff --git a/packages/taler-wallet-core/src/shepherd.ts b/packages/taler-wallet-core/src/shepherd.ts @@ -17,6 +17,7 @@ /** * Imports. */ +import { processFountain } from "./fountains.js"; import { processRefreshBalance } from "./refreshBalance.js"; import { autoRefreshRetryCap, @@ -175,6 +176,7 @@ function taskGivesLiveness(taskId: string): boolean { case PendingTaskType.RefreshBalance: case PendingTaskType.ValidateDenoms: case PendingTaskType.CleanupExpiredTransactions: + case PendingTaskType.Fountain: return false; case PendingTaskType.Deposit: case PendingTaskType.PeerPullCredit: @@ -879,6 +881,8 @@ async function callOperationHandlerForTaskId( } switch (pending.tag) { + case PendingTaskType.Fountain: + return processFountain(wex, pending.fountainId); case PendingTaskType.ExchangeUpdate: return await updateExchangeFromUrlHandler(wex, pending.exchangeBaseUrl); case PendingTaskType.ExchangeAutoRefresh: @@ -944,6 +948,7 @@ async function taskToRetryNotification( case PendingTaskType.PeerPushDebit: case PendingTaskType.Purchase: return makeTransactionRetryNotification(ws, tx, pendingTaskId, e); + case PendingTaskType.Fountain: case PendingTaskType.RefreshBalance: case PendingTaskType.ValidateDenoms: case PendingTaskType.CleanupExpiredTransactions: @@ -1224,6 +1229,15 @@ export async function getActiveTaskIds( taskIds: [], }; await ws.runStandaloneWalletDbTx(async (tx) => { + for (const f of await tx.listFountains()) { + if (f.status === "active") + res.taskIds.push( + constructTaskIdentifier({ + tag: PendingTaskType.Fountain, + fountainId: f.fountainId, + }), + ); + } // Withdrawals { diff --git a/packages/wallet-webui/src/api/notifications.ts b/packages/wallet-webui/src/api/notifications.ts @@ -63,6 +63,8 @@ export function notificationFamilies( return ["refresh-info"]; case NotificationType.UserAttentionChanged: return ["user-attention"]; + case NotificationType.FountainChanged: + return ["tokens"]; case NotificationType.BalanceChange: return ["balances", "transactions", "tokens"]; case NotificationType.TransactionStateTransition: