commit 56ee705ad483da4c2aef53fd09c8c599b36aead0 parent 957d9603e2e309faff2b9298c97916f70fc0960d Author: Florian Dold <dold@taler.net> Date: Mon, 23 Nov 2026 19:48:40 +0100 wallet-core: add tables for the notification inbox Keep the signatures of conflicting spends so retries can avoid counting the same debit twice. Diffstat:
14 files changed, 400 insertions(+), 5 deletions(-)
diff --git a/packages/taler-util/src/index.ts b/packages/taler-util/src/index.ts @@ -113,3 +113,5 @@ export * from "./aml/reporting.js"; export * from "./iso-3166.js"; export * from "./result.js"; + +export * from "./user-attention.js"; diff --git a/packages/taler-util/src/user-attention.ts b/packages/taler-util/src/user-attention.ts @@ -0,0 +1,57 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: GPL-3.0-or-later + */ +import type { AmountString } from "./types-taler-common.js"; +import type { TalerPreciseTimestamp } from "./time.js"; +import type { TransactionIdStr } from "./types-taler-wallet.js"; + +export type UserAttentionDetails = + | { + type: "coin-double-spent"; + /** Sum of the original verified debits, before any refunds. */ + amountSpentElsewhere: AmountString; + exchangeBaseUrls: string[]; + merchantName?: string; + transactionId?: TransactionIdStr; + } + | { + type: "exchange-tos-changed"; + exchangeBaseUrl: string; + acceptedEtag: string; + currentEtag: string; + } + | { + type: "exchange-master-key-changed"; + exchangeBaseUrl: string; + previousMasterPub: string; + currentMasterPub: string; + } + | { + type: "exchange-currency-changed"; + exchangeBaseUrl: string; + masterPub: string; + previousCurrency: string; + currentCurrency: string; + } + | { type: "refresh-blocked-for-debugging" }; + +export type UserAttentionItem = UserAttentionDetails & { + /** Identifies one occurrence, including across wallet restarts. */ + attentionId: string; + createdAt: TalerPreciseTimestamp; + /** Absent until the user marks this occurrence as read. */ + readAt?: TalerPreciseTimestamp; + /** If present, this occurrence leaves the inbox at the given time. */ + expiresAt?: TalerPreciseTimestamp; + /** False when resolving the underlying condition removes the item. */ + dismissible: boolean; + /** Generated by the UI test experiment. */ + isSample?: boolean; +}; + +export interface UserAttentionSnapshot { + items: UserAttentionItem[]; + unreadCount: number; +} diff --git a/packages/taler-wallet-core/src/db/indexeddb/database.test.ts b/packages/taler-wallet-core/src/db/indexeddb/database.test.ts @@ -18,6 +18,7 @@ import { BridgeIDBFactory, createSqliteBackend, IDBDatabase, + structuredRevive, } from "@gnu-taler/idb-bridge"; import { createNodeHelperSqlite3Impl } from "@gnu-taler/idb-bridge/node-helper-sqlite3-impl"; import assert from "node:assert"; @@ -32,7 +33,11 @@ import { } from "./database.js"; import { exportSingleDb } from "./dump.js"; import { applyFixups } from "./fixups.js"; -import { TALER_WALLET_MAIN_DB_NAME } from "./schema.js"; +import { openDatabase } from "../query.js"; +import { + WalletIndexedDbStoresV1, + TALER_WALLET_MAIN_DB_NAME, +} from "./schema.js"; import { IdbWalletDbHandle } from "./handle.js"; import { makeIdbRunner } from "../testing/runners.js"; @@ -298,3 +303,40 @@ test("an aborted transaction without pending requests settles its promise", asyn await handle.close(); } }); + +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"); +}); diff --git a/packages/taler-wallet-core/src/db/indexeddb/schema.ts b/packages/taler-wallet-core/src/db/indexeddb/schema.ts @@ -48,6 +48,8 @@ import { WalletCoin, WalletCoinAvailability, WalletCoinHistory, + WalletTransactionCoinConflict, + WalletUserAttention, WalletContractTerms, WalletDenomination, WalletDenominationFamily, @@ -170,7 +172,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 = 36; +export const WALLET_DB_MINOR_VERSION = 37; export interface BankWithdrawUriRecord { /** @@ -651,6 +653,28 @@ export const WalletIndexedDbStoresV1 = { }), }, ), + transactionCoinConflicts: describeStoreV2({ + storeName: "transactionCoinConflicts", + recordCodec: passthroughCodec<WalletTransactionCoinConflict>(), + keyPath: ["transactionId", "coinPub"], + versionAdded: 37, + }), + // The legacy "userAttention" store has a different key path and can still contain rows. + userAttentionItems: describeStoreV2({ + storeName: "userAttentionItems", + recordCodec: passthroughCodec<WalletUserAttention>(), + keyPath: "sourceKey", + versionAdded: 37, + indexes: { + byId: describeIndex("byId", "item.attentionId", { + versionAdded: 37, + unique: true, + }), + byUnreadUntil: describeIndex("byUnreadUntil", "unreadUntil", { + versionAdded: 37, + }), + }, + }), coinHistory: describeStoreV2({ storeName: "coinHistory", recordCodec: passthroughCodec<WalletCoinHistory>(), diff --git a/packages/taler-wallet-core/src/db/indexeddb/transaction.ts b/packages/taler-wallet-core/src/db/indexeddb/transaction.ts @@ -57,6 +57,8 @@ import { OPERATION_STATUS_NONFINAL_LAST, WalletCoinAvailability, WalletCoinHistory, + WalletTransactionCoinConflict, + WalletUserAttention, WalletCoin, WalletDepositGroup, WalletRecoupGroup, @@ -166,6 +168,8 @@ export class IdbWalletTransaction implements WalletDbTransaction { refreshSessions: "refreshSessions", coinRecoveries: "coinRecoveries", refreshMeltConfirmations: "refreshMeltConfirmations", + transactionCoinConflicts: "transactionCoinConflicts", + userAttentionItems: "userAttentionItems", coinHistory: "coinHistory", coinAvailability: "coinAvailabilityV2", refundGroups: "refundGroups", @@ -1623,6 +1627,50 @@ export class IdbWalletTransaction implements WalletDbTransaction { }); } + async getTransactionCoinConflict(transactionId: string, coinPub: string) { + return this.tx.transactionCoinConflicts.get([transactionId, coinPub]); + } + + async listTransactionCoinConflicts() { + return this.tx.transactionCoinConflicts.getAll(); + } + + async upsertTransactionCoinConflict(row: WalletTransactionCoinConflict) { + await this.tx.transactionCoinConflicts.put(row); + } + + async deleteTransactionCoinConflicts(transactionId: string) { + const store = this.tx.transactionCoinConflicts; + const range = GlobalIDB.KeyRange.bound( + [transactionId], + [transactionId, []], + ); + for (const { coinPub } of await store.getAll(range)) { + await store.delete([transactionId, coinPub]); + } + } + + async getUserAttention(key: string) { + return this.tx.userAttentionItems.get(key); + } + async getUserAttentionById(id: string) { + return this.tx.userAttentionItems.indexes.byId.get(id); + } + async listUserAttention() { + return this.tx.userAttentionItems.getAll(); + } + async countUnreadAttention(now: number) { + return this.tx.userAttentionItems.indexes.byUnreadUntil.count( + GlobalIDB.KeyRange.lowerBound(now, true), + ); + } + async upsertUserAttention(row: WalletUserAttention) { + await this.tx.userAttentionItems.put(row); + } + async deleteUserAttention(key: string) { + await this.tx.userAttentionItems.delete(key); + } + async getCoinHistory( coinPub: string, ): Promise<WalletCoinHistory | undefined> { diff --git a/packages/taler-wallet-core/src/db/migration/converter.test.ts b/packages/taler-wallet-core/src/db/migration/converter.test.ts @@ -1384,6 +1384,8 @@ test("converter: the copy plan covers every table in the schema", async () => { planchets: "planchets", coins: "coins", coin_availability: "coinAvailability", + transaction_coin_conflicts: "transactionCoinConflicts", + user_attention_items: "userAttentionItems", coin_history: "coinHistory", refund_groups: "refundGroups", refund_items: "refundItems", diff --git a/packages/taler-wallet-core/src/db/migration/converter.ts b/packages/taler-wallet-core/src/db/migration/converter.ts @@ -421,6 +421,16 @@ const COPY_PLAN: CopyStep[][] = [ (tx, r) => tx.upsertRefreshMeltConfirmation(r), ), step( + "transactionCoinConflicts", + (tx) => tx.listTransactionCoinConflicts(), + (tx, row) => tx.upsertTransactionCoinConflict(row), + ), + step( + "userAttentionItems", + (tx) => tx.listUserAttention(), + (tx, row) => tx.upsertUserAttention(row), + ), + step( "coinHistory", (tx) => tx.listAllCoinHistories(), (tx, r) => tx.upsertCoinHistory(r), diff --git a/packages/taler-wallet-core/src/db/query.ts b/packages/taler-wallet-core/src/db/query.ts @@ -434,7 +434,7 @@ interface IndexReadWriteAccessor<RecordType> { query?: IDBKeyRange | IDBValidKey, count?: number, ): Promise<IDBValidKey[]>; - count(query?: IDBValidKey): Promise<number>; + count(query?: IDBValidKey | IDBKeyRange): Promise<number>; } type GetIndexReadWriteAccess<RecordType, IndexMap> = { diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -2200,6 +2200,23 @@ export enum PurchaseStatus { AbortedClaimedByOther = 0x0503_0004, } +export interface WalletTransactionCoinConflict { + transactionId: TransactionIdStr; + coinPub: string; + exchangeBaseUrl: string; + /** Original debits keyed by their verified spend signatures. */ + debits: Record<string, AmountString>; +} + +export interface WalletUserAttention { + /** Stable identity of the condition or affected transaction. */ + sourceKey: string; + item: import("@gnu-taler/taler-util").UserAttentionItem; + dismissed?: boolean; + /** Zero for read/dismissed rows, otherwise the expiry or MAX_SAFE_INTEGER. */ + unreadUntil: number; +} + export enum ConfigRecordKey { RecoupRecoveryVersion = "recoupRecoveryVersion", WalletBackupState = "walletBackupState", diff --git a/packages/taler-wallet-core/src/db/sqlite/database.ts b/packages/taler-wallet-core/src/db/sqlite/database.ts @@ -636,7 +636,11 @@ export async function importNativeSqliteDb( cancellationToken: CancellationToken = CancellationToken.CONTINUE, ): Promise<void> { cancellationToken.throwIfCancelled(); - if (dump.schemaVersion !== SQLITE_SCHEMA_VERSION) { + // A v29 dump has the same row formats. Its missing attention table starts empty. + if ( + dump.schemaVersion !== SQLITE_SCHEMA_VERSION && + !(SQLITE_SCHEMA_VERSION === 30 && dump.schemaVersion === 29) + ) { throw Error( `cannot import a native wallet DB dump of schema version` + ` ${dump.schemaVersion} into version ${SQLITE_SCHEMA_VERSION}`, diff --git a/packages/taler-wallet-core/src/db/sqlite/schema.ts b/packages/taler-wallet-core/src/db/sqlite/schema.ts @@ -85,7 +85,7 @@ * * Bump this when adding a migration to {@link schemaMigrations}. */ -export const SQLITE_SCHEMA_VERSION = 29; +export const SQLITE_SCHEMA_VERSION = 30; /** * Tables of the IndexedDB emulation, children before parents. @@ -183,6 +183,7 @@ export interface SchemaMigration { export const BLOB_COLUMNS: Readonly<Record<string, readonly string[]>> = { coin_availability: ["denom_pub_hash", "exchange_master_pub"], coin_history: ["coin_pub"], + transaction_coin_conflicts: ["coin_pub"], coins: [ "blinding_key", "coin_ev_hash", @@ -1559,6 +1560,21 @@ export const schemaMigrations: SchemaMigration[] = [ "ALTER TABLE recoup_groups ADD COLUMN legacy_refresh_credits TEXT", ], }, + { + version: 30, + name: "user-attention", + statements: [ + `CREATE TABLE transaction_coin_conflicts ( + transaction_id TEXT NOT NULL, + coin_pub BLOB NOT NULL, + exchange_base_url TEXT NOT NULL, + debits TEXT NOT NULL, + PRIMARY KEY (transaction_id, coin_pub) + )`, + "CREATE TABLE user_attention_items (source_key TEXT PRIMARY KEY, attention_id TEXT NOT NULL UNIQUE, unread_until INTEGER NOT NULL, record TEXT NOT NULL)", + "CREATE INDEX user_attention_unread ON user_attention_items (unread_until)", + ], + }, ]; /** Native tables that contain wallet records (not schema bookkeeping). */ @@ -1566,6 +1582,8 @@ export const NATIVE_DATA_TABLES = [ ...[...SQLITE_BASELINE_SCHEMA.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g)] .map((m) => m[1]) .filter((name) => !NON_DATA_TABLES.includes(name)), + "transaction_coin_conflicts", + "user_attention_items", "coin_recoveries", "refresh_melt_confirmations", ]; diff --git a/packages/taler-wallet-core/src/db/sqlite/transaction.ts b/packages/taler-wallet-core/src/db/sqlite/transaction.ts @@ -69,6 +69,8 @@ import { WalletCoin, WalletCoinAvailability, WalletCoinHistory, + WalletTransactionCoinConflict, + WalletUserAttention, OPERATION_STATUS_NONFINAL_FIRST, OPERATION_STATUS_NONFINAL_LAST, ReserveBankInfo, @@ -264,6 +266,8 @@ const SQLITE_MIGRATION_TABLES: Record<WalletDbMigrationStore, string> = { refreshSessions: "refresh_sessions", coinRecoveries: "coin_recoveries", refreshMeltConfirmations: "refresh_melt_confirmations", + transactionCoinConflicts: "transaction_coin_conflicts", + userAttentionItems: "user_attention_items", coinHistory: "coin_history", coinAvailability: "coin_availability", refundGroups: "refund_groups", @@ -1395,6 +1399,99 @@ export class SqliteWalletTransaction implements WalletDbTransaction { }); } + // ------------------------------------------------------ user attention + + private rowToTransactionCoinConflict( + row: ResultRow, + ): WalletTransactionCoinConflict { + return { + transactionId: + row.transaction_id as WalletTransactionCoinConflict["transactionId"], + coinPub: dbToCrock(row.coin_pub), + exchangeBaseUrl: str(row.exchange_base_url), + debits: dbToJson(row.debits), + }; + } + + async getTransactionCoinConflict(transactionId: string, coinPub: string) { + const row = await this.first( + "SELECT * FROM transaction_coin_conflicts WHERE transaction_id = $id AND coin_pub = $pub", + { id: transactionId, pub: crockToDb(coinPub) }, + ); + return row && this.rowToTransactionCoinConflict(row); + } + + async listTransactionCoinConflicts() { + return (await this.all("SELECT * FROM transaction_coin_conflicts")).map( + (row) => this.rowToTransactionCoinConflict(row), + ); + } + + async upsertTransactionCoinConflict(row: WalletTransactionCoinConflict) { + await this.run( + `INSERT INTO transaction_coin_conflicts (transaction_id, coin_pub, exchange_base_url, debits) + VALUES ($id, $pub, $url, $debits) + ON CONFLICT(transaction_id, coin_pub) DO UPDATE SET + exchange_base_url = excluded.exchange_base_url, debits = excluded.debits`, + { + id: row.transactionId, + pub: crockToDb(row.coinPub), + url: row.exchangeBaseUrl, + debits: jsonToDb(row.debits), + }, + ); + } + + async deleteTransactionCoinConflicts(transactionId: string) { + await this.run( + "DELETE FROM transaction_coin_conflicts WHERE transaction_id = $id", + { id: transactionId }, + ); + } + + async getUserAttention(key: string) { + const row = await this.first( + "SELECT record FROM user_attention_items WHERE source_key = $key", + { key }, + ); + return row && dbToJson<WalletUserAttention>(row.record); + } + async getUserAttentionById(id: string) { + const row = await this.first( + "SELECT record FROM user_attention_items WHERE attention_id = $id", + { id }, + ); + return row && dbToJson<WalletUserAttention>(row.record); + } + async listUserAttention() { + return (await this.all("SELECT record FROM user_attention_items")).map( + (row) => dbToJson<WalletUserAttention>(row.record), + ); + } + async countUnreadAttention(now: number) { + const row = await this.first( + "SELECT count(*) AS n FROM user_attention_items WHERE unread_until > $now", + { now }, + ); + return Number(row!.n); + } + async upsertUserAttention(row: WalletUserAttention) { + await this.run( + "INSERT INTO user_attention_items (source_key,attention_id,unread_until,record) VALUES ($key,$id,$until,$record) ON CONFLICT(source_key) DO UPDATE SET attention_id=excluded.attention_id, unread_until=excluded.unread_until, record=excluded.record", + { + key: row.sourceKey, + id: row.item.attentionId, + until: row.unreadUntil, + record: jsonToDb(row), + }, + ); + } + async deleteUserAttention(key: string) { + await this.run("DELETE FROM user_attention_items WHERE source_key=$key", { + key, + }); + } + // ------------------------------------------------------ coin history async getCoinHistory( diff --git a/packages/taler-wallet-core/src/db/testing/conformance-cases.ts b/packages/taler-wallet-core/src/db/testing/conformance-cases.ts @@ -836,6 +836,59 @@ async function seedRecoveryExchange(tx: WalletDbTransaction, baseUrl: string) { export const conformanceCases: ConformanceCase[] = [ { + name: "verified conflict records round-trip with compound transaction and coin keys", + async run(t, runner) { + const row = { + transactionId: txnId("txn:payment:conflict"), + coinPub: ck("conflict"), + exchangeBaseUrl: "https://exchange.example/", + debits: { [ck("authorization")]: "TESTKUDOS:2" as const }, + }; + const sameCoin = { ...row, transactionId: txnId("txn:payment:other") }; + const samePayment = { ...row, coinPub: ck("second-coin") }; + const records = [row, sameCoin, samePayment]; + await runner.runReadWriteTx(async (tx) => { + for (const record of records) + await tx.upsertTransactionCoinConflict(record); + }); + await runner.runReadWriteTx(async (tx) => { + for (const record of records) + t.deepEqual( + await tx.getTransactionCoinConflict( + record.transactionId, + record.coinPub, + ), + record, + ); + }); + }, + }, + { + name: "attention retains occurrence identity and excludes the expiry instant from unread counts", + async run(t, runner) { + const row = { + sourceKey: "sample:coin-double-spent", + unreadUntil: 2000, + item: { + type: "coin-double-spent" as const, + attentionId: "sample-occurrence", + exchangeBaseUrls: ["https://exchange.example/"], + amountSpentElsewhere: "TESTKUDOS:1" as const, + createdAt: { t_s: 1 }, + expiresAt: { t_s: 2 }, + dismissible: true, + isSample: true, + }, + }; + await runner.runReadWriteTx(async (tx) => { + await tx.upsertUserAttention(row); + t.deepEqual(await tx.getUserAttentionById(row.item.attentionId), row); + t.equal(await tx.countUnreadAttention(1999), 1); + t.equal(await tx.countUnreadAttention(2000), 0); + }); + }, + }, + { name: "recoup credit and superseded refresh commit or roll back together", async run(t, runner) { const { recordRecoupCredit } = await import("../../recoup.js"); diff --git a/packages/taler-wallet-core/src/db/transaction.ts b/packages/taler-wallet-core/src/db/transaction.ts @@ -56,6 +56,8 @@ import { DenominationVerificationStatus, WalletCoinAvailability, WalletCoinHistory, + WalletTransactionCoinConflict, + WalletUserAttention, WalletCoin, WalletDepositGroup, WalletRecoupGroup, @@ -189,6 +191,8 @@ export type WalletDbMigrationStore = | "refreshSessions" | "coinRecoveries" | "refreshMeltConfirmations" + | "transactionCoinConflicts" + | "userAttentionItems" | "coinHistory" | "coinAvailability" | "refundGroups" @@ -545,6 +549,23 @@ export interface WalletDbTransaction { /** Delete a coin by its public key. */ deleteCoin(coinPub: string): Promise<void>; + getTransactionCoinConflict( + transactionId: string, + coinPub: string, + ): Promise<WalletTransactionCoinConflict | undefined>; + listTransactionCoinConflicts(): Promise<WalletTransactionCoinConflict[]>; + upsertTransactionCoinConflict( + row: WalletTransactionCoinConflict, + ): Promise<void>; + deleteTransactionCoinConflicts(transactionId: string): Promise<void>; + + getUserAttention(key: string): Promise<WalletUserAttention | undefined>; + getUserAttentionById(id: string): Promise<WalletUserAttention | undefined>; + listUserAttention(): Promise<WalletUserAttention[]>; + countUnreadAttention(now: number): Promise<number>; + upsertUserAttention(row: WalletUserAttention): Promise<void>; + deleteUserAttention(key: string): Promise<void>; + /** Delete the recorded history of a coin. */ deleteCoinHistory(coinPub: string): Promise<void>;