commit 3a4a31f13d1600a6e29e3ffa1820080538e9deb5 parent bb3ff21d0ee61c0740cb4c396451ef98a065e5f1 Author: Florian Dold <dold@taler.net> Date: Thu, 24 Sep 2026 22:27:59 +0200 wallet-core: store fountain credentials and tokens without a purchase Carry the fountain record and pending withdrawal through SQLite, IndexedDB and database conversion. Give fountain tokens their own planchet derivation and reuse signature validation when accepting tokens from either source. Diffstat:
19 files changed, 661 insertions(+), 119 deletions(-)
diff --git a/packages/taler-util/src/index.ts b/packages/taler-util/src/index.ts @@ -117,3 +117,4 @@ export * from "./result.js"; export * from "./user-attention.js"; export * from "./challenge-confirmation.js"; export * from "./types-taler-fountain.js"; +export * from "./types-wallet-fountain.js"; diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -1483,6 +1483,15 @@ export interface Slate { blindingKey: string; } +export type TokenPlanchet = Omit<Slate, "tokenWalletData">; +export interface TokenPlanchetCreationRequest { + secretSeed: string; + outputIndex: number; + repeatIndex: number; + tokenIssuePub: TokenIssuePublicKey; + purpose: "payment" | "fountain"; +} + export interface SlateCreationRequest { secretSeed: string; choiceIndex: number; diff --git a/packages/taler-util/src/types-wallet-fountain.ts b/packages/taler-util/src/types-wallet-fountain.ts @@ -0,0 +1,129 @@ +/* + 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 Affero 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 Affero General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + + SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { + buildCodecForObject, + codecOptional, + codecForStringEnum, + codecForString, +} from "./codec.js"; +import { + FountainPurpose, + FountainWalletGrant, +} from "./types-taler-fountain.js"; +import { InternationalizedString } from "./types-taler-common.js"; +import { TalerProtocolDuration, TalerProtocolTimestamp } from "./time.js"; +import { TalerErrorDetail } from "./types-taler-wallet.js"; + +export interface ImportFountainRequest { + talerFountainUri: string; +} +/** Local wallet identifier; distinct from the merchant's fountain_id. */ +export interface FountainRequest { + fountainId: string; +} +export interface RemoveFountainRequest extends FountainRequest { + /** Explicitly abandon only the withdrawal identified by a prior removal attempt. */ + discardPendingWithdrawalId?: string; +} +export type RemoveFountainResponse = + | { status: "removed" } + | { status: "withdrawalPending"; pendingWithdrawalId: string }; + +export interface FountainReceiptFamily { + tokenFamilySlug: string; + kind: "discount" | "subscription"; + name: string; + /** Direct fountain receipts since tracking began, including tokens later spent or expired. */ + received: number; +} +export interface FountainReceiptStats { + trackingSince: TalerProtocolTimestamp; + /** False for fountains imported before receipt tracking was available. */ + historyComplete: boolean; + families: FountainReceiptFamily[]; +} +export interface FountainTokenStatistics extends Omit< + FountainReceiptFamily, + "received" +> { + /** Direct receipts from this fountain since tracking began, including spent or expired tokens. */ + receivedFromFountain: number; + /** Wallet-wide supply for this merchant/family, excluding reserved tokens. */ + availableInWallet: number; + /** Unreserved tokens whose validity has not started yet. */ + futureInWallet: number; +} +export interface FountainPeriodQuota { + tokenFamilySlug: string; + validityStart: TalerProtocolTimestamp; + validityEnd: TalerProtocolTimestamp; + /** Issuance known to this wallet, not usage by other holders of the credential. */ + issued: number; + limitReached: boolean; +} +export interface FountainDetails { + fountainId: string; + merchantBaseUrl: string; + merchantFountainId: string; + /** Merchant's display name, falling back to merchantFountainId. */ + name: string; + nameI18n?: InternationalizedString; + extraData?: Record<string, unknown>; + /** Recognized fountain_purpose from the last successful merchant info poll. */ + purpose?: FountainPurpose; + /** Active means enabled locally. A newly imported credential awaits its first merchant poll. */ + status: "active" | "revoked"; + /** True while the first poll, a saved withdrawal, or a further stocking pass is outstanding. + * Scheduled future polls alone do not set this flag. */ + collectionPending: boolean; + grants: FountainWalletGrant[]; + /** Most recent successful metadata poll. Absent until the wallet has fetched valid grants. */ + lastPoll?: TalerProtocolTimestamp; + nextPoll: TalerProtocolTimestamp; + lastError?: TalerErrorDetail; + pollFrequency?: TalerProtocolDuration; + statistics?: Omit<FountainReceiptStats, "families"> & { + families: FountainTokenStatistics[]; + }; + quotas?: FountainPeriodQuota[]; +} +export interface ListFountainsRequest { + /** Only include fountains with this purpose. Omit to include every fountain. */ + purpose?: FountainPurpose; +} +export interface ListFountainsResponse { + fountains: FountainDetails[]; +} +export const codecForListFountainsRequest = () => + buildCodecForObject<ListFountainsRequest>() + .property("purpose", codecOptional(codecForStringEnum(FountainPurpose))) + .build("ListFountainsRequest"); +export const codecForImportFountainRequest = () => + buildCodecForObject<ImportFountainRequest>() + .property("talerFountainUri", codecForString()) + .build("ImportFountainRequest"); +export const codecForFountainRequest = () => + buildCodecForObject<FountainRequest>() + .property("fountainId", codecForString()) + .build("FountainRequest"); +export const codecForRemoveFountainRequest = () => + buildCodecForObject<RemoveFountainRequest>() + .property("fountainId", codecForString()) + .property("discardPendingWithdrawalId", codecOptional(codecForString())) + .build("RemoveFountainRequest"); diff --git a/packages/taler-wallet-core/src/crypto/cryptoImplementation.ts b/packages/taler-wallet-core/src/crypto/cryptoImplementation.ts @@ -25,6 +25,8 @@ */ import { + TokenPlanchet, + TokenPlanchetCreationRequest, AgeCommitmentProof, AgeRestriction, assertUnreachable, @@ -87,7 +89,6 @@ import { MakeSyncSignatureRequest, MerchantContractOutputType, MerchantContractTermsV1, - PayWalletData, PlanchetCreationRequest, PlanchetUnblindInfo, PurseDeposit, @@ -312,6 +313,10 @@ export interface TalerCryptoInterface { /** * Create a pre-token (a.k.a. slate) of a given token family. */ + createTokenPlanchet( + req: TokenPlanchetCreationRequest, + ): Promise<TokenPlanchet>; + createSlate(req: SlateCreationRequest): Promise<Slate>; signTokenUse(req: SignTokenUseRequest): Promise<EddsaSigningResult>; @@ -547,6 +552,11 @@ export const nullCrypto: TalerCryptoInterface = { eddsaSign: function (req: EddsaSignRequest): Promise<EddsaSignResponse> { throw new Error("Function not implemented."); }, + createTokenPlanchet: function ( + _req: TokenPlanchetCreationRequest, + ): Promise<TokenPlanchet> { + throw new Error("Function not implemented."); + }, createSlate: function (req: SlateCreationRequest): Promise<Slate> { throw new Error("Function not implemented."); }, @@ -1513,16 +1523,20 @@ export const nativeCryptoR: TalerCryptoInterfaceR = { }; }, - async createSlate( + async createTokenPlanchet( tci: TalerCryptoInterfaceR, - req: SlateCreationRequest, - ): Promise<Slate> { + req: TokenPlanchetCreationRequest, + ): Promise<TokenPlanchet> { if (req.tokenIssuePub.cipher !== DenomKeyType.Rsa) { throw Error(`unsupported cipher (${req.tokenIssuePub.cipher})`); } // token generation - const info = stringToBytes("taler-payment-token-derivation"); + const info = stringToBytes( + req.purpose === "payment" + ? "taler-payment-token-derivation" + : "taler-fountain-token-derivation", + ); const saltArrBuf = new ArrayBuffer(8); const salt = new Uint8Array(saltArrBuf); const saltDataView = new DataView(saltArrBuf); @@ -1557,29 +1571,37 @@ export const nativeCryptoR: TalerCryptoInterfaceR = { const tokenIssuePubHash = hashTokenIssuePub(req.tokenIssuePub); const evHash = hashTokenEv(tokenEv, encodeCrock(tokenIssuePubHash)); - const tokenEvs = collectSlateTokenEnvelopes( - req.contractTerms, - req.choiceIndex, - ); - - // wallet data object with envelopes - const tokenWalletData: PayWalletData = { - choice_index: req.choiceIndex, - tokens_evs: tokenEvs, - }; - return { tokenPub: tokenPubRes.pub, tokenPriv: tokenPrivEnc, tokenIssuePub: req.tokenIssuePub, tokenIssuePubHash: encodeCrock(tokenIssuePubHash), - tokenWalletData, tokenEv, tokenEvHash: encodeCrock(evHash), blindingKey: bks, }; }, + async createSlate( + tci: TalerCryptoInterfaceR, + req: SlateCreationRequest, + ): Promise<Slate> { + const planchet = await tci.createTokenPlanchet(tci, { + ...req, + purpose: "payment", + }); + return { + ...planchet, + tokenWalletData: { + choice_index: req.choiceIndex, + tokens_evs: collectSlateTokenEnvelopes( + req.contractTerms, + req.choiceIndex, + ), + }, + }; + }, + async signTokenUse( tci: TalerCryptoInterfaceR, req: SignTokenUseRequest, diff --git a/packages/taler-wallet-core/src/db/indexeddb/database.test.ts b/packages/taler-wallet-core/src/db/indexeddb/database.test.ts @@ -323,39 +323,56 @@ test("an aborted transaction without pending requests settles its promise", asyn } }); -test("upgrading a wallet keeps the legacy userAttention store and its rows separate", async () => { - const sqlite = await createNodeHelperSqlite3Impl({ enableTracing: false }); - const backend = await createSqliteBackend(sqlite, { filename: ":memory:" }); - const factory = new BridgeIDBFactory(backend); - const legacy = { entityId: "old", info: { type: "exchange-tos-changed" } }; - const previous = await openDatabase( - factory, - TALER_WALLET_MAIN_DB_NAME, - 36, - () => {}, - (db) => { - for (const store of Object.values(WalletIndexedDbStoresV1)) { - if ((store.store.versionAdded ?? 0) > 36) continue; - const s = db.createObjectStore(store.storeName, { - keyPath: store.store.keyPath, - autoIncrement: store.store.autoIncrement, - }); - if (store.storeName === "userAttention") s.put(legacy); - } - }, - ); - previous.close(); - const upgraded = await openTalerDatabase(factory, () => {}); - upgraded.close(); - const dump = await exportSingleDb(factory, TALER_WALLET_MAIN_DB_NAME); - assert.deepEqual(dump.stores.userAttention.keyPath, [ - "entityId", - "info.type", - ]); - assert.deepEqual( - dump.stores.userAttention.records.map((row) => structuredRevive(row.value)), - [legacy], - ); - assert.deepEqual(dump.stores.userAttentionItems.records, []); - assert.equal(dump.stores.userAttentionItems.keyPath, "sourceKey"); -}); +for (const version of [36, 37]) { + test(`upgrading a version ${version} wallet preserves legacy attention and fountain records`, async () => { + const sqlite = await createNodeHelperSqlite3Impl({ enableTracing: false }); + const backend = await createSqliteBackend(sqlite, { filename: ":memory:" }); + const factory = new BridgeIDBFactory(backend); + const fountain = { + fountainId: "test", + pending: { id: "withdrawal-in-progress" }, + }; + const legacy = { entityId: "old", info: { type: "exchange-tos-changed" } }; + const previous = await openDatabase( + factory, + TALER_WALLET_MAIN_DB_NAME, + version, + () => {}, + (db) => { + if (version === 37) { + db.createObjectStore("fountains", { keyPath: "fountainId" }).put( + fountain, + ); + } + for (const store of Object.values(WalletIndexedDbStoresV1)) { + if ((store.store.versionAdded ?? 0) > 36) continue; + const s = db.createObjectStore(store.storeName, { + keyPath: store.store.keyPath, + autoIncrement: store.store.autoIncrement, + }); + if (store.storeName === "userAttention") s.put(legacy); + } + }, + ); + previous.close(); + const upgraded = await openTalerDatabase(factory, () => {}); + upgraded.close(); + const dump = await exportSingleDb(factory, TALER_WALLET_MAIN_DB_NAME); + assert.deepEqual(dump.stores.userAttention.keyPath, [ + "entityId", + "info.type", + ]); + assert.deepEqual( + dump.stores.userAttention.records.map((row) => + structuredRevive(row.value), + ), + [legacy], + ); + assert.deepEqual( + dump.stores.fountains.records.map((row) => structuredRevive(row.value)), + version === 37 ? [fountain] : [], + ); + assert.deepEqual(dump.stores.userAttentionItems.records, []); + assert.equal(dump.stores.userAttentionItems.keyPath, "sourceKey"); + }); +} diff --git a/packages/taler-wallet-core/src/db/indexeddb/database.ts b/packages/taler-wallet-core/src/db/indexeddb/database.ts @@ -203,10 +203,14 @@ function onTalerDbUpgradeNeeded( newVersion: number, upgradeTransaction: IDBTransaction, ) { + // Early fountain wallets and inbox wallets independently used version 37. + // Recheck stores and indexes added since their last shared version. + const earlyFountains = + oldVersion === 37 && db.objectStoreNames.contains("fountains"); upgradeFromStoreMap( WalletIndexedDbStoresV1, db, - oldVersion, + earlyFountains ? 36 : oldVersion, newVersion, upgradeTransaction, ); diff --git a/packages/taler-wallet-core/src/db/indexeddb/schema.ts b/packages/taler-wallet-core/src/db/indexeddb/schema.ts @@ -77,6 +77,7 @@ import { WalletRefundItem, WalletReserve, WalletSlate, + WalletFountain, WalletToken, WalletTombstone, WalletTransactionMeta, @@ -172,7 +173,7 @@ export const TALER_WALLET_DB_GENERATION_PREFIX = `${TALER_WALLET_MAIN_DB_NAME}-g * backwards-compatible way or object stores and indices * are added. */ -export const WALLET_DB_MINOR_VERSION = 37; +export const WALLET_DB_MINOR_VERSION = 38; export interface BankWithdrawUriRecord { /** @@ -710,6 +711,14 @@ export const WalletIndexedDbStoresV1 = { ), }, ), + fountains: describeStore( + "fountains", + describeContents<WalletFountain>({ + keyPath: "fountainId", + versionAdded: 38, + }), + {}, + ), tokens: describeStore( "tokens", describeContents<WalletToken>({ diff --git a/packages/taler-wallet-core/src/db/indexeddb/transaction.ts b/packages/taler-wallet-core/src/db/indexeddb/transaction.ts @@ -43,6 +43,7 @@ import { WalletPeerPushDebit, WalletPeerPushCredit, WalletPeerPullDebit, + WalletFountain, WalletToken, WalletSlate, WalletDenomination, @@ -173,6 +174,7 @@ export class IdbWalletTransaction implements WalletDbTransaction { coinHistory: "coinHistory", coinAvailability: "coinAvailabilityV2", refundGroups: "refundGroups", + fountains: "fountains", tokens: "tokens", slates: "slates", depositGroups: "depositGroups", @@ -1696,6 +1698,19 @@ export class IdbWalletTransaction implements WalletDbTransaction { await tx.coinHistory.put(rec); } + async listFountains(): Promise<WalletFountain[]> { + return this.tx.fountains.getAll(); + } + async getFountain(id: string): Promise<WalletFountain | undefined> { + return this.tx.fountains.get(id); + } + async upsertFountain(record: WalletFountain): Promise<void> { + await this.tx.fountains.put(record); + } + async deleteFountain(id: string): Promise<void> { + await this.tx.fountains.delete(id); + } + async listTokens(): Promise<WalletToken[]> { const tx = this.tx; return await tx.tokens.getAll(); diff --git a/packages/taler-wallet-core/src/db/migration/converter.test.ts b/packages/taler-wallet-core/src/db/migration/converter.test.ts @@ -1352,6 +1352,7 @@ test("converter: the copy plan covers every table in the schema", async () => { global_currency_exchanges: "globalCurrencyExchanges", global_currency_auditors: "globalCurrencyAuditors", bank_accounts: "bankAccounts", + fountains: "fountains", tokens: "tokens", slates: "slates", refresh_sessions: "refreshSessions", diff --git a/packages/taler-wallet-core/src/db/migration/converter.ts b/packages/taler-wallet-core/src/db/migration/converter.ts @@ -455,6 +455,11 @@ const COPY_PLAN: CopyStep[][] = [ (tx, r) => tx.upsertRefundGroup(r), ), step( + "fountains", + (tx) => tx.listFountains(), + (tx, r) => tx.upsertFountain(r), + ), + step( "tokens", (tx) => tx.listTokens(), (tx, r) => tx.upsertToken(r), diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -15,6 +15,10 @@ */ import { + FountainDetails, + FountainReceiptStats, + FountainInfoResponse, + FountainGrantWithdrawal, AmountString, RefundPaymentInfo, ObservedBankWithdrawal, @@ -2997,7 +3001,10 @@ export interface WalletToken extends TokenFamilyInfo { /** * Source purchase of the token. */ - purchaseId: string; + purchaseId?: string; + + /** Source fountain, when issued without a purchase. */ + fountainId?: string; /** * Transaction where token is being used. @@ -3100,7 +3107,10 @@ export interface WalletSlate extends TokenFamilyInfo { /** * Source purchase of the token. */ - purchaseId: string; + purchaseId?: string; + + /** Source fountain, when issued without a purchase. */ + fountainId?: string; /** * Transaction where token is being used. @@ -3345,3 +3355,38 @@ export namespace WalletDenomination { }; } } + +/** DD98 credential and durable withdrawal journal. Never expose this record to hosts. */ +export interface WalletFountain { + /** Durable receipt totals, independent of expiring quota slots and token usage. */ + receipts?: FountainReceiptStats; + fountainId: string; + merchantBaseUrl: string; + merchantFountainId: string; + secret: string; + status: FountainDetails["status"]; + /** Last successful info poll, including the merchant's extra_data.fountain_purpose. */ + info?: FountainInfoResponse; + /** Milliseconds since epoch; MAX_SAFE_INTEGER means never. */ + lastPoll?: number; + nextPoll: number; + /** More bounded batches are needed before the next metadata poll. */ + needsStocking?: boolean; + lastError?: TalerErrorDetail; + /** Keyed by issue-key hash. Keep counts even after tokens are spent. */ + slots: Record< + string, + { + issued: number; + expires: number; + blockedAtLimit?: number; + rejectedGrant?: string; + } + >; + pending?: { + id: string; + request: FountainGrantWithdrawal; + slates: WalletSlate[]; + expires: number; + }; +} diff --git a/packages/taler-wallet-core/src/db/sqlite/database.ts b/packages/taler-wallet-core/src/db/sqlite/database.ts @@ -210,7 +210,22 @@ export async function initSqliteWalletDb( const recorded = await ( await db.prepare("SELECT version, name FROM schema_migrations") ).getAll(); + // Earlier fountain builds used 30 or 32 for the same DDL as migration 33. + const earlyFountains = recorded.find( + (row) => + [30, 32].includes(Number(row.version)) && + row.name === "token-fountains", + ); + if (earlyFountains) earlyFountains.version = 33; validateAppliedSchemaMigrations(recorded, migrations); + if (earlyFountains) { + await ( + await db.prepare( + "UPDATE schema_migrations SET version = 33" + + " WHERE version IN (30, 32) AND name = 'token-fountains'", + ) + ).run({}); + } } // WAL: readers do not block the writer, and a commit appends to the log // instead of fsyncing the whole database. diff --git a/packages/taler-wallet-core/src/db/sqlite/schema-migrations.test.ts b/packages/taler-wallet-core/src/db/sqlite/schema-migrations.test.ts @@ -988,3 +988,120 @@ test("refund snapshot backfill reads purchases from an upgraded database", async cleanup(); } }); + +test("fountain migration preserves purchase tokens and slates while allowing fountain origins", async () => { + const { path, cleanup } = withTempDb(); + try { + let db = await openRaw(path); + await initSqliteWalletDb( + db, + schemaMigrations.filter((x) => x.version < 33), + ); + for (const table of ["tokens", "slates"]) { + const columns = await queryAll(db, `PRAGMA table_info(${table})`); + const required = columns.filter((c) => c.notnull || c.pk); + const values = required.map((c) => + c.name === "purchase_id" + ? "'existing-purchase'" + : c.type === "BLOB" + ? "X'010203'" + : c.type === "INTEGER" + ? "1" + : "'{}'", + ); + await ( + await db.prepare( + `INSERT INTO ${table} (${required.map((c) => c.name).join(",")}) VALUES (${values.join(",")})`, + ) + ).run(); + } + const before = await queryAll(db, "SELECT * FROM tokens"); + const slates = await queryAll(db, "SELECT * FROM slates"); + await db.close(); + db = await openRaw(path); + await initSqliteWalletDb(db); + assert.deepEqual( + await queryAll(db, "SELECT * FROM slates"), + slates.map((s) => ({ ...s, fountain_id: null })), + ); + const after = await queryAll(db, "SELECT * FROM tokens"); + assert.deepStrictEqual( + after, + before.map((r) => ({ ...r, fountain_id: null })), + ); + for (const table of ["tokens", "slates"]) { + await ( + await db.prepare( + `UPDATE ${table} SET purchase_id = NULL, fountain_id = 'promotion'`, + ) + ).run(); + const rows = await queryAll( + db, + `SELECT purchase_id, fountain_id FROM ${table}`, + ); + assert.deepStrictEqual(rows, [ + { purchase_id: null, fountain_id: "promotion" }, + ]); + } + await db.close(); + } finally { + cleanup(); + } +}); + +for (const version of [30, 32]) { + test(`an early v${version} fountain wallet keeps its pending withdrawal on upgrade`, async () => { + const { path, cleanup } = withTempDb(); + try { + const db = await openRaw(path); + await initSqliteWalletDb( + db, + schemaMigrations.filter((m) => m.version < version || m.version === 33), + ); + await db.exec( + `UPDATE schema_migrations SET version = ${version} WHERE name = 'token-fountains'`, + ); + await db.exec(`PRAGMA user_version = ${version}`); + const payload = JSON.stringify({ + pending: { id: "withdrawal-in-progress" }, + }); + await ( + await db.prepare( + "INSERT INTO fountains(fountain_id, payload) VALUES ('test', $payload)", + ) + ).run({ payload }); + await db.close(); + + const upgraded = await openRaw(path); + try { + await initSqliteWalletDb(upgraded); + await initSqliteWalletDb(upgraded); + assert.deepEqual( + await queryAll(upgraded, "SELECT payload FROM fountains"), + [{ payload }], + ); + assert.deepEqual( + await queryAll(upgraded, "SELECT * FROM user_attention_items"), + [], + ); + const applied = await queryAll( + upgraded, + "SELECT name FROM schema_migrations WHERE version >= 30 ORDER BY version", + ); + assert.deepEqual( + applied.slice(0, 4).map((r) => r.name), + [ + "user-attention", + "refund-purchase-snapshots", + "refresh-cs-r-pubs", + "token-fountains", + ], + ); + } finally { + await upgraded.close(); + } + } finally { + cleanup(); + } + }); +} diff --git a/packages/taler-wallet-core/src/db/sqlite/schema.ts b/packages/taler-wallet-core/src/db/sqlite/schema.ts @@ -85,11 +85,11 @@ * * Bump this when adding a migration to {@link schemaMigrations}. */ -export const SQLITE_SCHEMA_VERSION = 32; +export const SQLITE_SCHEMA_VERSION = 33; // v29 and v30 backups have compatible row formats. Missing attention data // starts empty, and refund snapshot columns added by v31 remain NULL. -export const SQLITE_BACKUP_VERSIONS = [29, 30, SQLITE_SCHEMA_VERSION]; +export const SQLITE_BACKUP_VERSIONS = [29, 30, 32, SQLITE_SCHEMA_VERSION]; /** * Tables of the IndexedDB emulation, children before parents. @@ -1619,6 +1619,93 @@ export const schemaMigrations: SchemaMigration[] = [ name: "refresh-cs-r-pubs", statements: ["ALTER TABLE refresh_sessions ADD COLUMN cs_r_pubs TEXT"], }, + { + version: 33, + name: "token-fountains", + statements: [ + `CREATE TABLE fountains (fountain_id TEXT PRIMARY KEY NOT NULL, payload TEXT NOT NULL)`, + `CREATE TABLE tokens_fountain_migration ( + token_use_pub BLOB PRIMARY KEY, + token_use_priv BLOB NOT NULL, + purchase_id TEXT, + transaction_id TEXT, + choice_index INTEGER, + output_index INTEGER, + repeat_index INTEGER, + merchant_base_url TEXT NOT NULL, + kind TEXT NOT NULL, + token_issue_pub_hash BLOB NOT NULL, + token_family_hash BLOB, + valid_after INTEGER NOT NULL, + valid_before INTEGER NOT NULL, + -- JSON: UnblindedDenominationSignature + token_issue_sig TEXT NOT NULL, + -- JSON: TokenUseSig + token_use_sig TEXT, + -- JSON: TokenEnvelope + token_ev TEXT NOT NULL, + token_ev_hash BLOB NOT NULL, + blinding_key BLOB NOT NULL, + -- Inherited from TokenFamilyInfo. + slug TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT NOT NULL, + -- JSON: MerchantContractTokenDetails + extra_data TEXT NOT NULL, + -- JSON: TokenIssuePublicKey + token_issue_pub TEXT NOT NULL, + -- JSON: translations, keyed by IETF language tag + description_i18n TEXT, + fountain_id TEXT +);`, + `INSERT INTO tokens_fountain_migration (token_use_pub, token_use_priv, purchase_id, transaction_id, choice_index, output_index, repeat_index, merchant_base_url, kind, token_issue_pub_hash, token_family_hash, valid_after, valid_before, token_issue_sig, token_use_sig, token_ev, token_ev_hash, blinding_key, slug, name, description, extra_data, token_issue_pub, description_i18n) SELECT token_use_pub, token_use_priv, purchase_id, transaction_id, choice_index, output_index, repeat_index, merchant_base_url, kind, token_issue_pub_hash, token_family_hash, valid_after, valid_before, token_issue_sig, token_use_sig, token_ev, token_ev_hash, blinding_key, slug, name, description, extra_data, token_issue_pub, description_i18n FROM tokens`, + `DROP TABLE tokens`, + `ALTER TABLE tokens_fountain_migration RENAME TO tokens`, + `CREATE INDEX IF NOT EXISTS tokens_by_issue_pub_hash + ON tokens (token_issue_pub_hash);`, + `CREATE INDEX IF NOT EXISTS tokens_by_purchase_and_choice + ON tokens (purchase_id, choice_index);`, + `CREATE INDEX IF NOT EXISTS tokens_by_family_hash + ON tokens (token_family_hash);`, + `CREATE TABLE slates_fountain_migration ( + token_use_pub BLOB PRIMARY KEY, + token_use_priv BLOB NOT NULL, + purchase_id TEXT, + transaction_id TEXT, + choice_index INTEGER, + output_index INTEGER, + repeat_index INTEGER, + merchant_base_url TEXT NOT NULL, + kind TEXT NOT NULL, + token_issue_pub_hash BLOB NOT NULL, + token_family_hash BLOB, + valid_after INTEGER NOT NULL, + valid_before INTEGER NOT NULL, + -- JSON: TokenUseSig + token_use_sig TEXT, + -- JSON: TokenEnvelope + token_ev TEXT NOT NULL, + token_ev_hash BLOB NOT NULL, + blinding_key BLOB NOT NULL, + -- Inherited from TokenFamilyInfo. + slug TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT NOT NULL, + -- JSON: MerchantContractTokenDetails + extra_data TEXT NOT NULL, + -- JSON: TokenIssuePublicKey + token_issue_pub TEXT NOT NULL, + -- JSON: translations, keyed by IETF language tag + description_i18n TEXT, + fountain_id TEXT +);`, + `INSERT INTO slates_fountain_migration (token_use_pub, token_use_priv, purchase_id, transaction_id, choice_index, output_index, repeat_index, merchant_base_url, kind, token_issue_pub_hash, token_family_hash, valid_after, valid_before, token_use_sig, token_ev, token_ev_hash, blinding_key, slug, name, description, extra_data, token_issue_pub, description_i18n) SELECT token_use_pub, token_use_priv, purchase_id, transaction_id, choice_index, output_index, repeat_index, merchant_base_url, kind, token_issue_pub_hash, token_family_hash, valid_after, valid_before, token_use_sig, token_ev, token_ev_hash, blinding_key, slug, name, description, extra_data, token_issue_pub, description_i18n FROM slates`, + `DROP TABLE slates`, + `ALTER TABLE slates_fountain_migration RENAME TO slates`, + `CREATE INDEX IF NOT EXISTS slates_by_purchase_choice_output_repeat + ON slates (purchase_id, choice_index, output_index, repeat_index);`, + ], + }, ]; /** Native data tables present after the specified migration. */ diff --git a/packages/taler-wallet-core/src/db/sqlite/transaction.ts b/packages/taler-wallet-core/src/db/sqlite/transaction.ts @@ -122,6 +122,7 @@ import { WalletCoinRecovery, WalletRefreshMeltConfirmation, WalletSlate, + WalletFountain, WalletToken, WalletTransactionMeta, timestampProtocolFromDb, @@ -272,6 +273,7 @@ const SQLITE_MIGRATION_TABLES: Record<WalletDbMigrationStore, string> = { coinHistory: "coin_history", coinAvailability: "coin_availability", refundGroups: "refund_groups", + fountains: "fountains", tokens: "tokens", slates: "slates", depositGroups: "deposit_groups", @@ -5168,7 +5170,8 @@ export class SqliteWalletTransaction implements WalletDbTransaction { return { tokenUsePub: dbToCrock(row.token_use_pub), tokenUsePriv: dbToCrock(row.token_use_priv), - purchaseId: str(row.purchase_id), + purchaseId: row.purchase_id == null ? undefined : str(row.purchase_id), + fountainId: row.fountain_id == null ? undefined : str(row.fountain_id), merchantBaseUrl: str(row.merchant_base_url), kind: str(row.kind) as MerchantContractTokenKind, tokenIssuePubHash: dbToCrock(row.token_issue_pub_hash), @@ -5203,6 +5206,28 @@ export class SqliteWalletTransaction implements WalletDbTransaction { }; } + async listFountains(): Promise<WalletFountain[]> { + return (await this.all("SELECT payload FROM fountains")).map((r) => + dbToJson<WalletFountain>(r.payload), + ); + } + async getFountain(id: string): Promise<WalletFountain | undefined> { + const row = await this.first( + "SELECT payload FROM fountains WHERE fountain_id = $id", + { id }, + ); + return row ? dbToJson<WalletFountain>(row.payload) : undefined; + } + async upsertFountain(record: WalletFountain): Promise<void> { + await this.run( + "INSERT INTO fountains (fountain_id, payload) VALUES ($id, $payload) ON CONFLICT(fountain_id) DO UPDATE SET payload = excluded.payload", + { id: record.fountainId, payload: jsonToDb(record) }, + ); + } + async deleteFountain(id: string): Promise<void> { + await this.run("DELETE FROM fountains WHERE fountain_id = $id", { id }); + } + async listTokens(): Promise<WalletToken[]> { const rows = await this.all("SELECT * FROM tokens"); return rows.map((r) => this.rowToToken(r)); @@ -5219,19 +5244,20 @@ export class SqliteWalletTransaction implements WalletDbTransaction { async upsertToken(rec: WalletToken): Promise<void> { await this.run( `INSERT INTO tokens ( - token_use_pub, token_use_priv, purchase_id, transaction_id, + token_use_pub, token_use_priv, purchase_id, fountain_id, transaction_id, choice_index, output_index, repeat_index, merchant_base_url, kind, token_issue_pub_hash, token_family_hash, valid_after, valid_before, token_issue_sig, token_use_sig, token_ev, token_ev_hash, blinding_key, slug, name, description, extra_data, token_issue_pub, description_i18n ) VALUES ( - $pub, $priv, $pid, $tid, $ci, $oi, $ri, $url, $kind, $tiph, $tfh, + $pub, $priv, $pid, $fid, $tid, $ci, $oi, $ri, $url, $kind, $tiph, $tfh, $va, $vb, $sig, $tokenUseSig, $ev, $evh, $bk, $slug, $name, $desc, $extra, $tipub, $di18n ) ON CONFLICT(token_use_pub) DO UPDATE SET token_use_priv = excluded.token_use_priv, purchase_id = excluded.purchase_id, + fountain_id = excluded.fountain_id, transaction_id = excluded.transaction_id, choice_index = excluded.choice_index, output_index = excluded.output_index, @@ -5256,7 +5282,8 @@ export class SqliteWalletTransaction implements WalletDbTransaction { { pub: crockToDb(rec.tokenUsePub), priv: crockToDb(rec.tokenUsePriv), - pid: rec.purchaseId, + pid: rec.purchaseId ?? null, + fid: rec.fountainId ?? null, tid: rec.transactionId ?? null, ci: rec.choiceIndex ?? null, oi: rec.outputIndex ?? null, @@ -5316,7 +5343,8 @@ export class SqliteWalletTransaction implements WalletDbTransaction { return { tokenUsePub: dbToCrock(row.token_use_pub), tokenUsePriv: dbToCrock(row.token_use_priv), - purchaseId: str(row.purchase_id), + purchaseId: row.purchase_id == null ? undefined : str(row.purchase_id), + fountainId: row.fountain_id == null ? undefined : str(row.fountain_id), merchantBaseUrl: str(row.merchant_base_url), kind: str(row.kind) as MerchantContractTokenKind, tokenIssuePubHash: dbToCrock(row.token_issue_pub_hash), @@ -5384,18 +5412,19 @@ export class SqliteWalletTransaction implements WalletDbTransaction { async upsertSlate(rec: WalletSlate): Promise<void> { await this.run( `INSERT INTO slates ( - token_use_pub, token_use_priv, purchase_id, transaction_id, + token_use_pub, token_use_priv, purchase_id, fountain_id, transaction_id, choice_index, output_index, repeat_index, merchant_base_url, kind, token_issue_pub_hash, token_family_hash, valid_after, valid_before, token_use_sig, token_ev, token_ev_hash, blinding_key, slug, name, description, extra_data, token_issue_pub, description_i18n ) VALUES ( - $pub, $priv, $pid, $tid, $ci, $oi, $ri, $url, $kind, $tiph, $tfh, + $pub, $priv, $pid, $fid, $tid, $ci, $oi, $ri, $url, $kind, $tiph, $tfh, $va, $vb, $tokenUseSig, $ev, $evh, $bk, $slug, $name, $desc, $extra, $tipub, $di18n ) ON CONFLICT(token_use_pub) DO UPDATE SET token_use_priv = excluded.token_use_priv, purchase_id = excluded.purchase_id, + fountain_id = excluded.fountain_id, transaction_id = excluded.transaction_id, choice_index = excluded.choice_index, output_index = excluded.output_index, @@ -5419,7 +5448,8 @@ export class SqliteWalletTransaction implements WalletDbTransaction { { pub: crockToDb(rec.tokenUsePub), priv: crockToDb(rec.tokenUsePriv), - pid: rec.purchaseId, + pid: rec.purchaseId ?? null, + fid: rec.fountainId ?? null, tid: rec.transactionId ?? null, ci: rec.choiceIndex ?? null, oi: rec.outputIndex ?? null, diff --git a/packages/taler-wallet-core/src/db/transaction.ts b/packages/taler-wallet-core/src/db/transaction.ts @@ -39,6 +39,7 @@ import { WalletNotification, } from "@gnu-taler/taler-util"; import { + WalletFountain, ConfigRecord, WalletPeerPullCredit, WalletPeerPushDebit, @@ -196,6 +197,7 @@ export type WalletDbMigrationStore = | "coinHistory" | "coinAvailability" | "refundGroups" + | "fountains" | "tokens" | "slates" | "depositGroups" @@ -218,6 +220,11 @@ export interface WalletDbMigrationPage<T> { } export interface WalletDbTransaction { + listFountains(): Promise<WalletFountain[]>; + getFountain(fountainId: string): Promise<WalletFountain | undefined>; + upsertFountain(record: WalletFountain): Promise<void>; + deleteFountain(fountainId: string): Promise<void>; + /** Count the root records represented by one migration store. */ countMigrationRecords(store: WalletDbMigrationStore): Promise<number>; diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -25,6 +25,8 @@ * Imports. */ import { RefreshInput } from "./refresh-input.js"; +import { validateToken } from "./tokens.js"; +export { validateToken } from "./tokens.js"; import { readVerifiedCoinHistory, recordConflictingCoinHistory, @@ -50,7 +52,6 @@ import { ConfirmPayResult, ConfirmPayResultType, ContractTermsUtil, - DenomKeyType, DownloadedContractData, Duration, EddsaPublicKeyString, @@ -4590,54 +4591,6 @@ async function processPurchasePay( return TaskRunResult.progress(); } -export async function validateToken( - wex: WalletExecutionContext, - slate: WalletSlate, - blindedEv: SignedTokenEnvelope, -): Promise<WalletToken> { - const { tokenIssuePub, tokenIssuePubHash, tokenUsePub, blindingKey } = slate; - logger.trace( - `validating token ${tokenIssuePubHash} for purchase ${slate.purchaseId}`, - ); - const tokenIssueSig = await wex.cryptoApi.unblindTokenIssueSignature({ - slate: { - tokenIssuePub, - blindingKey, - }, - evSig: blindedEv.blind_sig, - }); - - if (tokenIssueSig.cipher !== tokenIssuePub.cipher) - throw Error("token issue signature mismatch"); - - if (!(tokenIssuePub.cipher === DenomKeyType.Rsa)) - throw Error("unsupported cipher"); - if (tokenIssueSig.cipher !== DenomKeyType.Rsa) - throw Error("unsupported cipher"); - - const rsaVerifyResp = await wex.cryptoApi.rsaVerify({ - hm: tokenUsePub, - pk: tokenIssuePub.rsa_pub, - sig: tokenIssueSig.rsa_signature, - }); - - if (!rsaVerifyResp.valid) { - logger.error("token issue signature invalid"); - // TODO: properly display error - throw Error("token issue signature invalid"); - } - - logger.trace( - `token ${tokenIssuePubHash} for purchase ${slate.purchaseId} is valid, will be stored`, - ); - - const token: WalletToken = { - tokenIssueSig, - ...slate, - }; - return token; -} - export async function generateTokenSigs( wex: WalletExecutionContext, proposalId: string, diff --git a/packages/taler-wallet-core/src/tokenFamilies.ts b/packages/taler-wallet-core/src/tokenFamilies.ts @@ -60,7 +60,9 @@ function groupDiscounts( tokenFamilyHash: familyHash, tokenIssuePubHash: token.tokenIssuePubHash, merchantBaseUrl: token.merchantBaseUrl, - merchantInfo: merchantInfos[token.purchaseId], + merchantInfo: token.purchaseId + ? merchantInfos[token.purchaseId] + : undefined, name: token.name, description: token.description, descriptionI18n: token.descriptionI18n, @@ -91,7 +93,9 @@ function groupSubscriptions( tokenFamilyHash: familyHash, tokenIssuePubHash: token.tokenIssuePubHash, merchantBaseUrl: token.merchantBaseUrl, - merchantInfo: merchantInfos[token.purchaseId], + merchantInfo: token.purchaseId + ? merchantInfos[token.purchaseId] + : undefined, name: token.name, description: token.description, descriptionI18n: token.descriptionI18n, @@ -108,7 +112,9 @@ async function getMerchantInfos( ): Promise<MerchantInfos> { const merchantInfos: MerchantInfos = {}; await wex.runWalletDbTx(async (tx) => { - const purchaseIds = [...new Set(tokens.map((t) => t.purchaseId))]; + const purchaseIds = [ + ...new Set(tokens.flatMap((t) => (t.purchaseId ? [t.purchaseId] : []))), + ]; const purchases = await tx.getPurchasesByIds(purchaseIds); for (const purchase of purchases) { const download = await expectProposalDownloadInTx(wex, tx, purchase); diff --git a/packages/taler-wallet-core/src/tokens.ts b/packages/taler-wallet-core/src/tokens.ts @@ -0,0 +1,70 @@ +/* + 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 { + DenomKeyType, + Logger, + SignedTokenEnvelope, +} from "@gnu-taler/taler-util"; +import { WalletSlate, WalletToken } from "./db/records.js"; +import { WalletExecutionContext } from "./wallet.js"; +const logger = new Logger("tokens.ts"); + +export async function validateToken( + wex: WalletExecutionContext, + slate: WalletSlate, + blindedEv: SignedTokenEnvelope, +): Promise<WalletToken> { + const { tokenIssuePub, tokenIssuePubHash, tokenUsePub, blindingKey } = slate; + logger.trace(`validating token for issue key ${tokenIssuePubHash}`); + const tokenIssueSig = await wex.cryptoApi.unblindTokenIssueSignature({ + slate: { + tokenIssuePub, + blindingKey, + }, + evSig: blindedEv.blind_sig, + }); + + if (tokenIssueSig.cipher !== tokenIssuePub.cipher) + throw Error("token issue signature mismatch"); + + if (!(tokenIssuePub.cipher === DenomKeyType.Rsa)) + throw Error("unsupported cipher"); + if (tokenIssueSig.cipher !== DenomKeyType.Rsa) + throw Error("unsupported cipher"); + + const rsaVerifyResp = await wex.cryptoApi.rsaVerify({ + hm: tokenUsePub, + pk: tokenIssuePub.rsa_pub, + sig: tokenIssueSig.rsa_signature, + }); + + if (!rsaVerifyResp.valid) { + logger.error("token issue signature invalid"); + // TODO: properly display error + throw Error("token issue signature invalid"); + } + + logger.trace( + `token for issue key ${tokenIssuePubHash} is valid, will be stored`, + ); + + const token: WalletToken = { + tokenIssueSig, + ...slate, + }; + return token; +}