commit 02921716dd0e4465c46eab1ab98d873d43eb6de2
parent 54869f69e15b44a4c52cbff6b8de549915170738
Author: Florian Dold <dold@taler.net>
Date: Thu, 26 Nov 2026 00:54:39 +0100
wallet-core: expose fountain management and purpose filters in API v13
Import credentials offline, report receipt and wallet-wide token counts,
and filter on the last known merchant purpose. Removing a fountain with
unfinished work requires confirmation for the current withdrawal ID.
Diffstat:
8 files changed, 798 insertions(+), 6 deletions(-)
diff --git a/packages/taler-wallet-core/src/fountains.test.ts b/packages/taler-wallet-core/src/fountains.test.ts
@@ -0,0 +1,457 @@
+/*
+ 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 assert from "node:assert/strict";
+import { constants, generateKeyPairSync, privateEncrypt } from "node:crypto";
+import { test } from "node:test";
+import {
+ CancellationToken,
+ decodeCrock,
+ DenomKeyType,
+ encodeCrock,
+ FountainInfoResponse,
+ FountainPurpose,
+ FountainWithdrawRequest,
+ hashTokenIssuePub,
+ MerchantContractTokenKind,
+ SetTimeoutTimerAPI,
+ TalerError,
+ TalerErrorCode,
+} from "@gnu-taler/taler-util";
+import { FakeHttpLib } from "../../taler-util/lib/http-fake.js";
+import { nativeCrypto } from "./crypto/cryptoImplementation.js";
+import { WalletDbHandle } from "./db/handle.js";
+import { makeSqliteRunner, runnerFactories } from "./db/testing/runners.js";
+import {
+ importFountain,
+ listFountains,
+ refreshFountain,
+ removeFountain,
+} from "./fountains.js";
+import { SequentialLocks } from "./sequential-locks.js";
+import { Wallet, WalletExecutionContext } from "./wallet.js";
+import { WalletApiOperation } from "./wallet-api-types.js";
+import { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronousWorkerFactoryPlain.js";
+import { listDiscounts } from "./tokenFamilies.js";
+
+function rsaFixture() {
+ const pair = generateKeyPairSync("rsa", { modulusLength: 1024 });
+ const jwk = pair.publicKey.export({ format: "jwk" });
+ const n = Buffer.from(jwk.n!, "base64url"),
+ e = Buffer.from(jwk.e!, "base64url");
+ const lengths = Buffer.alloc(4);
+ lengths.writeUInt16BE(n.length, 0);
+ lengths.writeUInt16BE(e.length, 2);
+ return { pair, n, rsaPub: encodeCrock(Buffer.concat([lengths, n, e])) };
+}
+const firstKey = rsaFixture(),
+ nextKey = rsaFixture();
+const { rsaPub } = firstKey;
+const secret = encodeCrock(new Uint8Array(32).fill(7));
+const uri = `taler://fountain/merchant.example/instances/default/fountain/${secret}`;
+const start = Math.floor(Date.now() / 1000) - 60;
+function info(stash = 2, limit = 3): FountainInfoResponse {
+ return {
+ poll_freq: { d_us: 3600_000_000 },
+ grants: [
+ {
+ token_family_slug: "discount",
+ tokens_per_period_limit: limit,
+ tokens_per_period_stash: stash,
+ key_window_size: 0,
+ token_family: {
+ name: "Student discount",
+ description: "Discount",
+ details: {
+ class: MerchantContractTokenKind.Discount,
+ expected_domains: [],
+ },
+ critical: false,
+ keys: [
+ {
+ cipher: "RSA",
+ rsa_pub: rsaPub,
+ signature_validity_start: { t_s: start },
+ signature_validity_end: { t_s: start + 86400 },
+ },
+ ],
+ },
+ },
+ ],
+ };
+}
+function issuer() {
+ const state = {
+ info: info(),
+ failAfterSigning: false,
+ remaining: Infinity,
+ quota: false,
+ revoked: false,
+ corrupt: false,
+ corruptSignature: false,
+ signatures: 0,
+ lost: false,
+ };
+ const journal = new Map<string, unknown>();
+ const requests: FountainWithdrawRequest[] = [];
+ const http = new FakeHttpLib().handle((req) => {
+ assert.ok(!req.url.includes(secret));
+ if (state.revoked)
+ return {
+ status: 401,
+ body: {
+ code: TalerErrorCode.MERCHANT_GENERIC_UNAUTHORIZED,
+ hint: secret,
+ },
+ };
+ if (req.method === "GET") {
+ assert.equal(req.headers?.Authorization, `Bearer ${secret}`);
+ return { status: 200, body: state.info };
+ }
+ const body = structuredClone(req.body) as FountainWithdrawRequest;
+ requests.push(body);
+ assert.equal(body.fountain_secret, secret);
+ assert.ok(body.grants.reduce((n, g) => n + g.envelopes.length, 0) <= 64);
+ const key = JSON.stringify(body.grants);
+ let result = journal.get(key);
+ if (!result) {
+ if (state.quota || body.grants[0].envelopes.length > state.remaining)
+ return {
+ status: 429,
+ body: {
+ code: TalerErrorCode.MERCHANT_POST_FOUNTAIN_WITHDRAW_LIMIT_EXCEEDED,
+ },
+ };
+ result = {
+ grants: body.grants.map((g) => {
+ const family = state.info.grants.find(
+ (f) => f.token_family_slug === g.token_family_slug,
+ )!;
+ const issue = family.token_family.keys.find(
+ (k) => k.signature_validity_start.t_s === g.valid_at?.t_s,
+ )!;
+ return {
+ token_family_slug: g.token_family_slug,
+ h_issue: encodeCrock(hashTokenIssuePub(issue)),
+ token_sigs: g.envelopes.map((ev) => {
+ assert.equal(ev.cipher, DenomKeyType.Rsa);
+ if (ev.cipher !== DenomKeyType.Rsa) throw Error("unsupported");
+ const { pair, n } =
+ issue.cipher === "RSA" && issue.rsa_pub === nextKey.rsaPub
+ ? nextKey
+ : firstKey;
+ const value = decodeCrock(ev.rsa_blinded_planchet);
+ const padded = Buffer.alloc(n.length);
+ padded.set(value, padded.length - value.length);
+ state.signatures++;
+ return {
+ blind_sig: {
+ cipher: "RSA",
+ blinded_rsa_signature: encodeCrock(
+ privateEncrypt(
+ {
+ key: pair.privateKey,
+ padding: constants.RSA_NO_PADDING,
+ },
+ padded,
+ ),
+ ),
+ },
+ };
+ }),
+ };
+ }),
+ };
+ state.remaining -= body.grants[0].envelopes.length;
+ journal.set(key, result);
+ }
+ if (state.failAfterSigning && !state.lost) {
+ state.lost = true;
+ throw Error("connection lost after merchant commit");
+ }
+ if (state.corrupt) return { status: 200, body: { grants: [] } };
+ if (state.corruptSignature) {
+ const altered = structuredClone(result) as {
+ grants: {
+ token_sigs: { blind_sig: { blinded_rsa_signature: string } }[];
+ }[];
+ };
+ altered.grants[0].token_sigs[0].blind_sig.blinded_rsa_signature =
+ encodeCrock(new Uint8Array(128));
+ return { status: 200, body: altered };
+ }
+ return { status: 200, body: result };
+ });
+ return { state, requests, http };
+}
+function context(
+ db: WalletDbHandle,
+ http: FakeHttpLib,
+): WalletExecutionContext {
+ const locks = new SequentialLocks();
+ return {
+ runWalletDbTx: db.runReadWriteTx.bind(db),
+ cryptoApi: nativeCrypto,
+ http,
+ cancellationToken: CancellationToken.CONTINUE,
+ ws: { networkAvailable: true, runSequentialized: locks.run.bind(locks) },
+ taskScheduler: { startShepherdTask() {} },
+ } as unknown as WalletExecutionContext;
+}
+
+for (const makeDb of runnerFactories) {
+ test(`${makeDb.name}: fountain display metadata follows the latest successful poll`, async () => {
+ const db = await makeDb();
+ try {
+ const mock = issuer();
+ const wex = context(db, mock.http);
+ const f = await importFountain(wex, { talerFountainUri: uri });
+ assert.equal(f.name, f.merchantFountainId);
+ const translations = { de: "Campusvorteile" };
+ const metadata = {
+ fountain_purpose: "access-card",
+ campaign: { rooms: ["library", "museum"] },
+ };
+ assert.equal(f.purpose, undefined);
+ mock.state.info = {
+ ...info(0),
+ name: "Campus benefits",
+ name_i18n: translations,
+ extra_data: metadata,
+ };
+ const updated = await refreshFountain(wex, f);
+ assert.equal(updated.name, "Campus benefits");
+ assert.deepEqual(updated.nameI18n, translations);
+ assert.deepEqual(updated.extraData, metadata);
+ assert.equal(updated.purpose, "access-card");
+ const stored = await db.runReadWriteTx((tx) =>
+ tx.getFountain(f.fountainId),
+ );
+ assert.deepEqual(stored?.info?.extra_data, metadata);
+ const restarted = context(db, mock.http);
+ const malformed = new FakeHttpLib().on("GET", "/fountain/info", {
+ status: 200,
+ body: { ...mock.state.info, extra_data: [secret] },
+ });
+ await assert.rejects(
+ refreshFountain(context(db, malformed), f),
+ (e) =>
+ e instanceof TalerError &&
+ e.hasErrorCode(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE),
+ );
+ const [listed] = (
+ await listFountains(restarted, { purpose: FountainPurpose.AccessCard })
+ ).fountains;
+ assert.equal(listed.name, updated.name);
+ assert.deepEqual(listed.nameI18n, translations);
+ assert.deepEqual(listed.extraData, metadata);
+ assert.equal(listed.purpose, "access-card");
+ assert.ok(!JSON.stringify(listed).includes(secret));
+ mock.state.info = info(0);
+ const cleared = await refreshFountain(restarted, f);
+ assert.equal(cleared.name, f.merchantFountainId);
+ assert.equal(cleared.nameI18n, undefined);
+ assert.equal(cleared.extraData, undefined);
+ assert.equal(cleared.purpose, undefined);
+ assert.deepEqual(
+ (
+ await listFountains(restarted, {
+ purpose: FountainPurpose.AccessCard,
+ })
+ ).fountains,
+ [],
+ );
+ } finally {
+ await db.close();
+ }
+ });
+ test(`${makeDb.name}: list fountains by the last known purpose while offline`, async () => {
+ const db = await makeDb();
+ try {
+ const mock = issuer();
+ const wex = context(db, mock.http);
+ const offline = context(db, new FakeHttpLib());
+ const purposes = [
+ "access-card",
+ "promotion",
+ "future-purpose",
+ 42,
+ undefined,
+ ];
+ const ids: string[] = [];
+ for (const [i, purpose] of purposes.entries()) {
+ const f = await importFountain(wex, {
+ talerFountainUri: uri.replace(
+ "/default/fountain/",
+ `/default/fountain-${i}/`,
+ ),
+ });
+ ids.push(f.fountainId);
+ if (purpose !== undefined) {
+ mock.state.info = {
+ ...info(0),
+ extra_data: { fountain_purpose: purpose },
+ };
+ await refreshFountain(wex, f);
+ }
+ }
+ const all = (await listFountains(offline)).fountains;
+ assert.equal(all.length, ids.length);
+ for (const [i, id] of ids.entries()) {
+ const f = all.find((item) => item.fountainId === id)!;
+ assert.equal(f.purpose, i < 2 ? purposes[i] : undefined);
+ assert.equal(f.extraData?.fountain_purpose, purposes[i]);
+ }
+ for (const [i, purpose] of Object.values(FountainPurpose).entries()) {
+ const { fountains } = await listFountains(offline, { purpose });
+ assert.deepEqual(
+ fountains.map((f) => f.fountainId),
+ [ids[i]],
+ );
+ }
+ } finally {
+ await db.close();
+ }
+ });
+ test(`${makeDb.name}: fountain tokens persist, replenish within quota and survive removal`, async () => {
+ const db = await makeDb();
+ try {
+ const mock = issuer(),
+ wex = context(db, mock.http);
+ const f = await importFountain(wex, { talerFountainUri: uri });
+ assert.equal(f.collectionPending, true);
+ assert.equal(f.lastPoll, undefined);
+ assert.equal(mock.http.requests.length, 0);
+ assert.equal(
+ (await importFountain(wex, { talerFountainUri: uri })).fountainId,
+ f.fountainId,
+ );
+ await assert.rejects(
+ importFountain(wex, {
+ talerFountainUri: uri.replace(
+ secret,
+ encodeCrock(new Uint8Array(32)),
+ ),
+ }),
+ /different credential/,
+ );
+ await Promise.all([refreshFountain(wex, f), refreshFountain(wex, f)]);
+ assert.equal(mock.state.signatures, 2);
+ const synced = (await listFountains(wex)).fountains[0];
+ assert.equal(synced.collectionPending, false);
+ assert.ok(synced.lastPoll);
+ const stats = synced.statistics!;
+ assert.equal(stats.historyComplete, true);
+ assert.equal(stats.families[0].receivedFromFountain, 2);
+ assert.equal(stats.families[0].availableInWallet, 2);
+ const discounts = await listDiscounts(wex);
+ assert.equal(discounts.discounts[0].tokensAvailable, 2);
+ assert.equal(discounts.discounts[0].merchantInfo, undefined);
+ let tokens = await db.runReadWriteTx((tx) => tx.listTokens());
+ assert.equal(tokens[0].purchaseId, undefined);
+ assert.equal(tokens[0].fountainId, f.fountainId);
+ await db.runReadWriteTx((tx) => tx.deleteToken(tokens[0].tokenUsePub));
+ await refreshFountain(wex, f);
+ assert.equal(mock.state.signatures, 3);
+ tokens = await db.runReadWriteTx((tx) => tx.listTokens());
+ await db.runReadWriteTx((tx) => tx.deleteToken(tokens[0].tokenUsePub));
+ await refreshFountain(wex, f);
+ assert.equal(mock.state.signatures, 3);
+ const details = (await listFountains(wex)).fountains[0];
+ assert.equal(details.statistics!.families[0].receivedFromFountain, 3);
+ assert.equal(details.statistics!.families[0].availableInWallet, 1);
+ assert.equal(details.quotas![0].limitReached, true);
+ assert.ok(!JSON.stringify(details).includes(secret));
+ await removeFountain(wex, f);
+ assert.equal((await listFountains(wex)).fountains.length, 0);
+ assert.equal((await listDiscounts(wex)).discounts[0].tokensAvailable, 1);
+ const reimported = await importFountain(wex, { talerFountainUri: uri });
+ assert.deepEqual(reimported.statistics!.families, []);
+ const recollected = await refreshFountain(wex, reimported);
+ assert.equal(recollected.statistics!.families[0].receivedFromFountain, 1);
+ assert.equal(recollected.statistics!.families[0].availableInWallet, 2);
+ } finally {
+ await db.close();
+ }
+ });
+}
+
+test("refreshFountain returns typed errors for documented and unknown merchant codes", async (t) => {
+ let status = 404;
+ let code: number =
+ TalerErrorCode.MERCHANT_PRIVATE_POST_ORDERS_TOKEN_FAMILY_SLUG_UNKNOWN;
+ const http = new FakeHttpLib().handle(() => ({
+ status,
+ body: { code, hint: secret, extra: secret },
+ }));
+ const wallet = await Wallet.create(
+ await makeSqliteRunner(),
+ () => http,
+ new SetTimeoutTimerAPI(),
+ new SynchronousCryptoWorkerFactoryPlain(),
+ );
+ t.after(() => wallet.shutdown());
+ const client = wallet.client;
+ await client.call(WalletApiOperation.SetWalletRunConfig, {
+ config: { lazyTaskLoop: true, testing: { skipDefaults: true } },
+ });
+ const { fountainId } = await client.call(WalletApiOperation.ImportFountain, {
+ talerFountainUri: uri,
+ });
+ for (const [httpStatus, merchantCode] of [
+ [404, code],
+ [503, 987654],
+ [429, TalerErrorCode.MERCHANT_POST_FOUNTAIN_WITHDRAW_LIMIT_EXCEEDED],
+ ]) {
+ status = httpStatus;
+ code = merchantCode;
+ const result = await client.callForResult(
+ WalletApiOperation.RefreshFountain,
+ { fountainId },
+ );
+ assert.equal(result.tag, "error");
+ assert.equal(result.error, TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR);
+ const stored = (await client.call(WalletApiOperation.ListFountains, {}))
+ .fountains[0].lastError;
+ assert.equal(stored?.httpStatusCode, status);
+ assert.deepEqual(stored?.errorResponse, { code });
+ assert.deepEqual(structuredClone(result.detail), stored);
+ assert.ok(!JSON.stringify(result).includes(secret));
+ }
+});
+
+test("fountain diagnostics omit credentials echoed by the HTTP client", async () => {
+ const db = await makeSqliteRunner();
+ try {
+ const http = new FakeHttpLib().handle(() => {
+ throw TalerError.fromUncheckedDetail({
+ code: TalerErrorCode.WALLET_NETWORK_ERROR,
+ hint: `Fountain request failed: ${secret}`,
+ });
+ });
+ const wex = context(db, http);
+ const f = await importFountain(wex, { talerFountainUri: uri });
+ await assert.rejects(refreshFountain(wex, f), (error) => {
+ assert.ok(error instanceof TalerError);
+ assert.equal(error.errorDetail.code, TalerErrorCode.WALLET_NETWORK_ERROR);
+ assert.ok(!JSON.stringify(error.errorDetail).includes(secret));
+ return true;
+ });
+ assert.ok(!JSON.stringify(await listFountains(wex)).includes(secret));
+ } finally {
+ await db.close();
+ }
+});
diff --git a/packages/taler-wallet-core/src/fountains.ts b/packages/taler-wallet-core/src/fountains.ts
@@ -19,26 +19,46 @@ import {
CancellationToken,
DenomKeyType,
encodeCrock,
+ decodeCrockFixed,
+ FountainDetails,
FountainInfoResponse,
+ FountainPurpose,
+ FountainRequest,
FountainWalletGrant,
getRandomBytes,
hashTokenIssuePub,
+ ImportFountainRequest,
+ ListFountainsRequest,
+ ListFountainsResponse,
+ RemoveFountainRequest,
+ RemoveFountainResponse,
MerchantContractTokenKind,
NotificationType,
OperationFail,
+ FountainTokenStatistics,
+ Result,
TalerError,
TalerErrorCode,
TalerMerchantInstanceHttpClient,
TalerProtocolTimestamp,
+ TalerUriAction,
+ TalerUris,
} from "@gnu-taler/taler-util";
import { getHttpResponseErrorDetails } from "@gnu-taler/taler-util/http";
-import { TaskRunResult } from "./common.js";
+import {
+ constructTaskIdentifier,
+ PendingTaskType,
+ TaskRunResult,
+} from "./common.js";
import {
timestampProtocolToDb,
WalletFountain,
WalletSlate,
WalletToken,
} from "./db/records.js";
+import { WalletDbTransaction } from "./db/transaction.js";
+import { isTokenInUse, isTokenValid } from "./tokenSelection.js";
+import { timestampProtocolFromDb } from "./db/timestamps.js";
import { validateToken } from "./tokens.js";
import { walletMerchantClient, WalletExecutionContext } from "./wallet.js";
@@ -71,6 +91,215 @@ function initializeReceipts(
return true;
}
+async function detailsInTx(
+ tx: WalletDbTransaction,
+ r: WalletFountain,
+): Promise<FountainDetails> {
+ if (initializeReceipts(r)) await tx.upsertFountain(r);
+ return fountainDetails(r, await tx.listTokens());
+}
+
+function fountainPurpose(record: WalletFountain) {
+ const value = record.info?.extra_data?.fountain_purpose;
+ return Object.values(FountainPurpose).find((purpose) => purpose === value);
+}
+
+export function fountainDetails(
+ r: WalletFountain,
+ tokens: readonly WalletToken[] = [],
+): FountainDetails {
+ const families: FountainTokenStatistics[] = (r.receipts?.families ?? []).map(
+ ({ received, ...family }) => ({
+ ...family,
+ receivedFromFountain: received,
+ availableInWallet: 0,
+ futureInWallet: 0,
+ }),
+ );
+ for (const grant of r.info?.grants ?? []) {
+ const kind = grant.token_family.details.class;
+ if (kind !== "discount" && kind !== "subscription") continue;
+ const existing = families.find(
+ (f) => f.tokenFamilySlug === grant.token_family_slug && f.kind === kind,
+ );
+ if (existing) existing.name = grant.token_family.name;
+ else
+ families.push({
+ tokenFamilySlug: grant.token_family_slug,
+ kind,
+ name: grant.token_family.name,
+ receivedFromFountain: 0,
+ availableInWallet: 0,
+ futureInWallet: 0,
+ });
+ }
+ for (const token of tokens) {
+ if (token.merchantBaseUrl !== r.merchantBaseUrl || isTokenInUse(token))
+ continue;
+ const family = families.find(
+ (f) => f.tokenFamilySlug === token.slug && f.kind === token.kind,
+ );
+ if (!family) continue;
+ if (isTokenValid(token)) family.availableInWallet++;
+ else if (
+ millis(timestampProtocolFromDb(token.validAfter)) > now() &&
+ millis(timestampProtocolFromDb(token.validBefore)) > now()
+ )
+ family.futureInWallet++;
+ }
+ return {
+ fountainId: r.fountainId,
+ merchantFountainId: r.merchantFountainId,
+ name: r.info?.name ?? r.merchantFountainId,
+ nameI18n: r.info?.name_i18n,
+ extraData: r.info?.extra_data,
+ purpose: fountainPurpose(r),
+ merchantBaseUrl: r.merchantBaseUrl,
+ status: r.status,
+ collectionPending:
+ r.status === "active" &&
+ (r.lastPoll === undefined || !!r.pending || !!r.needsStocking),
+ grants: r.info?.grants ?? [],
+ lastPoll: r.lastPoll === undefined ? undefined : stamp(r.lastPoll),
+ nextPoll: stamp(r.nextPoll),
+ lastError: r.lastError,
+ pollFrequency: r.info?.poll_freq,
+ statistics: r.receipts ? { ...r.receipts, families } : undefined,
+ quotas: r.info?.grants.flatMap((g) =>
+ g.token_family.keys.map((key) => {
+ const slot = r.slots[encodeCrock(hashTokenIssuePub(key))];
+ return {
+ tokenFamilySlug: g.token_family_slug,
+ validityStart: key.signature_validity_start,
+ validityEnd: key.signature_validity_end,
+ issued: slot?.issued ?? 0,
+ limitReached:
+ (slot?.issued ?? 0) >= g.tokens_per_period_limit ||
+ (slot?.blockedAtLimit !== undefined &&
+ g.tokens_per_period_limit <= slot.blockedAtLimit),
+ };
+ }),
+ ),
+ };
+}
+function wake(wex: WalletExecutionContext, id: string): void {
+ wex.taskScheduler.startShepherdTask(
+ constructTaskIdentifier({ tag: PendingTaskType.Fountain, fountainId: id }),
+ );
+}
+export async function importFountain(
+ wex: WalletExecutionContext,
+ req: ImportFountainRequest,
+): Promise<FountainDetails> {
+ const uri = Result.orUndefined(
+ TalerUris.parseRestricted(req.talerFountainUri, TalerUriAction.Fountain),
+ );
+ if (!uri)
+ throw TalerError.fromDetail(TalerErrorCode.WALLET_TALER_URI_MALFORMED, {
+ expectedAction: TalerUriAction.Fountain,
+ });
+ const secret = encodeCrock(decodeCrockFixed(uri.fountainSecret, 32));
+ const result = await wex.runWalletDbTx(async (tx) => {
+ const existing = (await tx.listFountains()).find(
+ (r) =>
+ r.merchantBaseUrl === uri.merchantBaseUrl &&
+ r.merchantFountainId === uri.fountainId,
+ );
+ if (existing) {
+ if (existing.secret !== secret)
+ throw failure(
+ "A different credential is already stored for this fountain",
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ );
+ return detailsInTx(tx, existing);
+ }
+ const record: WalletFountain = {
+ fountainId: encodeCrock(getRandomBytes(32)),
+ merchantBaseUrl: uri.merchantBaseUrl,
+ merchantFountainId: uri.fountainId,
+ secret,
+ status: "active",
+ slots: {},
+ nextPoll: 0,
+ };
+ initializeReceipts(record, true);
+ await tx.upsertFountain(record);
+ tx.notify({
+ type: NotificationType.FountainChanged,
+ fountainId: record.fountainId,
+ });
+ return detailsInTx(tx, record);
+ });
+ wake(wex, result.fountainId);
+ return result;
+}
+export async function listFountains(
+ wex: WalletExecutionContext,
+ { purpose }: ListFountainsRequest = {},
+): Promise<ListFountainsResponse> {
+ return wex.runWalletDbTx(async (tx) => {
+ const records = (await tx.listFountains()).filter(
+ (r) => purpose === undefined || fountainPurpose(r) === purpose,
+ );
+ if (records.length === 0) return { fountains: [] };
+ const tokens = await tx.listTokens();
+ for (const r of records)
+ if (initializeReceipts(r)) await tx.upsertFountain(r);
+ return { fountains: records.map((r) => fountainDetails(r, tokens)) };
+ });
+}
+export async function removeFountain(
+ wex: WalletExecutionContext,
+ req: RemoveFountainRequest,
+): Promise<RemoveFountainResponse> {
+ const result = await wex.ws.runSequentialized(
+ [`fountain:${req.fountainId}`],
+ () =>
+ wex.runWalletDbTx(async (tx): Promise<RemoveFountainResponse> => {
+ const record = await tx.getFountain(req.fountainId);
+ if (!record) return { status: "removed" };
+ const pending = record.pending;
+ if (
+ pending &&
+ pending.expires > now() &&
+ req.discardPendingWithdrawalId !== pending.id
+ ) {
+ return {
+ status: "withdrawalPending",
+ pendingWithdrawalId: pending.id,
+ };
+ }
+ await tx.deleteFountain(req.fountainId);
+ tx.notify({
+ type: NotificationType.FountainChanged,
+ fountainId: req.fountainId,
+ });
+ return { status: "removed" };
+ }),
+ );
+ if (result.status === "removed") wake(wex, req.fountainId);
+ return result;
+}
+export async function refreshFountain(
+ wex: WalletExecutionContext,
+ req: FountainRequest,
+): Promise<FountainDetails> {
+ try {
+ await synchronizeFountain(wex, req.fountainId, true);
+ return wex.runWalletDbTx(async (tx) => {
+ const r = await tx.getFountain(req.fountainId);
+ if (!r)
+ throw failure(
+ "Unknown fountain",
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ );
+ return detailsInTx(tx, r);
+ });
+ } finally {
+ wake(wex, req.fountainId);
+ }
+}
+
/** Validate quantities before using remote values as loop bounds or allocations. */
export function validateFountainInfo(info: FountainInfoResponse): void {
if (
diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts
@@ -46,6 +46,16 @@ import {
} from "./user-attention.js";
import { observeTransaction, stopObservation } from "./observe-transaction.js";
import {
+ importFountain,
+ listFountains,
+ refreshFountain,
+ removeFountain,
+} from "./fountains.js";
+import {
+ codecForImportFountainRequest,
+ codecForListFountainsRequest,
+ codecForRemoveFountainRequest,
+ codecForFountainRequest,
AbsoluteTime,
codecForString,
codecForBoolean,
@@ -2844,6 +2854,22 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = {
codec: codecForDeleteDiscountRequest(),
handler: handleDeleteDiscount,
},
+ [WalletApiOperation.ImportFountain]: {
+ codec: codecForImportFountainRequest(),
+ handler: importFountain,
+ },
+ [WalletApiOperation.ListFountains]: {
+ codec: codecForListFountainsRequest(),
+ handler: listFountains,
+ },
+ [WalletApiOperation.RefreshFountain]: {
+ codec: codecForFountainRequest(),
+ handler: refreshFountain,
+ },
+ [WalletApiOperation.RemoveFountain]: {
+ codec: codecForRemoveFountainRequest(),
+ handler: removeFountain,
+ },
[WalletApiOperation.ListSubscriptions]: {
codec: codecForListSubscriptionsRequest(),
handler: handleListSubscriptions,
diff --git a/packages/taler-wallet-core/src/versions.ts b/packages/taler-wallet-core/src/versions.ts
@@ -52,7 +52,7 @@ export const WALLET_BANK_CONVERSION_API_PROTOCOL_VERSION = "2:0:0";
/**
* Libtool version of the wallet-core API.
*/
-export const WALLET_CORE_API_PROTOCOL_VERSION = "12:0:0";
+export const WALLET_CORE_API_PROTOCOL_VERSION = "13:0:1";
/**
* Libtool rules:
diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts
@@ -24,6 +24,13 @@
* Imports.
*/
import {
+ ImportFountainRequest,
+ FountainRequest,
+ FountainDetails,
+ ListFountainsRequest,
+ ListFountainsResponse,
+ RemoveFountainRequest,
+ RemoveFountainResponse,
AbortTransactionRequest,
AcceptBankIntegratedWithdrawalRequest,
AcceptExchangeTosRequest,
@@ -367,6 +374,11 @@ export enum WalletApiOperation {
ConfirmPeerPullDebit = "confirmPeerPullDebit",
GetMaxPeerPushDebitAmount = "getMaxPeerPushDebitAmount",
+ ImportFountain = "importFountain",
+ ListFountains = "listFountains",
+ RefreshFountain = "refreshFountain",
+ RemoveFountain = "removeFountain",
+
// Tokens and token families
ListDiscounts = "listDiscounts",
DeleteDiscount = "deleteDiscount",
@@ -1054,6 +1066,36 @@ export type DeleteSubscriptionOp = {
response: EmptyObject;
};
+// group: Token fountains
+
+/** Store a fountain credential locally and schedule collection. */
+export type ImportFountainOp = {
+ op: WalletApiOperation.ImportFountain;
+ request: ImportFountainRequest;
+ response: FountainDetails;
+};
+
+/** List the wallet's fountains and their last known collection state. */
+export type ListFountainsOp = {
+ op: WalletApiOperation.ListFountains;
+ request: ListFountainsRequest;
+ response: ListFountainsResponse;
+};
+
+/** Retry a saved withdrawal and check the merchant for available tokens. */
+export type RefreshFountainOp = {
+ op: WalletApiOperation.RefreshFountain;
+ request: FountainRequest;
+ response: FountainDetails;
+};
+
+/** Remove a fountain, requesting confirmation for a recoverable withdrawal. */
+export type RemoveFountainOp = {
+ op: WalletApiOperation.RemoveFountain;
+ request: RemoveFountainRequest;
+ response: RemoveFountainResponse;
+};
+
// group: Global Currency management
export type ListGlobalCurrencyAuditorsOp = {
@@ -1959,6 +2001,17 @@ export const walletApiExpectedErrors = {
TalerErrorCode.PAIVANA_TOO_LATE,
TalerErrorCode.PAIVANA_INVALID_TARGET,
],
+ [WalletApiOperation.ImportFountain]: [
+ TalerErrorCode.WALLET_TALER_URI_MALFORMED,
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ ],
+ [WalletApiOperation.RefreshFountain]: [
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ TalerErrorCode.WALLET_NETWORK_ERROR,
+ TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
+ TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
+ TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
+ ],
[WalletApiOperation.CheckPayForTemplate]: [
TalerErrorCode.WALLET_TALER_URI_MALFORMED,
TalerErrorCode.WALLET_CONTRACT_TERMS_UNSUPPORTED,
@@ -2356,6 +2409,10 @@ export type WalletOperations = {
[WalletApiOperation.DismissWalletWarning]: DismissWalletWarningOp;
[WalletApiOperation.GetDepositWireTypes]: GetDepositWireTypesOp;
[WalletApiOperation.GetBankingChoicesForPayto]: GetBankingChoicesForPaytoOp;
+ [WalletApiOperation.ImportFountain]: ImportFountainOp;
+ [WalletApiOperation.ListFountains]: ListFountainsOp;
+ [WalletApiOperation.RefreshFountain]: RefreshFountainOp;
+ [WalletApiOperation.RemoveFountain]: RemoveFountainOp;
[WalletApiOperation.ListDiscounts]: ListDiscountsOp;
[WalletApiOperation.DeleteDiscount]: DeleteDiscountOp;
[WalletApiOperation.ListSubscriptions]: ListSubscriptionsOp;
diff --git a/packages/wallet-webui/src/api/notifications.ts b/packages/wallet-webui/src/api/notifications.ts
@@ -12,6 +12,7 @@ export type WalletKeyFamily =
| "accounts"
| "contacts"
| "mailbox"
+ | "fountains"
| "tokens"
| "donau"
| "refresh-info"
@@ -44,6 +45,7 @@ export const familyOperations: Record<WalletKeyFamily, readonly string[]> = {
WalletApiOperation.GetMailbox,
WalletApiOperation.GetMailboxMessages,
],
+ fountains: [WalletApiOperation.ListFountains],
tokens: [
WalletApiOperation.ListDiscounts,
WalletApiOperation.ListSubscriptions,
@@ -64,11 +66,11 @@ export function notificationFamilies(
case NotificationType.UserAttentionChanged:
return ["user-attention"];
case NotificationType.FountainChanged:
- return ["tokens"];
+ return ["fountains", "tokens"];
case NotificationType.BalanceChange:
- return ["balances", "transactions", "tokens"];
+ return ["balances", "transactions", "tokens", "fountains"];
case NotificationType.TransactionStateTransition:
- return ["transactions", "tokens"];
+ return ["transactions", "tokens", "fountains"];
case NotificationType.ExchangeStateTransition:
return ["transactions", "exchanges"];
case NotificationType.BankAccountChange:
diff --git a/packages/wallet-webui/src/testing/demo-wallet.ts b/packages/wallet-webui/src/testing/demo-wallet.ts
@@ -1692,7 +1692,7 @@ export class DemoWalletConnection implements WalletConnection {
walletCoreVersion: {
implementationSemver: "demo",
implementationGitHash: "demo",
- version: "12:0:0",
+ version: "13:0:1",
},
frontendInfo: request.frontendInfo,
database: { backend: "indexeddb", recordCounts: {} },
diff --git a/packages/wallet-webui/test/notifications.test.ts b/packages/wallet-webui/test/notifications.test.ts
@@ -64,3 +64,24 @@ test("Donau and refresh report events revalidate their respective queries", () =
[WalletApiOperation.GetBalanceRefreshInfo],
);
});
+
+test("fountain changes refresh grants and usable tokens without payment queries", () => {
+ const operations = operationsForNotification({
+ type: NotificationType.FountainChanged,
+ fountainId: "local-id",
+ });
+ assert.deepEqual(
+ operations,
+ new Set([
+ WalletApiOperation.ListFountains,
+ WalletApiOperation.ListDiscounts,
+ WalletApiOperation.ListSubscriptions,
+ ]),
+ );
+ assert(
+ operationsForNotification({
+ type: NotificationType.BalanceChange,
+ hintTransactionId: "payment",
+ }).has(WalletApiOperation.ListFountains),
+ );
+});