taler-typescript-core

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

commit 93d5c7c4e17c896f9ad1f3f728cec60799bf15fc
parent 58a36bb664820109852797fe4794a563df74d935
Author: Florian Dold <dold@taler.net>
Date:   Tue, 24 Nov 2026 16:44:37 +0100

wallet-core: keep the exchange key and refund reason with each refund

A stored scope can go stale when an exchange rotates its master key.
Save the exchange URL and key so the wallet can recompute the scope, and
recover the refund reason while the payment is still available.

Issue: https://bugs.taler.net/n/10663

Diffstat:
Mpackages/taler-wallet-core/src/db/records.ts | 32+++++++++++++++++++-------------
Mpackages/taler-wallet-core/src/db/sqlite/schema-migrations.test.ts | 6+++---
Mpackages/taler-wallet-core/src/exchanges.test.ts | 14++++++++++----
Mpackages/taler-wallet-core/src/exchanges.ts | 6+++++-
Mpackages/taler-wallet-core/src/observe-transaction.test.ts | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/observe-transaction.ts | 5++++-
Mpackages/taler-wallet-core/src/pay-merchant.test.ts | 71++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mpackages/taler-wallet-core/src/pay-merchant.ts | 206+++++++++++++++----------------------------------------------------------------
Apackages/taler-wallet-core/src/refund-history.ts | 295+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/requests.test.ts | 4++--
Mpackages/taler-wallet-core/src/requests.ts | 6++++--
Mpackages/taler-wallet-core/src/transaction-amounts.ts | 26+++++++++++++++-----------
12 files changed, 581 insertions(+), 217 deletions(-)

diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -1119,14 +1119,22 @@ export interface WalletPurchase { talerUri?: string; } -/** Immutable purchase context retained by a refund after payment deletion. */ +export interface WalletRefundExchangeIdentity { + url: string; + masterPub?: string; +} + +/** Purchase and issuing-exchange facts retained by a refund. */ export interface WalletRefundPurchaseSnapshot { - paymentInfo: RefundPaymentInfo; - merchantBaseUrl: string; - orderId: string; - scopes: ScopeInfo[]; - exchanges: string[]; - legacyScopes: ScopeInfoExchangeLegacyKeys[]; + paymentInfo?: RefundPaymentInfo; + merchantBaseUrl?: string; + orderId?: string; + /** One entry per issuing key, or just its URL when the key is unknown. */ + exchangeIdentities?: WalletRefundExchangeIdentity[]; + /** Version 1 fields, read during upgrade. Its URLs could be contract offers. */ + scopes?: ScopeInfo[]; + exchanges?: string[]; + legacyScopes?: ScopeInfoExchangeLegacyKeys[]; } /** @@ -1151,12 +1159,8 @@ export interface WalletRefundGroup { refreshGroupId?: string; /** - * Immutable purchase context retained by the refund. - * - * A pre-snapshot refund whose purchase was already deleted cannot be - * backfilled: its refund record lacks the contract terms hash and sufficient - * merchant/order data. Such legacy orphans require an external source such - * as a backup; their missing snapshot does not block migration completion. + * Purchase and exchange facts available when the refund was recorded or repaired. + * Older detached refunds can lack merchant details. */ purchaseSnapshot?: WalletRefundPurchaseSnapshot; refundReason?: RefundReason; @@ -2575,6 +2579,8 @@ export enum RefundItemStatus { * for the refund. */ Failed = 0x0501_0000, + /** Wallet stopped collection before the exchange confirmed this item. */ + Aborted = 0x0503_0000, } export enum DenomLossStatus { 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 @@ -35,7 +35,7 @@ import { } from "./schema.js"; import { initSqliteWalletDb, openNativeSqliteWalletDb } from "./database.js"; import { SqliteWalletDbHandle } from "./handle.js"; -import { migrateRefundPurchaseSnapshots } from "../../pay-merchant.js"; +import { migrateRefundPurchaseSnapshots } from "../../refund-history.js"; import type { WalletExecutionContext } from "../../wallet.js"; import type { WalletDbTransaction } from "../transaction.js"; @@ -936,11 +936,11 @@ test("refund snapshot backfill reads purchases from an upgraded database", async tx.getRefundGroup("upgrade-refund"), ); assert.strictEqual( - group?.purchaseSnapshot?.paymentInfo.merchant.name, + group?.purchaseSnapshot?.paymentInfo?.merchant.name, "upgrade merchant", ); assert.strictEqual( - group?.purchaseSnapshot?.paymentInfo.summary, + group?.purchaseSnapshot?.paymentInfo?.summary, "Upgraded refund", ); assert.strictEqual(group?.purchaseSnapshot?.orderId, "order"); diff --git a/packages/taler-wallet-core/src/exchanges.test.ts b/packages/taler-wallet-core/src/exchanges.test.ts @@ -295,6 +295,7 @@ for (const makeRunner of runnerFactories) { for (const [index, url] of [ exchangeBaseUrl, otherExchangeBaseUrl, + exchangeBaseUrl, ].entries()) { const refundGroupId = `detached-refund-${index}`; await tx.upsertRefundGroup({ @@ -312,9 +313,9 @@ for (const makeRunner of runnerFactories) { }, merchantBaseUrl: "https://merchant.example/", orderId: `order-${index}`, - scopes: [], - exchanges: [url], - legacyScopes: [], + ...(index === 2 + ? { exchanges: [url] } + : { exchangeIdentities: [{ url }] }), }, }); await tx.upsertRefundItem({ @@ -342,15 +343,20 @@ for (const makeRunner of runnerFactories) { deletedItems: await tx.getRefundItemsByGroup("detached-refund-0"), retainedGroup: await tx.getRefundGroup("detached-refund-1"), retainedItems: await tx.getRefundItemsByGroup("detached-refund-1"), + unverifiedGroup: await tx.getRefundGroup("detached-refund-2"), })); assert.strictEqual(result.exchange, undefined); assert.strictEqual(result.deletedGroup, undefined); assert.deepStrictEqual(result.deletedItems, []); assert.strictEqual( - result.retainedGroup?.purchaseSnapshot?.exchanges[0], + result.retainedGroup?.purchaseSnapshot?.exchangeIdentities?.[0].url, otherExchangeBaseUrl, ); assert.strictEqual(result.retainedItems.length, 1); + assert.ok( + result.unverifiedGroup, + "a legacy contract offer alone cannot establish ownership", + ); } finally { await runner.close(); } diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -4631,7 +4631,11 @@ async function purgeExchange( await payCtx.deleteTransactionInTx(tx); } for (const refund of await tx.listAllRefundGroups()) { - if (!refund.purchaseSnapshot?.exchanges.includes(exchangeBaseUrl)) { + if ( + !refund.purchaseSnapshot?.exchangeIdentities?.some( + (issuer) => issuer.url === exchangeBaseUrl, + ) + ) { continue; } const refundCtx = new RefundTransactionContext( diff --git a/packages/taler-wallet-core/src/observe-transaction.test.ts b/packages/taler-wallet-core/src/observe-transaction.test.ts @@ -13,6 +13,9 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { CancellationToken, + CoinStatus, + DenomKeyType, + ScopeType, encodeCrock, ExchangeTosStatus, NotificationType, @@ -41,6 +44,10 @@ import { } from "./common.js"; import { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronousWorkerFactoryPlain.js"; import { + CoinSourceType, + RefundGroupStatus, + RefundItemStatus, + timestampProtocolToDb, ExchangeEntryDbRecordStatus, ExchangeEntryDbUpdateStatus, PeerPushCreditStatus, @@ -53,6 +60,7 @@ import { WithdrawalGroupStatus, WithdrawalRecordType, } from "./db/records.js"; +import { migrateRefundPurchaseSnapshots } from "./refund-history.js"; import { runnerFactories } from "./db/testing/runners.js"; import { observeTransaction, @@ -76,6 +84,7 @@ import { import { constructTransactionIdentifier, parseTransactionIdentifier, + rematerializeTransactionsForExchange, getTransactionById, } from "./transactions.js"; import { WalletApiOperation } from "./wallet-api-types.js"; @@ -1580,6 +1589,124 @@ for (const makeRunner of runnerFactories) { } for (const makeRunner of runnerFactories) { + test(`${makeRunner.name}: detached refunds retain their issuing exchange across key rotation`, async () => { + const f = await fixture(makeRunner); + const currency = "TESTKUDOS"; + const id = "txn:refund:retained"; + try { + await f.wex.runWalletDbTx(async (tx) => { + await tx.upsertGlobalCurrencyExchange({ + currency, + exchangeBaseUrl: exchangeUrl, + exchangeMasterPub: master, + }); + await tx.upsertCoin({ + coinPub: master, + coinPriv: master, + denomPubHash: master, + denomSig: { cipher: DenomKeyType.Rsa, rsa_signature: master }, + exchangeBaseUrl: exchangeUrl, + exchangeMasterPub: master, + blindingKey: master, + exchangeWithdrawValues: { cipher: "RSA" }, + coinEvHash: master, + status: CoinStatus.Fresh, + visible: 1, + maxAge: 0, + ageCommitmentProof: undefined, + coinSource: { + type: CoinSourceType.Withdraw, + withdrawalGroupId: "withdrawal", + coinIndex: 0, + reservePub: master, + }, + }); + await tx.upsertRefundGroup({ + refundGroupId: "retained", + proposalId: "deleted", + status: RefundGroupStatus.Done, + timestampCreated: f.credit.timestamp, + amountRaw: "TESTKUDOS:3", + amountEffective: "TESTKUDOS:3", + purchaseSnapshot: { + orderId: "order", + merchantBaseUrl: "https://merchant.example/", + paymentInfo: { + merchant: { name: "Merchant" }, + summary: "Order", + summary_i18n: undefined, + }, + exchanges: [exchangeUrl, "https://offered-but-unused.example/"], + scopes: [{ type: ScopeType.Global, currency }], + legacyScopes: [ + { + type: ScopeType.ExchangeLegacyKeys, + currency, + url: "https://offered-but-unused.example/", + masterPub: oldMaster, + }, + ], + }, + }); + await tx.upsertRefundItem({ + refundGroupId: "retained", + coinPub: master, + rtxid: 1, + refundAmount: "TESTKUDOS:3", + status: RefundItemStatus.Done, + obtainedTime: f.credit.timestamp, + executionTime: timestampProtocolToDb({ t_s: 1 }), + }); + }); + await migrateRefundPurchaseSnapshots(f.wex); + const read = () => + f.wex.runWalletDbTx((tx) => readTransactionSnapshot(f.wex, tx, id)); + const before = await read(); + assert.ok(before?.type === TransactionType.Refund); + assert.deepEqual(before.transaction.scopes, [ + { type: ScopeType.Global, currency }, + ]); + assert.deepEqual( + before.exchanges.map((x) => x.exchangeBaseUrl), + [exchangeUrl], + ); + await f.wex.runWalletDbTx(async (tx) => { + await tx.deleteCoin(master); + await tx.upsertExchangeDetails({ + ...f.details, + rowId: undefined, + masterPublicKey: oldMaster, + }); + await tx.upsertExchange({ + ...f.exchange, + detailsPointer: { + currency, + masterPublicKey: oldMaster, + updateClock: f.credit.timestamp, + }, + }); + await rematerializeTransactionsForExchange(f.wex, tx, exchangeUrl); + }); + const after = await read(); + assert.ok(after?.type === TransactionType.Refund); + assert.deepEqual( + after.exchanges.map((x) => x.exchangeBaseUrl), + [exchangeUrl], + ); + assert.ok( + after.transaction.scopes.some( + (scope) => + scope.type === ScopeType.ExchangeLegacyKeys && + scope.url === exchangeUrl && + scope.masterPub === master && + scope.currency === currency, + ), + ); + } finally { + await f.ws.shutdown(); + } + }); + test(`${makeRunner.name}: invoice observations retain the preparation estimate without checking affordability`, async () => { const f = await fixture(makeRunner); const { PeerPullDebitRecordStatus } = await import("./db/records.js"); diff --git a/packages/taler-wallet-core/src/observe-transaction.ts b/packages/taler-wallet-core/src/observe-transaction.ts @@ -37,6 +37,7 @@ import { WithdrawalRecordType, timestampPreciseFromDb, } from "./db/records.js"; +import { refundExchangeUrls, resolveRefundSnapshot } from "./refund-history.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { loadReadyExchangeSummary, @@ -220,7 +221,9 @@ async function transactionExchangeUrls( case TransactionType.Refund: { const refund = await tx.getRefundGroup(id.refundGroupId); if (refund) - for (const url of await purchaseExchangeUrls(tx, refund.proposalId)) + for (const url of refundExchangeUrls( + await resolveRefundSnapshot(tx, refund), + )) urls.add(url); break; } diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts @@ -13,6 +13,7 @@ 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 { migrateRefundPurchaseSnapshots } from "./refund-history.js"; import { Amounts, AmountString, @@ -89,7 +90,6 @@ import { isSharedPurchase, isStableMerchantPayFailure, isTransientRefundStatus, - migrateRefundPurchaseSnapshots, PayMerchantTransactionContext, RefundTransactionContext, recoveredPayFailureStatus, @@ -980,6 +980,10 @@ for (const makeRunner of runnerFactories) { } as unknown as WalletExecutionContext; try { await runner.runReadWriteTx(async (tx) => { + await tx.upsertConfig({ + key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, + value: 1, + }); await upsertTestContractTerms(tx, good); await tx.upsertPurchase(good); await tx.upsertPurchase(delayed); @@ -998,7 +1002,11 @@ for (const makeRunner of runnerFactories) { ); } await tx.upsertRefundGroup( - makeTestRefundGroup("snapshot-orphan", "snapshot-orphan-group"), + makeTestRefundGroup( + "snapshot-orphan", + "snapshot-orphan-group", + RefundGroupStatus.Pending, + ), ); }); @@ -1014,13 +1022,28 @@ for (const makeRunner of runnerFactories) { ), })); assert.strictEqual( - stored.good?.purchaseSnapshot?.paymentInfo.summary, + stored.good?.purchaseSnapshot?.paymentInfo?.summary, "Refund test", ); - assert.strictEqual(stored.delayed?.purchaseSnapshot, undefined); - assert.strictEqual(stored.broken?.purchaseSnapshot, undefined); + assert.strictEqual( + stored.delayed?.purchaseSnapshot?.orderId, + delayed.orderId, + ); + assert.strictEqual( + stored.delayed?.purchaseSnapshot?.paymentInfo, + undefined, + ); + assert.strictEqual( + stored.broken?.purchaseSnapshot?.orderId, + broken.orderId, + ); + assert.strictEqual( + stored.broken?.purchaseSnapshot?.paymentInfo, + undefined, + ); assert.strictEqual(stored.orphan?.purchaseSnapshot, undefined); - assert.strictEqual(stored.version, undefined); + assert.equal(stored.orphan?.status, RefundGroupStatus.Aborted); + assert.strictEqual(stored.version?.value, 1); await runner.runReadWriteTx(async (tx) => { await upsertTestContractTerms(tx, delayed); @@ -1038,10 +1061,10 @@ for (const makeRunner of runnerFactories) { ), })); assert.strictEqual( - stored.delayed?.purchaseSnapshot?.paymentInfo.summary, + stored.delayed?.purchaseSnapshot?.paymentInfo?.summary, "Refund test", ); - assert.strictEqual(stored.version?.value, 1); + assert.strictEqual(stored.version?.value, 2); } finally { await runner.close(); } @@ -1064,7 +1087,7 @@ for (const makeRunner of runnerFactories) { ); await tx.upsertConfig({ key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, - value: 2, + value: 3, }); }); @@ -1077,7 +1100,7 @@ for (const makeRunner of runnerFactories) { ), })); assert.strictEqual(stored.group?.purchaseSnapshot, undefined); - assert.strictEqual(stored.version?.value, 2); + assert.strictEqual(stored.version?.value, 3); } finally { await runner.close(); } @@ -1110,7 +1133,7 @@ for (const makeRunner of runnerFactories) { tx.getRefundGroup(doneGroupId), ); assert.strictEqual( - group?.purchaseSnapshot?.paymentInfo.summary, + group?.purchaseSnapshot?.paymentInfo?.summary, "Refund test", ); } finally { @@ -1145,8 +1168,30 @@ for (const makeRunner of runnerFactories) { await tx.upsertPurchase(purchase); }); - await storeRefunds(wex, purchase, [], RefundReason.AbortRefund); - + await storeRefunds( + wex, + purchase, + [ + { + type: "failure", + exchange_status: 404, + exchange_code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN, + exchange_reply: {}, + coin_pub: encodeCrock(new Uint8Array(32)), + rtransaction_id: 1, + refund_amount: "TESTKUDOS:1", + execution_time: { t_s: 3 }, + }, + ], + RefundReason.NormalRefund, + ); + const [refund] = await runner.runReadWriteTx((tx) => + tx.getRefundGroupsByProposal(purchase.proposalId), + ); + assert.equal( + refund.purchaseSnapshot?.paymentInfo?.merchant.name, + "sandbox merchant", + ); assert.strictEqual( ( await runner.runReadWriteTx((tx) => diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -158,11 +158,17 @@ import { WalletPurchasePayInfo, WalletRefundGroup, WalletRefundItem, - WalletRefundPurchaseSnapshot, WalletRefreshGroup, WalletSlate, WalletToken, } from "./db/records.js"; +import { + recoverRefundSnapshot, + refundScopes, + resolveRefundSnapshot, + writeRefundMeta, +} from "./refund-history.js"; +import { refundReasonForPurchase } from "./transaction-amounts.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { acceptDonauBlindSigs, generateDonauPlanchets } from "./donau.js"; import { @@ -890,130 +896,6 @@ async function computePayMerchantTransactionScopesInTx( ]; } -export async function createRefundPurchaseSnapshot( - tx: WalletDbTransaction, - purchase: WalletPurchase, -): Promise<WalletRefundPurchaseSnapshot | undefined> { - if (!purchase.download) { - return undefined; - } - const contractTermsRecord = await tx.getContractTerms( - purchase.download.contractTermsHash, - ); - if (!contractTermsRecord) { - return undefined; - } - const contractTerms = codecForMerchantContractTerms().decode( - contractTermsRecord.contractTermsRaw, - ); - const amounts = getPayMerchantTransactionAmounts( - contractTerms, - purchase, - computePayMerchantTransactionState(purchase), - ); - const exchanges = await computePayMerchantExchangesInTx(tx, purchase); - const scopes = await computePayMerchantTransactionScopesInTx(tx, purchase); - const legacyScopes = await getLegacyScopesForTransaction(tx, { - currency: amounts.currency, - exchanges, - coinPubs: purchase.payInfo?.payCoinSelection?.coinPubs, - }); - return { - paymentInfo: { - merchant: contractTerms.merchant, - summary: contractTerms.summary, - summary_i18n: contractTerms.summary_i18n, - }, - merchantBaseUrl: purchase.merchantBaseUrl, - orderId: contractTerms.order_id, - scopes, - exchanges, - legacyScopes, - }; -} - -const REFUND_PURCHASE_SNAPSHOTS_VERSION = 1; - -export async function migrateRefundPurchaseSnapshotsInTx( - tx: WalletDbTransaction, -): Promise<void> { - const version = await tx.getConfig( - ConfigRecordKey.RefundPurchaseSnapshotsVersion, - ); - if (version?.value === REFUND_PURCHASE_SNAPSHOTS_VERSION) { - return; - } - if ( - version !== undefined && - version.value > REFUND_PURCHASE_SNAPSHOTS_VERSION - ) { - logger.error( - "database is newer than code (refundPurchaseSnapshotsVersion)", - ); - return; - } - let complete = true; - for (const refundGroup of await tx.listAllRefundGroups()) { - if (refundGroup.purchaseSnapshot) { - continue; - } - const purchase = await tx.getPurchase(refundGroup.proposalId); - if (!purchase) { - continue; - } - let purchaseSnapshot: WalletRefundPurchaseSnapshot | undefined; - try { - purchaseSnapshot = await createRefundPurchaseSnapshot(tx, purchase); - } catch (e) { - complete = false; - logger.warn( - `could not backfill refund purchase snapshot for ${refundGroup.refundGroupId}: ${safeStringifyException(e)}`, - ); - continue; - } - if (!purchaseSnapshot) { - complete = false; - continue; - } - refundGroup.purchaseSnapshot = purchaseSnapshot; - await tx.upsertRefundGroup(refundGroup); - } - if (!complete) { - return; - } - await tx.upsertConfig({ - key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, - value: REFUND_PURCHASE_SNAPSHOTS_VERSION, - }); -} - -export async function migrateRefundPurchaseSnapshots( - wex: WalletExecutionContext, -): Promise<void> { - await wex.runWalletDbTx(migrateRefundPurchaseSnapshotsInTx); -} - -async function resolveRefundPurchaseSnapshot( - tx: WalletDbTransaction, - refundGroup: WalletRefundGroup, -): Promise<WalletRefundPurchaseSnapshot | undefined> { - if (refundGroup.purchaseSnapshot) { - return refundGroup.purchaseSnapshot; - } - const purchase = await tx.getPurchase(refundGroup.proposalId); - if (!purchase) { - return undefined; - } - try { - return await createRefundPurchaseSnapshot(tx, purchase); - } catch (e) { - logger.warn( - `could not reconstruct refund purchase snapshot for ${refundGroup.refundGroupId}: ${safeStringifyException(e)}`, - ); - return undefined; - } -} - export class RefundTransactionContext implements TransactionContext { public transactionId: TransactionIdStr; public taskId: TaskIdStr | undefined = undefined; @@ -1039,16 +921,11 @@ export class RefundTransactionContext implements TransactionContext { await tx.deleteTransactionMeta(this.transactionId); return; } - const purchaseSnapshot = await resolveRefundPurchaseSnapshot(tx, refundRec); - const exchanges = purchaseSnapshot?.exchanges ?? []; - await tx.upsertTransactionMeta({ - transactionId: this.transactionId, - status: refundRec.status, - timestamp: refundRec.timestampCreated, - currency: Amounts.currencyOf(refundRec.amountEffective), - exchanges, - legacyScopes: purchaseSnapshot?.legacyScopes ?? [], - }); + await writeRefundMeta( + tx, + refundRec, + await resolveRefundSnapshot(tx, refundRec), + ); } async lookupFullTransaction( @@ -1058,17 +935,10 @@ export class RefundTransactionContext implements TransactionContext { if (!refundRecord) { return undefined; } - const purchaseSnapshot = await resolveRefundPurchaseSnapshot( - tx, - refundRecord, - ); + const purchaseSnapshot = await resolveRefundSnapshot(tx, refundRecord); const paymentInfo = purchaseSnapshot?.paymentInfo; - const scopes = purchaseSnapshot?.scopes ?? [ - { - type: ScopeType.Global, - currency: Amounts.currencyOf(refundRecord.amountEffective), - }, - ]; + const currency = Amounts.currencyOf(refundRecord.amountEffective); + const scopes = await refundScopes(tx, currency, purchaseSnapshot); return { type: TransactionType.Refund, scopes, @@ -6068,7 +5938,8 @@ export function classifyMerchantAbortRecoveryEvidence( (x) => x.coinPub === coinPub && x.rtxid === 0 && - x.status !== RefundItemStatus.Failed, + (x.status === RefundItemStatus.Done || + x.status === RefundItemStatus.Pending), ); if (!refundItem) { return "failed"; @@ -6581,21 +6452,7 @@ export async function storeRefunds( return; } - let purchaseSnapshot: WalletRefundPurchaseSnapshot | undefined; - try { - purchaseSnapshot = await createRefundPurchaseSnapshot(tx, myPurchase); - } catch (e) { - logger.warn( - `could not create refund purchase snapshot for ${myPurchase.proposalId}: ${safeStringifyException(e)}`, - ); - } - if (!purchaseSnapshot) { - logger.warn( - `refund purchase snapshot unavailable for ${purchase.proposalId}`, - ); - } let newGroup: WalletRefundGroup | undefined = undefined; - const newGroupRefunds: WalletRefundItem[] = []; const newlySuccessfulRefunds = new Set<string>(); const refundKey = (coinPub: string, rtxid: number) => `${coinPub}\0${rtxid}`; @@ -6636,7 +6493,6 @@ export async function storeRefunds( status: RefundGroupStatus.Pending, timestampCreated: timestampPreciseToDb(now), refundReason: reason, - ...(purchaseSnapshot ? { purchaseSnapshot } : {}), amountEffective: Amounts.stringify( Amounts.zeroOfCurrency(currency), ), @@ -6654,7 +6510,6 @@ export async function storeRefunds( status, failReason: getPermanentRefundReason(rf), }; - newGroupRefunds.push(newItem); if (status === RefundItemStatus.Done) { newlySuccessfulRefunds.add(refundKey(newItem.coinPub, newItem.rtxid)); } @@ -6668,6 +6523,12 @@ export async function storeRefunds( wex, newGroup.refundGroupId, ); + newGroup.purchaseSnapshot = await recoverRefundSnapshot( + tx, + newGroup, + myPurchase, + download.contractTerms, + ); await tx.upsertRefundGroup(newGroup); await refundCtx.updateTransactionMeta(tx); applyNotifyTransition(tx.notify, refundCtx.transactionId, { @@ -6690,16 +6551,26 @@ export async function storeRefunds( wex, refundGroup.refundGroupId, ); - const addedPurchaseSnapshot = - purchaseSnapshot !== undefined && !refundGroup.purchaseSnapshot; - if (addedPurchaseSnapshot) { - refundGroup.purchaseSnapshot = purchaseSnapshot; + const needsHistory = + !refundGroup.purchaseSnapshot?.exchangeIdentities || + !refundGroup.purchaseSnapshot.paymentInfo || + !refundGroup.refundReason; + if (needsHistory) { + refundGroup.purchaseSnapshot = await recoverRefundSnapshot( + tx, + refundGroup, + myPurchase, + download.contractTerms, + ); + refundGroup.refundReason ??= refundReasonForPurchase( + myPurchase.purchaseStatus, + ); } switch (refundGroup.status) { case RefundGroupStatus.Aborted: case RefundGroupStatus.Expired: case RefundGroupStatus.Done: - if (addedPurchaseSnapshot) { + if (needsHistory) { await tx.upsertRefundGroup(refundGroup); await refundCtx.updateTransactionMeta(tx); } @@ -6795,6 +6666,7 @@ export async function storeRefunds( } else { refundGroup.status = RefundGroupStatus.Pending; await tx.upsertRefundGroup(refundGroup); + await refundCtx.updateTransactionMeta(tx); } } const shouldCheckAutoRefund = diff --git a/packages/taler-wallet-core/src/refund-history.ts b/packages/taler-wallet-core/src/refund-history.ts @@ -0,0 +1,295 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { + Amounts, + codecForMerchantContractTerms, + Logger, + MerchantContractTerms, + ScopeInfo, + ScopeInfoExchangeLegacyKeys, + ScopeType, + stringifyScopeInfo, + TransactionMajorState, + TransactionType, +} from "@gnu-taler/taler-util"; +import { + ConfigRecordKey, + RefundGroupStatus, + RefundItemStatus, + RefundReason, + WalletPurchase, + WalletRefundExchangeIdentity, + WalletRefundGroup, + WalletRefundPurchaseSnapshot, +} from "./db/records.js"; +import type { WalletDbTransaction } from "./db/transaction.js"; +import { getExchangeScopeInfo } from "./exchanges.js"; +import { refundReasonForPurchase } from "./transaction-amounts.js"; +import { + applyNotifyTransition, + BalanceEffect, + constructTransactionIdentifier, +} from "./transactions.js"; +import type { WalletExecutionContext } from "./wallet.js"; + +const logger = new Logger("refund-history.ts"); +const REFUND_PURCHASE_SNAPSHOTS_VERSION = 2; + +async function readContractTerms( + tx: WalletDbTransaction, + purchase?: WalletPurchase, +) { + if (!purchase?.download) return; + const record = await tx.getContractTerms(purchase.download.contractTermsHash); + if (!record) return; + try { + return codecForMerchantContractTerms().decode(record.contractTermsRaw); + } catch (e) { + logger.warn( + `unreadable contract for refund of ${purchase.proposalId}: ${e}`, + ); + return undefined; + } +} + +/** Recover each available fact independently, including when contract terms are missing. */ +export async function recoverRefundSnapshot( + tx: WalletDbTransaction, + refund: WalletRefundGroup, + purchase: WalletPurchase | undefined, + terms?: MerchantContractTerms, +): Promise<WalletRefundPurchaseSnapshot | undefined> { + const saved = refund.purchaseSnapshot; + let paymentInfo = saved?.paymentInfo; + if (!paymentInfo) { + terms ??= await readContractTerms(tx, purchase); + if (terms) + paymentInfo = { + merchant: terms.merchant, + summary: terms.summary, + summary_i18n: terms.summary_i18n, + }; + } + + const issuers = new Map<string, Set<string>>(); + function addIssuer(url: string, masterPub?: string) { + let keys = issuers.get(url); + if (!keys) { + keys = new Set(); + issuers.set(url, keys); + } + if (masterPub) keys.add(masterPub); + } + for (const issuer of saved?.exchangeIdentities ?? []) + addIssuer(issuer.url, issuer.masterPub); + const items = await tx.getRefundItemsByGroup(refund.refundGroupId); + const coinPubs = new Set( + items.length + ? items.map((item) => item.coinPub) + : purchase?.payInfo?.payCoinSelection?.coinPubs, + ); + const coins = await tx.getCoinsByPubs([...coinPubs]); + for (const coin of coins) + addIssuer(coin.exchangeBaseUrl, coin.exchangeMasterPub); + // Version 1 classified the whole payment. Prefer the actual refund coins + // when available. Its URL list alone could be the merchant's contract offers. + if (!items.length || coins.length < coinPubs.size) { + for (const scope of [ + ...(saved?.legacyScopes ?? []), + ...(saved?.scopes ?? []), + ]) { + if (scope.type === ScopeType.ExchangeLegacyKeys) + addIssuer(scope.url, scope.masterPub); + } + } + // For missing coins a single participating exchange is unambiguous. Older + // groups without any item records retain the known payment participants. + const participants = purchase?.exchanges ?? []; + if ( + !items.length || + (coins.length < coinPubs.size && participants.length === 1) + ) { + for (const url of participants) addIssuer(url); + } + if (!purchase && !saved && !issuers.size) return undefined; + const exchangeIdentities: WalletRefundExchangeIdentity[] = []; + for (const [url, keys] of issuers) { + if (!keys.size) exchangeIdentities.push({ url }); + for (const masterPub of keys) exchangeIdentities.push({ url, masterPub }); + } + return { + merchantBaseUrl: saved?.merchantBaseUrl ?? purchase?.merchantBaseUrl, + orderId: saved?.orderId ?? terms?.order_id ?? purchase?.orderId, + paymentInfo, + exchangeIdentities, + }; +} + +/** Read-only fallback for wallets awaiting backfill. */ +export async function resolveRefundSnapshot( + tx: WalletDbTransaction, + refund: WalletRefundGroup, +) { + const saved = refund.purchaseSnapshot; + if (saved?.exchangeIdentities && saved.paymentInfo) return saved; + const purchase = await tx.getPurchase(refund.proposalId); + if (!purchase && saved?.exchangeIdentities) return saved; + return recoverRefundSnapshot(tx, refund, purchase); +} + +export function refundExchangeUrls( + snapshot?: WalletRefundPurchaseSnapshot, +): string[] { + return [ + ...new Set(snapshot?.exchangeIdentities?.map((issuer) => issuer.url)), + ]; +} + +export async function refundScopes( + tx: WalletDbTransaction, + currency: string, + snapshot?: WalletRefundPurchaseSnapshot, +): Promise<ScopeInfo[]> { + const scopes = new Map<string, ScopeInfo>(); + for (const url of refundExchangeUrls(snapshot)) { + const current = await getExchangeScopeInfo(tx, url, currency); + const scope: ScopeInfo = + current.currency === currency + ? current + : { type: ScopeType.Exchange, currency, url }; + scopes.set(stringifyScopeInfo(scope), scope); + } + return scopes.size + ? [...scopes.values()] + : [{ type: ScopeType.Global, currency }]; +} + +export async function writeRefundMeta( + tx: WalletDbTransaction, + refund: WalletRefundGroup, + snapshot: WalletRefundPurchaseSnapshot | undefined, +) { + const currency = Amounts.currencyOf(refund.amountEffective); + const exchanges = refundExchangeUrls(snapshot); + const legacyScopes: ScopeInfoExchangeLegacyKeys[] = []; + for (const url of exchanges) { + const current = (await tx.getExchange(url))?.detailsPointer; + if (!current) continue; + for (const issuer of snapshot?.exchangeIdentities ?? []) { + if ( + issuer.url === url && + issuer.masterPub && + (issuer.masterPub !== current.masterPublicKey || + currency !== current.currency) + ) { + legacyScopes.push({ + type: ScopeType.ExchangeLegacyKeys, + currency, + url, + masterPub: issuer.masterPub, + }); + } + } + } + await tx.upsertTransactionMeta({ + transactionId: constructTransactionIdentifier({ + tag: TransactionType.Refund, + refundGroupId: refund.refundGroupId, + }), + status: refund.status, + timestamp: refund.timestampCreated, + currency, + exchanges, + legacyScopes, + }); +} + +/** Save history before its purchase disappears, or repair a previously detached group. */ +export async function retainRefundHistory( + tx: WalletDbTransaction, + refund: WalletRefundGroup, + purchase: WalletPurchase | undefined, + detach: boolean, +): Promise<void> { + refund.purchaseSnapshot = await recoverRefundSnapshot(tx, refund, purchase); + if (!refund.refundReason) { + if (purchase) + refund.refundReason = refundReasonForPurchase(purchase.purchaseStatus); + else if (refund.transactionAmounts?.isAbortRecovery !== undefined) { + refund.refundReason = refund.transactionAmounts.isAbortRecovery + ? RefundReason.AbortRefund + : RefundReason.NormalRefund; + } + } + const stopped = detach && refund.status === RefundGroupStatus.Pending; + if (stopped) { + for (const item of await tx.getRefundItemsByGroup(refund.refundGroupId)) { + if (item.status !== RefundItemStatus.Pending) continue; + item.status = RefundItemStatus.Aborted; + await tx.upsertRefundItem(item); + } + refund.status = RefundGroupStatus.Aborted; + } + await tx.upsertRefundGroup(refund); + await writeRefundMeta(tx, refund, refund.purchaseSnapshot); + if (stopped) { + applyNotifyTransition( + tx.notify, + constructTransactionIdentifier({ + tag: TransactionType.Refund, + refundGroupId: refund.refundGroupId, + }), + { + causeHint: "refund-collection-stopped", + oldTxState: { major: TransactionMajorState.Pending }, + newTxState: { major: TransactionMajorState.Aborted }, + oldStId: RefundGroupStatus.Pending, + newStId: RefundGroupStatus.Aborted, + balanceEffect: BalanceEffect.Any, + }, + ); + } +} + +export async function migrateRefundPurchaseSnapshotsInTx( + tx: WalletDbTransaction, +): Promise<void> { + const version = await tx.getConfig( + ConfigRecordKey.RefundPurchaseSnapshotsVersion, + ); + if (version && version.value > REFUND_PURCHASE_SNAPSHOTS_VERSION) { + logger.error( + "database is newer than code (refundPurchaseSnapshotsVersion)", + ); + return; + } + if (version?.value === REFUND_PURCHASE_SNAPSHOTS_VERSION) return; + let complete = true; + for (const refund of await tx.listAllRefundGroups()) { + const purchase = await tx.getPurchase(refund.proposalId); + if ( + refund.purchaseSnapshot?.exchangeIdentities && + refund.purchaseSnapshot.paymentInfo && + refund.refundReason && + (refund.status !== RefundGroupStatus.Pending || purchase) + ) + continue; + await retainRefundHistory(tx, refund, purchase, !purchase); + if (purchase && !refund.purchaseSnapshot?.paymentInfo) complete = false; + } + if (complete) + await tx.upsertConfig({ + key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, + value: REFUND_PURCHASE_SNAPSHOTS_VERSION, + }); +} + +export async function migrateRefundPurchaseSnapshots( + wex: WalletExecutionContext, +): Promise<void> { + await wex.runWalletDbTx(migrateRefundPurchaseSnapshotsInTx); +} diff --git a/packages/taler-wallet-core/src/requests.test.ts b/packages/taler-wallet-core/src/requests.test.ts @@ -443,7 +443,7 @@ test("importDb request converts a foreign backend dump", async () => { tx.getRefundGroup("request-import-refund"), ); assert.strictEqual( - importedRefund?.purchaseSnapshot?.paymentInfo.merchant.name, + importedRefund?.purchaseSnapshot?.paymentInfo?.merchant.name, "import merchant", ); assert.strictEqual( @@ -456,7 +456,7 @@ test("importDb request converts a foreign backend dump", async () => { tx.getConfig(ConfigRecordKey.RefundPurchaseSnapshotsVersion), ) )?.value, - 1, + 2, ); assert.ok( progress.some( diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -15,6 +15,10 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ +import { + migrateRefundPurchaseSnapshots, + migrateRefundPurchaseSnapshotsInTx, +} from "./refund-history.js"; import { repairLegacyRecoupState } from "./recoup.js"; /** @@ -388,8 +392,6 @@ import { collectLeftoverClaims, confirmPay, getChoicesForPayment, - migrateRefundPurchaseSnapshots, - migrateRefundPurchaseSnapshotsInTx, preparePayForTemplateV2, preparePayForUriV2, reclaimPayment, diff --git a/packages/taler-wallet-core/src/transaction-amounts.ts b/packages/taler-wallet-core/src/transaction-amounts.ts @@ -50,6 +50,15 @@ const terminal = (status: number) => status >= OPERATION_STATUS_DONE_FIRST; const successful = (status: number) => status >= OPERATION_STATUS_DONE_FIRST && status <= OPERATION_STATUS_DONE_LAST; +/** Classify historical refunds created before the wallet recorded their reason. */ +export function refundReasonForPurchase(status: PurchaseStatus): RefundReason { + return status === PurchaseStatus.AbortingWithRefund || + status === PurchaseStatus.SuspendedAbortingWithRefund || + (terminal(status) && !successful(status)) + ? RefundReason.AbortRefund + : RefundReason.NormalRefund; +} + async function source( tx: WalletDbTransaction, transactionId: string, @@ -237,18 +246,13 @@ async function calculate( return a; } if (type === TransactionType.Refund) { - const payment = s.refundPaymentId - ? await tx.getPurchase(s.refundPaymentId) - : undefined; - if (s.refundReason !== undefined) { - a.isAbortRecovery = s.refundReason === RefundReason.AbortRefund; - } else if (payment) { - a.isAbortRecovery = - payment.purchaseStatus === PurchaseStatus.AbortingWithRefund || - payment.purchaseStatus === PurchaseStatus.SuspendedAbortingWithRefund || - (terminal(payment.purchaseStatus) && - !successful(payment.purchaseStatus)); + let reason = s.refundReason; + if (reason === undefined && s.refundPaymentId) { + const payment = await tx.getPurchase(s.refundPaymentId); + if (payment) reason = refundReasonForPurchase(payment.purchaseStatus); } + if (reason !== undefined) + a.isAbortRecovery = reason === RefundReason.AbortRefund; const outputs = { ...a.refreshOutputs }; const unsettled = new Set(a.unsettledRefreshIds); const ids = new Set([