taler-typescript-core

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

commit 8c486806206f02e46c820933bb93718778aa51ed
parent b8e65e4d9088c51e74b3e5f018d164f61d820508
Author: Florian Dold <dold@taler.net>
Date:   Tue, 24 Nov 2026 17:06:26 +0100

wallet-core: keep unrelated refunds when purging an exchange

A payment can use two exchanges even when only one issued the refunded
coins. Use the issuer and denomination of each refund coin to decide
which refunds to purge and which auditor scopes apply.

Older wallets counted pending and failed items in the refunded amount.
Recalculate that total from confirmed items when upgrading a stopped
refund.

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

Diffstat:
Mpackages/taler-wallet-core/src/db/records.ts | 18+++++++++++++-----
Mpackages/taler-wallet-core/src/exchanges.test.ts | 12++++++++++--
Mpackages/taler-wallet-core/src/exchanges.ts | 54++++++++++++++++++++++++++----------------------------
Mpackages/taler-wallet-core/src/observe-transaction.test.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mpackages/taler-wallet-core/src/pay-merchant.test.ts | 172++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mpackages/taler-wallet-core/src/pay-merchant.ts | 6+++---
Mpackages/taler-wallet-core/src/refund-history.ts | 143+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mpackages/taler-wallet-core/src/requests.test.ts | 2+-
8 files changed, 351 insertions(+), 117 deletions(-)

diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -1119,9 +1119,14 @@ export interface WalletPurchase { talerUri?: string; } -export interface WalletRefundExchangeIdentity { +export interface WalletRefundIssuer { url: string; + /** + * Master public key of the exchange that issued the refunded coin, as + * recorded on the coin at issuance. Absent when only the URL is known. + */ masterPub?: string; + denomPubHash?: string; } /** Purchase and issuing-exchange facts retained by a refund. */ @@ -1129,9 +1134,11 @@ export interface WalletRefundPurchaseSnapshot { 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. */ + /** Issuers established for this refund. Keep the denomination for auditor scopes. */ + issuers?: WalletRefundIssuer[]; + /** Version 2 could include keys from other coins in the same payment. */ + exchangeIdentities?: { url: string; masterPub?: string }[]; + /** Version 1 recorded payment-wide scopes and could include offered exchanges. */ scopes?: ScopeInfo[]; exchanges?: string[]; legacyScopes?: ScopeInfoExchangeLegacyKeys[]; @@ -1160,7 +1167,8 @@ export interface WalletRefundGroup { /** * Purchase and exchange facts available when the refund was recorded or repaired. - * Older detached refunds can lack merchant details. + * A detached refund without a prior snapshot has no contract hash from which + * to recover its merchant and order. It does not block migration completion. */ purchaseSnapshot?: WalletRefundPurchaseSnapshot; refundReason?: RefundReason; diff --git a/packages/taler-wallet-core/src/exchanges.test.ts b/packages/taler-wallet-core/src/exchanges.test.ts @@ -296,6 +296,7 @@ for (const makeRunner of runnerFactories) { exchangeBaseUrl, otherExchangeBaseUrl, exchangeBaseUrl, + exchangeBaseUrl, ].entries()) { const refundGroupId = `detached-refund-${index}`; await tx.upsertRefundGroup({ @@ -315,7 +316,9 @@ for (const makeRunner of runnerFactories) { orderId: `order-${index}`, ...(index === 2 ? { exchanges: [url] } - : { exchangeIdentities: [{ url }] }), + : index === 3 + ? { exchangeIdentities: [{ url }] } + : { issuers: [{ url }] }), }, }); await tx.upsertRefundItem({ @@ -344,16 +347,21 @@ for (const makeRunner of runnerFactories) { retainedGroup: await tx.getRefundGroup("detached-refund-1"), retainedItems: await tx.getRefundItemsByGroup("detached-refund-1"), unverifiedGroup: await tx.getRefundGroup("detached-refund-2"), + uncertainV2Group: await tx.getRefundGroup("detached-refund-3"), })); assert.strictEqual(result.exchange, undefined); assert.strictEqual(result.deletedGroup, undefined); assert.deepStrictEqual(result.deletedItems, []); assert.strictEqual( - result.retainedGroup?.purchaseSnapshot?.exchangeIdentities?.[0].url, + result.retainedGroup?.purchaseSnapshot?.issuers?.[0].url, otherExchangeBaseUrl, ); assert.strictEqual(result.retainedItems.length, 1); assert.ok( + result.uncertainV2Group, + "version 2 payment-wide evidence cannot authorize a purge", + ); + assert.ok( result.unverifiedGroup, "a legacy contract offer alone cannot establish ownership", ); diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -187,6 +187,7 @@ import { selectBestForOverlappingDenominations, selectMinimumFee, } from "./denominations.js"; +import { refundExchangeUrls, resolveRefundSnapshot } from "./refund-history.js"; import { hasVerifiedAuditorTrust } from "./auditorTrust.js"; import { DepositTransactionContext } from "./deposits.js"; import { @@ -572,8 +573,11 @@ export async function getExchangeScopeInfo( exchangeBaseUrl: string, currency: string, denomPubHash?: string, + masterPub?: string, ): Promise<ScopeInfo> { - const det = await getExchangeRecordsInternal(tx, exchangeBaseUrl); + const det = masterPub + ? await tx.getExchangeDetailsByPointer(exchangeBaseUrl, currency, masterPub) + : await getExchangeRecordsInternal(tx, exchangeBaseUrl); if (!det) { return { type: ScopeType.Exchange, @@ -4514,6 +4518,27 @@ async function purgeExchange( purgeTransactions?: boolean, ): Promise<void> { const exchangeBaseUrl = exchangeRec.baseUrl; + if (purgeTransactions) { + // Resolve ownership before deleting the coins. Deleting a payment retains + // refund groups whose coins were issued by another exchange. + for (const purchase of await tx.getPurchasesByExchange(exchangeBaseUrl)) { + await new PayMerchantTransactionContext( + wex, + purchase.proposalId, + ).deleteTransactionInTx(tx); + } + for (const refund of await tx.listAllRefundGroups()) { + const snapshot = refund.purchaseSnapshot?.issuers + ? refund.purchaseSnapshot + : await resolveRefundSnapshot(tx, refund); + if (refundExchangeUrls(snapshot).includes(exchangeBaseUrl)) { + await new RefundTransactionContext( + wex, + refund.refundGroupId, + ).deleteTransactionInTx(tx); + } + } + } const detRecs = await tx.listAllExchangeDetails(); // Remove all exchange detail records for that exchange for (const r of detRecs) { @@ -4618,33 +4643,6 @@ async function purgeExchange( } } } - // Remove from purchases, refundGroups, refundItems - { - const purchases = await tx.getPurchasesByExchange(exchangeBaseUrl); - for (const purch of purchases) { - const refunds = await tx.getRefundGroupsByProposal(purch.proposalId); - for (const r of refunds) { - const refundCtx = new RefundTransactionContext(wex, r.refundGroupId); - await refundCtx.deleteTransactionInTx(tx); - } - const payCtx = new PayMerchantTransactionContext(wex, purch.proposalId); - await payCtx.deleteTransactionInTx(tx); - } - for (const refund of await tx.listAllRefundGroups()) { - if ( - !refund.purchaseSnapshot?.exchangeIdentities?.some( - (issuer) => issuer.url === exchangeBaseUrl, - ) - ) { - continue; - } - const refundCtx = new RefundTransactionContext( - wex, - refund.refundGroupId, - ); - await refundCtx.deleteTransactionInTx(tx); - } - } // Remove from peerPullCredit { const recs = await tx.listAllPeerPullCredits(); diff --git a/packages/taler-wallet-core/src/observe-transaction.test.ts b/packages/taler-wallet-core/src/observe-transaction.test.ts @@ -1593,17 +1593,35 @@ for (const makeRunner of runnerFactories) { const f = await fixture(makeRunner); const currency = "TESTKUDOS"; const id = "txn:refund:retained"; + const auditorUrl = "https://auditor.example/"; + const coinPub = encodeCrock(new Uint8Array(32).fill(1)); + const denomPubHash = encodeCrock(new Uint8Array(64).fill(2)); + const auditorPub = encodeCrock(new Uint8Array(32).fill(4)); try { await f.wex.runWalletDbTx(async (tx) => { - await tx.upsertGlobalCurrencyExchange({ + await tx.upsertGlobalCurrencyAuditor({ currency, - exchangeBaseUrl: exchangeUrl, - exchangeMasterPub: master, + auditorBaseUrl: auditorUrl, + auditorPub, + }); + await tx.upsertExchangeDetails({ + ...f.details, + auditors: [ + { + auditor_name: "Auditor", + auditor_pub: auditorPub, + auditor_url: auditorUrl, + walletAuditorSignaturesVerified: true, + denomination_keys: [ + { denom_pub_h: denomPubHash, auditor_sig: master }, + ], + }, + ], }); await tx.upsertCoin({ - coinPub: master, + coinPub, coinPriv: master, - denomPubHash: master, + denomPubHash, denomSig: { cipher: DenomKeyType.Rsa, rsa_signature: master }, exchangeBaseUrl: exchangeUrl, exchangeMasterPub: master, @@ -1637,7 +1655,7 @@ for (const makeRunner of runnerFactories) { summary_i18n: undefined, }, exchanges: [exchangeUrl, "https://offered-but-unused.example/"], - scopes: [{ type: ScopeType.Global, currency }], + scopes: [{ type: ScopeType.Auditor, currency, url: auditorUrl }], legacyScopes: [ { type: ScopeType.ExchangeLegacyKeys, @@ -1650,17 +1668,45 @@ for (const makeRunner of runnerFactories) { }); await tx.upsertRefundItem({ refundGroupId: "retained", - coinPub: master, + coinPub, rtxid: 1, refundAmount: "TESTKUDOS:3", status: RefundItemStatus.Done, obtainedTime: f.credit.timestamp, executionTime: timestampProtocolToDb({ t_s: 1 }), }); + // This missing refund coin must not import another participant's key + // from the payment-wide version 1 snapshot. + await tx.upsertRefundItem({ + refundGroupId: "retained", + coinPub: oldMaster, + rtxid: 2, + refundAmount: "TESTKUDOS:1", + status: RefundItemStatus.Failed, + obtainedTime: f.credit.timestamp, + executionTime: timestampProtocolToDb({ t_s: 1 }), + }); }); await migrateRefundPurchaseSnapshots(f.wex); const read = () => f.wex.runWalletDbTx((tx) => readTransactionSnapshot(f.wex, tx, id)); + await f.wex.runWalletDbTx((tx) => tx.deleteCoin(coinPub)); + const audited = await read(); + assert.ok(audited?.type === TransactionType.Refund); + assert.deepEqual(audited.transaction.scopes, [ + { type: ScopeType.Auditor, currency, url: auditorUrl }, + ]); + assert.deepEqual( + audited.exchanges.map((x) => x.exchangeBaseUrl), + [exchangeUrl], + ); + await f.wex.runWalletDbTx((tx) => + tx.upsertGlobalCurrencyExchange({ + currency, + exchangeBaseUrl: exchangeUrl, + exchangeMasterPub: master, + }), + ); const before = await read(); assert.ok(before?.type === TransactionType.Refund); assert.deepEqual(before.transaction.scopes, [ @@ -1671,7 +1717,6 @@ for (const makeRunner of runnerFactories) { [exchangeUrl], ); await f.wex.runWalletDbTx(async (tx) => { - await tx.deleteCoin(master); await tx.upsertExchangeDetails({ ...f.details, rowId: undefined, diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts @@ -19,6 +19,8 @@ import { AmountString, buildSigPS, CancellationToken, + CoinStatus, + DenomKeyType, LongpollQueue, ContractTermsUtil, decodeCrock, @@ -50,6 +52,9 @@ import { test } from "node:test"; import { PurchaseStatus, ConfigRecordKey, + CoinSourceType, + ExchangeEntryDbRecordStatus, + ExchangeEntryDbUpdateStatus, RefreshCoinStatus, RefreshOperationStatus, RefundGroupStatus, @@ -102,6 +107,7 @@ import { validateClaimResponseBindings, partitionPayCoinSelectionForRepair, } from "./pay-merchant.js"; +import { deleteExchange } from "./exchanges.js"; import { makeIdbRunner, runnerFactories } from "./db/testing/runners.js"; import type { WalletExecutionContext } from "./wallet.js"; import { nativeCrypto } from "./crypto/cryptoImplementation.js"; @@ -714,7 +720,7 @@ for (const makeRunner of runnerFactories) { // capture the history even when startup has no outstanding migration. await tx.upsertConfig({ key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, - value: 2, + value: 3, }); await upsertTestContractTerms(tx, purchase); await tx.upsertPurchase(purchase); @@ -804,6 +810,161 @@ for (const makeRunner of runnerFactories) { } }); + test(`${makeRunner.name}: purging one payment exchange keeps refunds from the other`, async () => { + const runner = await makeRunner(); + const keptExchange = "https://kept-exchange.example/"; + const purgedExchange = "https://purged-exchange.example/"; + const purchase = makeDownloadedPurchase("multi-exchange"); + purchase.exchanges = [keptExchange, purgedExchange]; + const wex = { + ws: { notify() {}, exchangeCache: { clear() {} } }, + runWalletDbTx: <T>(f: (tx: WalletDbTransaction) => Promise<T>) => + runner.runReadWriteTx(f), + } as unknown as WalletExecutionContext; + const keptRefund = makeTestRefundGroup(purchase.proposalId, "kept-refund"); + const keptIssuer = { + url: keptExchange, + masterPub: encodeCrock(new Uint8Array(32).fill(1)), + denomPubHash: encodeCrock(new Uint8Array(64).fill(2)), + }; + keptRefund.purchaseSnapshot = { issuers: [keptIssuer] }; + const purgedRefund = makeTestRefundGroup( + purchase.proposalId, + "purged-refund", + ); + try { + await runner.runReadWriteTx(async (tx) => { + await upsertTestContractTerms(tx, purchase); + await tx.upsertPurchase(purchase); + for (const baseUrl of [keptExchange, purgedExchange]) { + await tx.upsertExchange({ + baseUrl, + entryStatus: ExchangeEntryDbRecordStatus.Used, + updateStatus: ExchangeEntryDbUpdateStatus.Initial, + detailsPointer: undefined, + tosCurrentEtag: undefined, + tosAcceptedEtag: undefined, + tosAcceptedTimestamp: undefined, + lastUpdate: undefined, + nextUpdateStamp: purchase.timestamp, + lastKeysEtag: undefined, + nextRefreshCheckStamp: purchase.timestamp, + }); + } + await tx.upsertRefundGroup(keptRefund); + await tx.upsertRefundGroup(purgedRefund); + // Only the coin ties this refund to the exchange being purged. + const coinPub = encodeCrock(new Uint8Array(32).fill(3)); + await tx.upsertCoin({ + coinPub, + exchangeBaseUrl: purgedExchange, + exchangeMasterPub: encodeCrock(new Uint8Array(32).fill(4)), + denomPubHash: encodeCrock(new Uint8Array(64).fill(5)), + coinPriv: coinPub, + blindingKey: coinPub, + coinEvHash: coinPub, + denomSig: { cipher: DenomKeyType.Rsa, rsa_signature: coinPub }, + exchangeWithdrawValues: { cipher: "RSA" }, + status: CoinStatus.Dormant, + maxAge: 0, + ageCommitmentProof: undefined, + coinSource: { + type: CoinSourceType.Withdraw, + withdrawalGroupId: "withdrawal", + coinIndex: 0, + reservePub: coinPub, + }, + }); + await tx.upsertRefundItem({ + refundGroupId: purgedRefund.refundGroupId, + coinPub, + rtxid: 1, + status: RefundItemStatus.Done, + refundAmount: "TESTKUDOS:1", + executionTime: timestampProtocolToDb({ t_s: 1 }), + obtainedTime: purchase.timestamp, + }); + }); + await deleteExchange(wex, { + exchangeBaseUrl: purgedExchange, + purge: true, + }); + await runner.runReadWriteTx(async (tx) => { + assert.equal(await tx.getPurchase(purchase.proposalId), undefined); + assert.equal( + await tx.getRefundGroup(purgedRefund.refundGroupId), + undefined, + ); + const kept = await tx.getRefundGroup(keptRefund.refundGroupId); + assert.deepEqual(kept?.purchaseSnapshot?.issuers, [keptIssuer]); + }); + await deleteExchange(wex, { exchangeBaseUrl: keptExchange, purge: true }); + assert.equal( + await runner.runReadWriteTx((tx) => + tx.getRefundGroup(keptRefund.refundGroupId), + ), + undefined, + ); + } finally { + await runner.close(); + } + }); + + test(`${makeRunner.name}: migration repairs stopped version 2 amounts and discards uncertain issuers`, async () => { + const runner = await makeRunner(); + const group = makeTestRefundGroup( + "deleted", + "previously-stopped", + RefundGroupStatus.Aborted, + ); + group.amountRaw = "TESTKUDOS:5"; + group.purchaseSnapshot = { + orderId: "order", + exchangeIdentities: [{ url: "https://unverified.example/" }], + }; + const wex = { + runWalletDbTx: <T>(f: (tx: WalletDbTransaction) => Promise<T>) => + runner.runReadWriteTx(f), + } as WalletExecutionContext; + try { + await runner.runReadWriteTx(async (tx) => { + await tx.upsertConfig({ + key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, + value: 2, + }); + await tx.upsertRefundGroup(group); + for (const [i, status] of [ + RefundItemStatus.Done, + RefundItemStatus.Aborted, + ].entries()) { + await tx.upsertRefundItem({ + refundGroupId: group.refundGroupId, + status, + rtxid: i, + coinPub: encodeCrock(new Uint8Array(32).fill(i + 1)), + refundAmount: i === 0 ? "TESTKUDOS:3" : "TESTKUDOS:2", + executionTime: timestampProtocolToDb({ t_s: 1 }), + obtainedTime: group.timestampCreated, + }); + } + }); + await migrateRefundPurchaseSnapshots(wex); + const repaired = await runner.runReadWriteTx((tx) => + tx.getRefundGroup(group.refundGroupId), + ); + assert.deepEqual(repaired?.purchaseSnapshot?.issuers, []); + assert.equal(repaired?.purchaseSnapshot?.orderId, "order"); + const details = await getTransactionById(wex, { + transactionId: "txn:refund:previously-stopped", + }); + assert.ok(details.type === TransactionType.Refund); + assert.equal(details.amountRaw, "TESTKUDOS:3"); + assert.equal(details.amountUncollected, "TESTKUDOS:2"); + } finally { + await runner.close(); + } + }); + test(`${makeRunner.name}: deleting a payment stops only unconfirmed refund items`, async () => { const runner = await makeRunner(); const purchase = makeDownloadedPurchase( @@ -823,7 +984,8 @@ for (const makeRunner of runnerFactories) { "partial", RefundGroupStatus.Pending, ); - group.amountRaw = "TESTKUDOS:3"; + // Historical groups included both the pending and failed amounts here. + group.amountRaw = "TESTKUDOS:7"; group.amountEffective = "TESTKUDOS:2.9"; group.transactionAmounts = { refreshOutputs: { settled: "TESTKUDOS:2.9" } }; try { @@ -1117,7 +1279,7 @@ for (const makeRunner of runnerFactories) { stored.delayed?.purchaseSnapshot?.paymentInfo?.summary, "Refund test", ); - assert.strictEqual(stored.version?.value, 2); + assert.strictEqual(stored.version?.value, 3); } finally { await runner.close(); } @@ -1140,7 +1302,7 @@ for (const makeRunner of runnerFactories) { ); await tx.upsertConfig({ key: ConfigRecordKey.RefundPurchaseSnapshotsVersion, - value: 3, + value: 4, }); }); @@ -1153,7 +1315,7 @@ for (const makeRunner of runnerFactories) { ), })); assert.strictEqual(stored.group?.purchaseSnapshot, undefined); - assert.strictEqual(stored.version?.value, 3); + assert.strictEqual(stored.version?.value, 4); } finally { await runner.close(); } diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -6567,7 +6567,7 @@ export async function storeRefunds( tx, newGroup, myPurchase, - download.contractTerms, + { terms: download.contractTerms }, ); await tx.upsertRefundGroup(newGroup); await refundCtx.updateTransactionMeta(tx); @@ -6592,7 +6592,7 @@ export async function storeRefunds( refundGroup.refundGroupId, ); const needsHistory = - !refundGroup.purchaseSnapshot?.exchangeIdentities || + !refundGroup.purchaseSnapshot?.issuers || !refundGroup.purchaseSnapshot.paymentInfo || !refundGroup.refundReason; if (needsHistory) { @@ -6600,7 +6600,7 @@ export async function storeRefunds( tx, refundGroup, myPurchase, - download.contractTerms, + { terms: download.contractTerms }, ); refundGroup.refundReason ??= refundReasonForPurchase( myPurchase.purchaseStatus, diff --git a/packages/taler-wallet-core/src/refund-history.ts b/packages/taler-wallet-core/src/refund-history.ts @@ -7,6 +7,7 @@ import { Amounts, codecForMerchantContractTerms, + DecodingError, Logger, MerchantContractTerms, ScopeInfo, @@ -22,7 +23,8 @@ import { RefundItemStatus, RefundReason, WalletPurchase, - WalletRefundExchangeIdentity, + WalletRefundIssuer, + WalletRefundItem, WalletRefundGroup, WalletRefundPurchaseSnapshot, } from "./db/records.js"; @@ -37,18 +39,22 @@ import { import type { WalletExecutionContext } from "./wallet.js"; const logger = new Logger("refund-history.ts"); -const REFUND_PURCHASE_SNAPSHOTS_VERSION = 2; +const REFUND_PURCHASE_SNAPSHOTS_VERSION = 3; async function readContractTerms( tx: WalletDbTransaction, purchase?: WalletPurchase, ) { if (!purchase?.download) return; - const record = await tx.getContractTerms(purchase.download.contractTermsHash); - if (!record) return; try { + const record = await tx.getContractTerms( + purchase.download.contractTermsHash, + ); + if (!record) return; return codecForMerchantContractTerms().decode(record.contractTermsRaw); } catch (e) { + // SQLite decodes the stored JSON before the contract codec runs. + if (!(e instanceof SyntaxError || e instanceof DecodingError)) throw e; logger.warn( `unreadable contract for refund of ${purchase.proposalId}: ${e}`, ); @@ -61,9 +67,10 @@ export async function recoverRefundSnapshot( tx: WalletDbTransaction, refund: WalletRefundGroup, purchase: WalletPurchase | undefined, - terms?: MerchantContractTerms, + options: { terms?: MerchantContractTerms; items?: WalletRefundItem[] } = {}, ): Promise<WalletRefundPurchaseSnapshot | undefined> { const saved = refund.purchaseSnapshot; + let terms = options.terms; let paymentInfo = saved?.paymentInfo; if (!paymentInfo) { terms ??= await readContractTerms(tx, purchase); @@ -75,57 +82,43 @@ export async function recoverRefundSnapshot( }; } - 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); + const items = + options.items ?? (await tx.getRefundItemsByGroup(refund.refundGroupId)); + const coinPubs = [...new Set(items.map((item) => item.coinPub))]; + const coins = await tx.getCoinsByPubs(coinPubs); + // Older snapshots describe the payment as a whole. Only refund-item coins + // identify particular issuing keys and denominations for this group. + const byDenomination = new Map<string, WalletRefundIssuer>(); + for (const issuer of [ + ...(saved?.issuers ?? []).filter( + (issuer) => issuer.denomPubHash !== undefined, + ), + ...coins.map((coin) => ({ + url: coin.exchangeBaseUrl, + masterPub: coin.exchangeMasterPub, + denomPubHash: coin.denomPubHash, + })), + ]) { + byDenomination.set( + JSON.stringify([issuer.url, issuer.masterPub, issuer.denomPubHash]), + issuer, + ); } - 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 }); + const issuers = [...byDenomination.values()]; + // A payment known to use exactly one exchange also establishes the URL. + // Its selection cannot establish which key or denomination was refunded. + if (!issuers.length) { + const soleIssuer = + saved?.issuers?.[0]?.url ?? + (purchase?.exchanges?.length === 1 ? purchase.exchanges[0] : undefined); + if (soleIssuer) issuers.push({ url: soleIssuer }); } + if (!purchase && !saved && !issuers.length) return undefined; return { merchantBaseUrl: saved?.merchantBaseUrl ?? purchase?.merchantBaseUrl, orderId: saved?.orderId ?? terms?.order_id ?? purchase?.orderId, paymentInfo, - exchangeIdentities, + issuers, }; } @@ -135,18 +128,16 @@ export async function resolveRefundSnapshot( refund: WalletRefundGroup, ) { const saved = refund.purchaseSnapshot; - if (saved?.exchangeIdentities && saved.paymentInfo) return saved; + if (saved?.issuers && saved.paymentInfo) return saved; const purchase = await tx.getPurchase(refund.proposalId); - if (!purchase && saved?.exchangeIdentities) return saved; + if (!purchase && saved?.issuers) return saved; return recoverRefundSnapshot(tx, refund, purchase); } export function refundExchangeUrls( snapshot?: WalletRefundPurchaseSnapshot, ): string[] { - return [ - ...new Set(snapshot?.exchangeIdentities?.map((issuer) => issuer.url)), - ]; + return [...new Set(snapshot?.issuers?.map((issuer) => issuer.url))]; } export async function refundScopes( @@ -155,8 +146,14 @@ export async function refundScopes( snapshot?: WalletRefundPurchaseSnapshot, ): Promise<ScopeInfo[]> { const scopes = new Map<string, ScopeInfo>(); - for (const url of refundExchangeUrls(snapshot)) { - const current = await getExchangeScopeInfo(tx, url, currency); + for (const { url, masterPub, denomPubHash } of snapshot?.issuers ?? []) { + const current = await getExchangeScopeInfo( + tx, + url, + currency, + denomPubHash, + masterPub, + ); const scope: ScopeInfo = current.currency === currency ? current @@ -175,23 +172,24 @@ export async function writeRefundMeta( ) { const currency = Amounts.currencyOf(refund.amountEffective); const exchanges = refundExchangeUrls(snapshot); - const legacyScopes: ScopeInfoExchangeLegacyKeys[] = []; + const legacyScopes = new Map<string, ScopeInfoExchangeLegacyKeys>(); for (const url of exchanges) { const current = (await tx.getExchange(url))?.detailsPointer; if (!current) continue; - for (const issuer of snapshot?.exchangeIdentities ?? []) { + for (const issuer of snapshot?.issuers ?? []) { if ( issuer.url === url && issuer.masterPub && (issuer.masterPub !== current.masterPublicKey || currency !== current.currency) ) { - legacyScopes.push({ + const scope: ScopeInfoExchangeLegacyKeys = { type: ScopeType.ExchangeLegacyKeys, currency, url, masterPub: issuer.masterPub, - }); + }; + legacyScopes.set(stringifyScopeInfo(scope), scope); } } } @@ -204,7 +202,7 @@ export async function writeRefundMeta( timestamp: refund.timestampCreated, currency, exchanges, - legacyScopes, + legacyScopes: [...legacyScopes.values()], }); } @@ -215,7 +213,10 @@ export async function retainRefundHistory( purchase: WalletPurchase | undefined, detach: boolean, ): Promise<void> { - refund.purchaseSnapshot = await recoverRefundSnapshot(tx, refund, purchase); + const items = await tx.getRefundItemsByGroup(refund.refundGroupId); + refund.purchaseSnapshot = await recoverRefundSnapshot(tx, refund, purchase, { + items, + }); if (!refund.refundReason) { if (purchase) refund.refundReason = refundReasonForPurchase(purchase.purchaseStatus); @@ -227,13 +228,25 @@ export async function retainRefundHistory( } const stopped = detach && refund.status === RefundGroupStatus.Pending; if (stopped) { - for (const item of await tx.getRefundItemsByGroup(refund.refundGroupId)) { + for (const item of items) { if (item.status !== RefundItemStatus.Pending) continue; item.status = RefundItemStatus.Aborted; await tx.upsertRefundItem(item); } refund.status = RefundGroupStatus.Aborted; } + if (refund.status === RefundGroupStatus.Aborted && items.length) { + // Older wallets included pending and failed items in amountRaw. + const confirmed = items.filter( + (item) => item.status === RefundItemStatus.Done, + ); + refund.amountRaw = Amounts.stringify( + Amounts.sumOrZero( + Amounts.currencyOf(refund.amountRaw), + confirmed.map((item) => item.refundAmount), + ).amount, + ); + } await tx.upsertRefundGroup(refund); await writeRefundMeta(tx, refund, refund.purchaseSnapshot); if (stopped) { @@ -272,7 +285,7 @@ export async function migrateRefundPurchaseSnapshotsInTx( for (const refund of await tx.listAllRefundGroups()) { const purchase = await tx.getPurchase(refund.proposalId); if ( - refund.purchaseSnapshot?.exchangeIdentities && + refund.purchaseSnapshot?.issuers && refund.purchaseSnapshot.paymentInfo && refund.refundReason && (refund.status !== RefundGroupStatus.Pending || purchase) diff --git a/packages/taler-wallet-core/src/requests.test.ts b/packages/taler-wallet-core/src/requests.test.ts @@ -456,7 +456,7 @@ test("importDb request converts a foreign backend dump", async () => { tx.getConfig(ConfigRecordKey.RefundPurchaseSnapshotsVersion), ) )?.value, - 2, + 3, ); assert.ok( progress.some(