taler-typescript-core

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

commit cbfa61f25803f92f3b9ff64a3bc87b693dd70baa
parent 02921716dd0e4465c46eab1ab98d873d43eb6de2
Author: Florian Dold <dold@taler.net>
Date:   Fri, 20 Nov 2026 19:35:19 +0100

wallet-core: cover fountain quota sharing and interrupted withdrawals

Exercise concurrent stocking, partial quotas and failed commits with a
signing merchant fixture. Check withdrawal recovery, token accounting
and database conversion across the two storage backends.

Diffstat:
Mpackages/taler-wallet-core/src/fountains.test.ts | 544++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 542 insertions(+), 2 deletions(-)

diff --git a/packages/taler-wallet-core/src/fountains.test.ts b/packages/taler-wallet-core/src/fountains.test.ts @@ -27,25 +27,36 @@ import { FountainWithdrawRequest, hashTokenIssuePub, MerchantContractTokenKind, + NotificationType, + openPromise, SetTimeoutTimerAPI, + WalletNotification, 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 { convertWalletDb } from "./db/migration/converter.js"; +import { + makeIdbRunner, + makeSqliteRunner, + runnerFactories, +} from "./db/testing/runners.js"; import { importFountain, listFountains, refreshFountain, removeFountain, + processFountain, } 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"; +import { listDiscounts, listSubscriptions } from "./tokenFamilies.js"; +import { timestampProtocolToDb } from "./db/records.js"; +import { TaskRunResultType } from "./common.js"; function rsaFixture() { const pair = generateKeyPairSync("rsa", { modulusLength: 1024 }); @@ -387,6 +398,343 @@ for (const makeDb of runnerFactories) { await db.close(); } }); + test(`${makeDb.name}: a stale removal cannot discard a smaller signed withdrawal`, async () => { + const db = await makeDb(); + try { + const mock = issuer(); + const wex = context(db, mock.http); + const f = await importFountain(wex, { talerFountainUri: uri }); + const fetch = mock.http.fetch.bind(mock.http); + mock.http.fetch = (url, options) => { + if (options?.method === "POST") throw Error("offline before delivery"); + return fetch(url, options); + }; + await assert.rejects(refreshFountain(wex, f)); + const original = await removeFountain(wex, f); + assert.equal(original.status, "withdrawalPending"); + + mock.http.fetch = fetch; + mock.state.remaining = 1; + mock.state.failAfterSigning = true; + await assert.rejects(refreshFountain(wex, f)); + assert.deepEqual( + mock.requests.map((r) => r.grants[0].envelopes.length), + [2, 1], + ); + const restarted = context(db, mock.http); + const current = await removeFountain(restarted, { + fountainId: f.fountainId, + discardPendingWithdrawalId: original.pendingWithdrawalId, + }); + assert.equal(current.status, "withdrawalPending"); + assert.notEqual( + current.pendingWithdrawalId, + original.pendingWithdrawalId, + ); + assert.deepEqual(await removeFountain(restarted, f), current); + + const recovered = await refreshFountain(restarted, f); + assert.deepEqual(mock.requests[2], mock.requests[1]); + assert.equal(mock.state.signatures, 1); + assert.equal(recovered.statistics!.families[0].receivedFromFountain, 1); + } finally { + await db.close(); + } + }); + test(`${makeDb.name}: lost withdrawal response recovers unchanged across database conversion`, async () => { + const db = await makeDb(); + const dst = await (makeDb === makeSqliteRunner + ? makeIdbRunner() + : makeSqliteRunner()); + try { + const mock = issuer(); + mock.state.failAfterSigning = true; + const wex = context(db, mock.http); + const f = await importFountain(wex, { talerFountainUri: uri }); + await assert.rejects(refreshFountain(wex, f), /saved request/); + assert.equal( + (await db.runReadWriteTx((tx) => tx.listTokens())).length, + 0, + ); + assert.ok( + (await db.runReadWriteTx((tx) => tx.getFountain(f.fountainId))) + ?.pending, + ); + assert.deepEqual( + (await listFountains(wex)).fountains[0].statistics!.families.map( + (f) => f.receivedFromFountain, + ), + [0], + ); + wex.ws.networkAvailable = false; + const blocked = await removeFountain(wex, f); + assert.equal(blocked.status, "withdrawalPending"); + assert.deepEqual( + await removeFountain(wex, { + fountainId: f.fountainId, + discardPendingWithdrawalId: "older-batch", + }), + blocked, + ); + assert.equal( + (await listFountains(wex)).fountains[0].collectionPending, + true, + ); + await convertWalletDb(db, dst); + // Abandon this copy offline; the migrated wallet can still recover the same response. + assert.deepEqual( + await removeFountain(wex, { + fountainId: f.fountainId, + discardPendingWithdrawalId: blocked.pendingWithdrawalId, + }), + { status: "removed" }, + ); + assert.deepEqual(await removeFountain(wex, f), { status: "removed" }); + assert.equal((await listFountains(wex)).fountains.length, 0); + // The committed merchant response remains recoverable after grants disappear. + mock.state.info.grants = []; + const restarted = context(dst, mock.http); + assert.deepEqual(await removeFountain(restarted, f), blocked); + assert.equal( + (await refreshFountain(restarted, f)).collectionPending, + false, + ); + assert.equal(mock.state.signatures, 2); + assert.deepEqual(mock.requests[0], mock.requests[1]); + assert.equal( + (await dst.runReadWriteTx((tx) => tx.listTokens())).length, + 2, + ); + assert.equal( + (await dst.runReadWriteTx((tx) => tx.getFountain(f.fountainId))) + ?.pending, + undefined, + ); + const stats = (await listFountains(restarted)).fountains[0].statistics; + assert.equal(stats!.families[0].receivedFromFountain, 2); + await refreshFountain(restarted, f); + assert.deepEqual( + (await listFountains(restarted)).fountains[0].statistics, + stats, + ); + const copy = await dst.exportDatabase(); + await dst.importDatabase(copy, async () => {}); + assert.deepEqual( + (await listFountains(restarted)).fountains[0].statistics, + stats, + ); + assert.equal( + (await dst.runReadWriteTx((tx) => tx.listTokens())).length, + 2, + ); + } finally { + await db.close(); + await dst.close(); + } + }); + test(`${makeDb.name}: receipt history is independent of wallet-wide usable supply`, async () => { + const db = await makeDb(); + try { + const mock = issuer(), + wex = context(db, mock.http); + const notifications: WalletNotification[] = []; + db.setNotificationSink((n) => notifications.push(n)); + const f = await importFountain(wex, { talerFountainUri: uri }); + await refreshFountain(wex, f); + const token = (await db.runReadWriteTx((tx) => tx.listTokens()))[0]; + await db.runReadWriteTx(async (tx) => { + // A replacement, a different fountain, and an unrelated merchant. + await tx.upsertToken({ + ...token, + tokenUsePub: encodeCrock(new Uint8Array(32).fill(1)), + fountainId: undefined, + purchaseId: "purchase", + }); + await tx.upsertToken({ + ...token, + tokenUsePub: encodeCrock(new Uint8Array(32).fill(2)), + fountainId: "other", + }); + await tx.upsertToken({ + ...token, + tokenUsePub: encodeCrock(new Uint8Array(32).fill(3)), + merchantBaseUrl: "https://elsewhere.example/", + }); + await tx.upsertToken({ + ...token, + tokenUsePub: encodeCrock(new Uint8Array(32).fill(4)), + transactionId: "payment", + }); + await tx.upsertToken({ + ...token, + tokenUsePub: encodeCrock(new Uint8Array(32).fill(5)), + validAfter: timestampProtocolToDb({ t_s: start + 3600 }), + }); + await tx.upsertToken({ + ...token, + tokenUsePub: encodeCrock(new Uint8Array(32).fill(6)), + validBefore: timestampProtocolToDb({ t_s: start }), + }); + }); + let details = (await listFountains(wex)).fountains[0]; + assert.deepEqual(details.statistics!.families[0], { + tokenFamilySlug: "discount", + kind: "discount", + name: "Student discount", + receivedFromFountain: 2, + availableInWallet: 4, + futureInWallet: 1, + }); + mock.state.info.grants = []; + details = await refreshFountain(wex, f); + assert.equal(details.grants.length, 0); + assert.equal(details.statistics!.families[0].receivedFromFountain, 2); + assert.equal(details.statistics!.families[0].availableInWallet, 4); + await removeFountain(wex, f); + assert.ok(notifications.length >= 3); + assert.ok( + notifications.every((n) => n.type === NotificationType.FountainChanged), + ); + assert.ok(!JSON.stringify(notifications).includes(secret)); + assert.deepEqual(notifications.at(-1), { + type: NotificationType.FountainChanged, + fountainId: f.fountainId, + }); + } finally { + await db.close(); + } + }); + test(`${makeDb.name}: old fountains start exact tracking without backfilling quotas`, async () => { + const db = await makeDb(); + try { + const mock = issuer(), + wex = context(db, mock.http); + const f = await importFountain(wex, { talerFountainUri: uri }); + await refreshFountain(wex, f); + await db.runReadWriteTx(async (tx) => { + const r = (await tx.getFountain(f.fountainId))!; + delete r.receipts; + await tx.upsertFountain(r); + }); + const legacy = (await listFountains(wex)).fountains[0].statistics!; + assert.equal(legacy.historyComplete, false); + assert.equal(legacy.families[0].receivedFromFountain, 0); + assert.equal(legacy.families[0].availableInWallet, 2); + assert.deepEqual( + (await listFountains(wex)).fountains[0].statistics, + legacy, + ); + const tokens = await db.runReadWriteTx((tx) => tx.listTokens()); + await db.runReadWriteTx((tx) => tx.deleteToken(tokens[0].tokenUsePub)); + const updated = (await refreshFountain(wex, f)).statistics!; + assert.equal(updated.families[0].receivedFromFountain, 1); + assert.equal(updated.families[0].availableInWallet, 2); + assert.equal(updated.historyComplete, false); + assert.deepEqual(updated.trackingSince, legacy.trackingSince); + } finally { + await db.close(); + } + }); + test(`${makeDb.name}: a failed receipt commit rolls back tokens and totals`, async () => { + const db = await makeDb(); + try { + const mock = issuer(), + wex = context(db, mock.http); + const f = await importFountain(wex, { talerFountainUri: uri }); + let fail = true; + wex.runWalletDbTx = (callback) => + db.runReadWriteTx((tx) => + callback( + new Proxy(tx, { + get(target, property) { + if (property === "upsertFountain") + return async ( + record: Parameters<typeof tx.upsertFountain>[0], + ) => { + if ( + fail && + record.receipts?.families.some( + (family) => family.received > 0, + ) + ) { + fail = false; + throw Error("simulated commit failure"); + } + return tx.upsertFountain(record); + }; + const value = Reflect.get(target, property); + return typeof value === "function" ? value.bind(target) : value; + }, + }), + ), + ); + await assert.rejects(refreshFountain(wex, f), /saved request/); + assert.equal( + (await db.runReadWriteTx((tx) => tx.listTokens())).length, + 0, + ); + assert.equal( + (await listFountains(wex)).fountains[0].statistics!.families[0] + .receivedFromFountain, + 0, + ); + assert.ok( + (await db.runReadWriteTx((tx) => tx.getFountain(f.fountainId)))! + .pending, + ); + const recovered = await refreshFountain(wex, f); + assert.equal(recovered.statistics!.families[0].receivedFromFountain, 2); + assert.equal(recovered.statistics!.families[0].availableInWallet, 2); + assert.equal(mock.state.signatures, 2); + const converted = await makeDb(); + try { + await convertWalletDb(db, converted); + assert.deepEqual( + (await listFountains(context(converted, mock.http))).fountains[0] + .statistics, + recovered.statistics, + ); + } finally { + await converted.close(); + } + } finally { + await db.close(); + } + }); + test(`${makeDb.name}: invalid result remains pending; revocation preserves issued tokens`, async () => { + const db = await makeDb(); + try { + const mock = issuer(), + wex = context(db, mock.http); + mock.state.corrupt = true; + const f = await importFountain(wex, { talerFountainUri: uri }); + await assert.rejects(refreshFountain(wex, f), /does not match/); + assert.equal( + (await db.runReadWriteTx((tx) => tx.listTokens())).length, + 0, + ); + mock.state.corrupt = false; + mock.state.corruptSignature = true; + await assert.rejects(refreshFountain(wex, f), /saved request/); + assert.equal( + (await db.runReadWriteTx((tx) => tx.listTokens())).length, + 0, + ); + mock.state.corruptSignature = false; + await refreshFountain(wex, f); + mock.state.revoked = true; + const revoked = await refreshFountain(wex, f); + assert.equal(revoked.status, "revoked"); + assert.equal(revoked.collectionPending, false); + assert.ok(!JSON.stringify(revoked).includes(secret)); + assert.equal( + (await db.runReadWriteTx((tx) => tx.listTokens())).length, + 2, + ); + } finally { + await db.close(); + } + }); } test("refreshFountain returns typed errors for documented and unknown merchant codes", async (t) => { @@ -455,3 +803,195 @@ test("fountain diagnostics omit credentials echoed by the HTTP client", async () await db.close(); } }); + +test("fountain empty grants stay active; quota backs off until allowance changes", async () => { + const db = await makeSqliteRunner(); + try { + const mock = issuer(), + wex = context(db, mock.http); + mock.state.info.grants = []; + const f = await importFountain(wex, { talerFountainUri: uri }); + assert.equal((await refreshFountain(wex, f)).status, "active"); + assert.equal(mock.requests.length, 0); + mock.state.info = info(); + mock.state.quota = true; + await refreshFountain(wex, f); + await refreshFountain(wex, f); + assert.deepEqual( + mock.requests.map((r) => r.grants[0].envelopes.length), + [2, 1], + ); + mock.state.info.grants[0].tokens_per_period_limit = 4; + mock.state.quota = false; + await refreshFountain(wex, f); + assert.equal(mock.state.signatures, 2); + (wex.ws as { networkAvailable: boolean }).networkAvailable = false; + assert.equal( + (await processFountain(wex, f.fountainId)).type, + TaskRunResultType.NetworkRequired, + ); + } finally { + await db.close(); + } +}); + +test("fountain batches cap at 64 and stock future subscription slots", async () => { + const db = await makeSqliteRunner(); + try { + const mock = issuer(), + wex = context(db, mock.http); + mock.state.info = info(65, 65); + mock.state.info.poll_freq = { d_us: "forever" }; + const g = mock.state.info.grants[0]; + g.key_window_size = 1; + g.token_family.details = { + class: MerchantContractTokenKind.Subscription, + trusted_domains: [], + }; + // Each period has an independently generated issue key. + g.token_family.keys.push({ + ...g.token_family.keys[0], + rsa_pub: nextKey.rsaPub, + cipher: "RSA", + signature_validity_start: { t_s: start + 86400 }, + signature_validity_end: { t_s: start + 172800 }, + }); + const f = await importFountain(wex, { talerFountainUri: uri }); + assert.equal((await refreshFountain(wex, f)).collectionPending, true); + assert.equal(mock.requests.length, 2); + assert.equal(mock.state.signatures, 128); + await processFountain(wex, f.fountainId); + assert.equal( + mock.http.requests.filter((r) => r.method === "GET").length, + 1, + ); + assert.equal( + (await listFountains(wex)).fountains[0].collectionPending, + false, + ); + assert.equal(mock.state.signatures, 130); + assert.equal((await listSubscriptions(wex)).subscriptions.length, 1); + } finally { + await db.close(); + } +}); + +test("failed token commit preserves the complete journal and quota for retry", async () => { + const db = await makeSqliteRunner(); + try { + const mock = issuer(), + wex = context(db, mock.http); + const f = await importFountain(wex, { talerFountainUri: uri }); + let writes = 0; + wex.runWalletDbTx = (fn) => + db.runReadWriteTx((tx) => { + const put = tx.upsertToken.bind(tx); + tx.upsertToken = async (record) => { + await put(record); + if (++writes === 2) throw Error("simulated commit failure"); + }; + return fn(tx); + }); + await assert.rejects(refreshFountain(wex, f), /saved request/); + assert.equal((await db.runReadWriteTx((tx) => tx.listTokens())).length, 0); + const saved = await db.runReadWriteTx((tx) => tx.getFountain(f.fountainId)); + assert.ok(saved?.pending); + assert.equal( + Object.values(saved.slots).reduce((n, s) => n + s.issued, 0), + 0, + ); + wex.runWalletDbTx = db.runReadWriteTx.bind(db); + await refreshFountain(wex, f); + assert.equal(mock.state.signatures, 2); + assert.equal((await db.runReadWriteTx((tx) => tx.listTokens())).length, 2); + } finally { + await db.close(); + } +}); + +test("expired pending withdrawal is retired without submitting new envelopes", async () => { + const db = await makeSqliteRunner(); + try { + const mock = issuer(), + wex = context(db, mock.http); + const f = await importFountain(wex, { talerFountainUri: uri }); + mock.state.failAfterSigning = true; + await assert.rejects(refreshFountain(wex, f)); + await db.runReadWriteTx(async (tx) => { + const r = (await tx.getFountain(f.fountainId))!; + r.pending!.expires = Date.now() - 1; + await tx.upsertFountain(r); + }); + mock.state.info.grants = []; + await refreshFountain(wex, f); + assert.equal(mock.requests.length, 1); + assert.equal( + (await db.runReadWriteTx((tx) => tx.getFountain(f.fountainId)))?.pending, + undefined, + ); + } finally { + await db.close(); + } +}); + +test("a shared grant yields the remaining token after a rejected batch", async () => { + const db = await makeSqliteRunner(); + try { + const mock = issuer(), + wex = context(db, mock.http); + mock.state.remaining = 1; + const f = await importFountain(wex, { talerFountainUri: uri }); + const result = await refreshFountain(wex, f); + assert.equal(result.statistics!.families[0].availableInWallet, 1); + assert.equal(result.quotas![0].limitReached, false); + assert.deepEqual( + mock.requests.map((r) => r.grants[0].envelopes.length), + [2, 1], + ); + assert.equal((await refreshFountain(wex, f)).quotas![0].limitReached, true); + } finally { + await db.close(); + } +}); + +test( + "a slow withdrawal allows listing and concurrent stocking without duplicate issuance", + { timeout: 10000 }, + async () => { + const db = await makeSqliteRunner(), + release = openPromise<void>(), + started = openPromise<void>(); + try { + const mock = issuer(), + wex = context(db, mock.http); + const a = await importFountain(wex, { talerFountainUri: uri }); + const b = await importFountain(wex, { + talerFountainUri: uri.replace("/default/fountain/", "/default/second/"), + }); + const fetch = mock.http.fetch.bind(mock.http); + mock.http.fetch = async (url, opts) => { + if (opts?.method === "POST") { + started.resolve(); + await release.promise; + } + return fetch(url, opts); + }; + const slow = refreshFountain(wex, a); + await started.promise; + assert.equal((await listFountains(wex)).fountains.length, 2); + const second = await refreshFountain(wex, b); + assert.equal(second.quotas![0].issued, 0); + await removeFountain(wex, b); + const removal = removeFountain(wex, a); + release.resolve(); + // The queued deletion can win the race with refresh's final details read. + await Promise.allSettled([slow]); + await removal; + assert.equal(mock.state.signatures, 2); + assert.equal((await listFountains(wex)).fountains.length, 0); + } finally { + release.resolve(); + await db.close(); + } + }, +);