commit aa4145c75d51a40f8da078cd51e5b5ad01e49371
parent 97c435dd720a1d45118e566368711c14e5da14f3
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 18:25:28 +0100
wallet-core: add each refund credit directly to its group
The wallet kept a separate list of refund credits and checked for
leftovers after scheduling refreshes. Look up each receipt's group on
the purchase and add the credit there, so the wallet checks ownership as
it processes the receipt.
Diffstat:
3 files changed, 182 insertions(+), 191 deletions(-)
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -128,7 +128,7 @@ import { HeadersImpl } from "@gnu-taler/taler-util/http";
import { dispatchRequestInternal } from "./requests.js";
import { deleteTransaction, getTransactionById } from "./transactions.js";
import { WalletApiOperation } from "./wallet-api-types.js";
-import { TaskIdentifiers } from "./common.js";
+import { TaskIdentifiers, TaskRunResultType } from "./common.js";
interface ScheduledTimer {
due: number;
@@ -1175,7 +1175,7 @@ for (const makeRunner of runnerFactories) {
await tx.upsertPurchase(p);
return p;
});
- await storeRefunds(wex, current, refunds, RefundReason.NormalRefund);
+ return storeRefunds(wex, current, refunds, RefundReason.NormalRefund);
};
const removeLedger = () =>
runner.runReadWriteTx(async (tx) => {
@@ -1248,14 +1248,17 @@ for (const makeRunner of runnerFactories) {
}
});
const first = success(full.coinPub, 1, "TESTKUDOS:10");
- const part = success(split.coinPub, 1, "TESTKUDOS:4");
+ const firstParts = [
+ success(split.coinPub, 0, "TESTKUDOS:3"),
+ success(split.coinPub, 1, "TESTKUDOS:1"),
+ ];
const netOnly = success(unknown.coinPub, 1, "TESTKUDOS:10");
const middle = success(split.coinPub, 2, "TESTKUDOS:2");
const last = success(split.coinPub, 3, "TESTKUDOS:4");
- await collect([first, part, netOnly, first]);
+ await collect([first, ...firstParts, netOnly, first]);
const expected = [
[full.coinPub, "TESTKUDOS:10.1"],
- [split.coinPub, "TESTKUDOS:3.9"],
+ [split.coinPub, "TESTKUDOS:3.8"],
[unknown.coinPub, "TESTKUDOS:9.9"],
];
assert.deepEqual(await recoveryAmounts(), expected.sort());
@@ -1267,13 +1270,17 @@ for (const makeRunner of runnerFactories) {
first,
{ ...middle, type: "failure", exchange_status: 503 },
]);
- await collect([{ ...last, type: "failure", exchange_status: 503 }]);
+ const pending = await collect([
+ { ...last, type: "failure", exchange_status: 503 },
+ ]);
+ assert.equal(pending.type, TaskRunResultType.Backoff);
assert.deepEqual(await recoveryAmounts(), expected);
const seeded = await runner.runReadWriteTx((tx) =>
tx.getPurchase(purchase.proposalId),
);
assert.deepEqual(seeded?.payInfo?.accountedRefunds?.[split.coinPub], {
- 1: "TESTKUDOS:4",
+ 0: "TESTKUDOS:3",
+ 1: "TESTKUDOS:1",
});
await removeLedger(); // Deletion itself may be the first action after an upgrade.
@@ -1284,7 +1291,15 @@ for (const makeRunner of runnerFactories) {
await runner.close();
runner = await makeRunner(filename);
// Two groups settle together, with the later refund first on the wire.
- await collect([first, part, netOnly, last, middle, last]);
+ const settled = await collect([
+ first,
+ ...firstParts,
+ netOnly,
+ last,
+ middle,
+ last,
+ ]);
+ assert.equal(settled.type, TaskRunResultType.Progress);
expected.push(
[split.coinPub, "TESTKUDOS:1.9"],
[split.coinPub, "TESTKUDOS:4.1"],
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -6277,19 +6277,13 @@ export async function startQueryRefund(
await wex.runWalletDbTx((tx) => startQueryRefundInTx(ctx, tx));
}
-/**
- * Compute the refund item status based on the merchant's response.
- */
-function getItemStatus(rf: MerchantCoinRefundStatus): RefundItemStatus {
- if (rf.type === "success") {
- return RefundItemStatus.Done;
- } else {
- if (isTransientRefundStatus(rf.exchange_status)) {
- return RefundItemStatus.Pending;
- } else {
- return RefundItemStatus.Failed;
- }
- }
+function getRefundItemStatus(
+ refund: MerchantCoinRefundStatus,
+): RefundItemStatus {
+ if (refund.type === "success") return RefundItemStatus.Done;
+ return isTransientRefundStatus(refund.exchange_status)
+ ? RefundItemStatus.Pending
+ : RefundItemStatus.Failed;
}
/** Retain the exchange reply even when it has no structured Taler error. */
@@ -6404,7 +6398,7 @@ export async function storeRefunds(
const ctx = new PayMerchantTransactionContext(wex, purchase.proposalId);
const newRefundGroupId = encodeCrock(getRandomBytes(32));
- const now = TalerPreciseTimestamp.now();
+ const obtainedTime = timestampPreciseToDb(TalerPreciseTimestamp.now());
const download = await expectProposalDownload(wex, purchase);
const { available, amountRaw } = ContractTermsUtil.extractAmounts(
@@ -6448,11 +6442,11 @@ export async function storeRefunds(
}
}
- const result = await wex.runWalletDbTx(async (tx) => {
+ return wex.runWalletDbTx(async (tx) => {
const [myPurchase, h] = await ctx.getRecordHandle(tx);
if (!myPurchase) {
logger.warn("purchase group not found anymore");
- return;
+ return TaskRunResult.finished();
}
let isAborting: boolean;
switch (myPurchase.purchaseStatus) {
@@ -6464,70 +6458,58 @@ export async function storeRefunds(
break;
default:
logger.warn("wrong state, not accepting refund");
- return;
+ return TaskRunResult.finished();
}
- let newGroup: WalletRefundGroup | undefined = undefined;
+ let newGroup: WalletRefundGroup | undefined;
+ const zero = Amounts.stringify(Amounts.zeroOfCurrency(currency));
const accounted = await loadAccountedRefunds(tx, myPurchase);
const newlySuccessful: WalletRefundItem[] = [];
- for (const rf of refunds) {
- if (accounted[rf.coin_pub]?.[rf.rtransaction_id] !== undefined) continue;
- let item = await tx.getRefundItemByCoinAndRtxid(
- rf.coin_pub,
- rf.rtransaction_id,
- );
+ for (const refund of refunds) {
+ const { coin_pub: coinPub, rtransaction_id: rtxid } = refund;
+ if (accounted[coinPub]?.[rtxid] !== undefined) continue;
+ let item = await tx.getRefundItemByCoinAndRtxid(coinPub, rtxid);
+ if (item?.status === RefundItemStatus.Done) continue;
+
+ const status = getRefundItemStatus(refund);
if (item) {
- if (item.status === RefundItemStatus.Done) {
- continue;
+ item.status = status;
+ if (status === RefundItemStatus.Done) {
+ item.refundAmount = refund.refund_amount;
+ item.executionTime = timestampProtocolToDb(refund.execution_time);
+ item.obtainedTime = obtainedTime;
}
- if (rf.type === "success") {
- item.status = RefundItemStatus.Done;
- delete item.failReason;
- item.refundAmount = rf.refund_amount;
- item.executionTime = timestampProtocolToDb(rf.execution_time);
- item.obtainedTime = timestampPreciseToDb(now);
+ if (status === RefundItemStatus.Failed) {
+ item.failReason = getPermanentRefundReason(refund);
} else {
- if (isTransientRefundStatus(rf.exchange_status)) {
- item.status = RefundItemStatus.Pending;
- delete item.failReason;
- } else {
- item.status = RefundItemStatus.Failed;
- item.failReason = getPermanentRefundReason(rf);
- }
+ delete item.failReason;
}
} else {
- // Put refund item into a new group!
- if (!newGroup) {
- newGroup = {
- proposalId: purchase.proposalId,
- refundGroupId: newRefundGroupId,
- status: RefundGroupStatus.Pending,
- timestampCreated: timestampPreciseToDb(now),
- refundReason: reason,
- amountEffective: Amounts.stringify(
- Amounts.zeroOfCurrency(currency),
- ),
- amountRaw: Amounts.stringify(Amounts.zeroOfCurrency(currency)),
- };
- }
- const status: RefundItemStatus = getItemStatus(rf);
+ newGroup ??= {
+ proposalId: purchase.proposalId,
+ refundGroupId: newRefundGroupId,
+ status: RefundGroupStatus.Pending,
+ timestampCreated: obtainedTime,
+ refundReason: reason,
+ amountEffective: zero,
+ amountRaw: zero,
+ };
item = {
- coinPub: rf.coin_pub,
- executionTime: timestampProtocolToDb(rf.execution_time),
- obtainedTime: timestampPreciseToDb(now),
- refundAmount: rf.refund_amount,
- refundGroupId: newGroup.refundGroupId,
- rtxid: rf.rtransaction_id,
+ coinPub,
+ rtxid,
status,
- failReason: getPermanentRefundReason(rf),
+ obtainedTime,
+ refundGroupId: newGroup.refundGroupId,
+ executionTime: timestampProtocolToDb(refund.execution_time),
+ refundAmount: refund.refund_amount,
+ failReason: getPermanentRefundReason(refund),
};
}
await tx.upsertRefundItem(item);
if (item.status === RefundItemStatus.Done) newlySuccessful.push(item);
}
- // Create the group before the common item-level accounting below.
if (newGroup) {
const refundCtx = new RefundTransactionContext(
wex,
@@ -6551,11 +6533,7 @@ export async function storeRefunds(
});
}
- const refundGroups = await tx.getRefundGroupsByProposal(
- purchase.proposalId,
- );
-
- const recoveryByGroup = await accountMerchantRefunds(
+ const refundGroups = await accountMerchantRefunds(
wex,
tx,
myPurchase,
@@ -6563,8 +6541,8 @@ export async function storeRefunds(
accounted,
newlySuccessful,
);
- let numPendingItemsTotal = 0;
- for (const refundGroup of refundGroups) {
+ let hasPendingRefunds = false;
+ for (const { refundGroup, creditByCoin } of refundGroups.values()) {
const refundCtx = new RefundTransactionContext(
wex,
refundGroup.refundGroupId,
@@ -6584,12 +6562,11 @@ export async function storeRefunds(
myPurchase.purchaseStatus,
);
}
- const newlyRefundedCoins = recoveryByGroup.get(refundGroup.refundGroupId);
switch (refundGroup.status) {
case RefundGroupStatus.Aborted:
case RefundGroupStatus.Expired:
case RefundGroupStatus.Done:
- if (newlyRefundedCoins) break;
+ if (creditByCoin.size > 0) break;
if (needsHistory) {
await tx.upsertRefundGroup(refundGroup);
await refundCtx.updateTransactionMeta(tx);
@@ -6611,7 +6588,14 @@ export async function storeRefunds(
successfulItems.map((x) => x.refundAmount),
).amount,
);
- if (newlyRefundedCoins) {
+ if (creditByCoin.size > 0) {
+ const newlyRefundedCoins = Array.from(
+ creditByCoin,
+ ([coinPub, amount]) => ({
+ coinPub,
+ amount: Amounts.stringify(amount),
+ }),
+ );
const outInfo = await calculateRefreshOutput(
wex,
tx,
@@ -6635,53 +6619,33 @@ export async function storeRefunds(
ctx.transactionId,
);
refundGroup.refreshGroupId = refreshResult.refreshGroupId;
- recoveryByGroup.delete(refundGroup.refundGroupId);
}
- let numPending = 0;
- let numFailed = 0;
- for (const item of items) {
- if (item.status === RefundItemStatus.Pending) {
- numPending++;
- }
- if (item.status === RefundItemStatus.Failed) {
- numFailed++;
- }
- }
- refundGroup.failReason = getRefundGroupFailure(items);
- numPendingItemsTotal += numPending;
- const oldTxState: TransactionState =
- computeRefundTransactionState(refundGroup);
+ const oldTxState = computeRefundTransactionState(refundGroup);
const oldStId = refundGroup.status;
- if (numPending === 0) {
- // We're done for this refund group!
- if (numFailed === 0) {
- refundGroup.status = RefundGroupStatus.Done;
- } else {
- refundGroup.status = RefundGroupStatus.Failed;
- }
- await tx.upsertRefundGroup(refundGroup);
- await refundCtx.updateTransactionMeta(tx);
- const newTxState: TransactionState =
- computeRefundTransactionState(refundGroup);
- const newStId = refundGroup.status;
+ refundGroup.failReason = getRefundGroupFailure(items);
+ if (items.some((item) => item.status === RefundItemStatus.Pending)) {
+ refundGroup.status = RefundGroupStatus.Pending;
+ hasPendingRefunds = true;
+ } else if (
+ items.some((item) => item.status === RefundItemStatus.Failed)
+ ) {
+ refundGroup.status = RefundGroupStatus.Failed;
+ } else {
+ refundGroup.status = RefundGroupStatus.Done;
+ }
+ await tx.upsertRefundGroup(refundGroup);
+ await refundCtx.updateTransactionMeta(tx);
+ if (refundGroup.status !== RefundGroupStatus.Pending) {
applyNotifyTransition(tx.notify, refundCtx.transactionId, {
causeHint: "refund-group-final",
oldTxState,
- newTxState,
+ newTxState: computeRefundTransactionState(refundGroup),
balanceEffect: BalanceEffect.Any,
- newStId,
+ newStId: refundGroup.status,
oldStId,
});
- } else {
- refundGroup.status = RefundGroupStatus.Pending;
- await tx.upsertRefundGroup(refundGroup);
- await refundCtx.updateTransactionMeta(tx);
}
}
- checkDbInvariant(
- recoveryByGroup.size === 0,
- "refund does not belong to this payment",
- );
const shouldCheckAutoRefund =
myPurchase.autoRefundDeadline &&
!AbsoluteTime.isExpired(
@@ -6690,30 +6654,20 @@ export async function storeRefunds(
),
);
- if (numPendingItemsTotal === 0) {
- if (!isAborting && shouldCheckAutoRefund) {
- myPurchase.purchaseStatus = PurchaseStatus.FinalizingQueryingAutoRefund;
- } else if (!isAborting) {
- myPurchase.purchaseStatus = PurchaseStatus.Done;
+ if (!hasPendingRefunds) {
+ if (!isAborting) {
+ myPurchase.purchaseStatus = shouldCheckAutoRefund
+ ? PurchaseStatus.FinalizingQueryingAutoRefund
+ : PurchaseStatus.Done;
}
myPurchase.refundAmountAwaiting = undefined;
}
await h.update(myPurchase, "refunds-stored");
- return {
- numPendingItemsTotal,
- };
+ return hasPendingRefunds
+ ? TaskRunResult.backoff()
+ : TaskRunResult.progress();
});
-
- if (!result) {
- return TaskRunResult.finished();
- }
-
- if (result.numPendingItemsTotal > 0) {
- return TaskRunResult.backoff();
- } else {
- return TaskRunResult.progress();
- }
}
export function computeRefundTransactionState(
diff --git a/packages/taler-wallet-core/src/refund-accounting.ts b/packages/taler-wallet-core/src/refund-accounting.ts
@@ -20,7 +20,6 @@ import {
Amounts,
AmountString,
checkDbInvariant,
- CoinRefreshRequest,
TalerError,
TalerErrorCode,
TransactionIdStr,
@@ -29,6 +28,7 @@ import {
AccountedCoinRefunds,
RefundItemStatus,
WalletPurchase,
+ WalletRefundGroup,
WalletRefundItem,
} from "./db/records.js";
import { WalletDbTransaction } from "./db/transaction.js";
@@ -102,84 +102,106 @@ export async function loadAccountedRefunds(
return accounted;
}
-/** Allocate all newly confirmed items together, returning refresh inputs by refund group. */
+/** Use the payment's coin selection, falling back to a unique spend for the same payment. */
+async function getRefundContributions(
+ tx: WalletDbTransaction,
+ purchase: WalletPurchase,
+ paymentId: TransactionIdStr,
+ coinPubs: string[],
+): Promise<Map<string, AmountString>> {
+ const selection = purchase.payInfo?.payCoinSelection;
+ const contributions = new Map<string, AmountString>(
+ selection?.coinPubs.map((pub, i) => [pub, selection.coinContributions[i]]),
+ );
+ const missing = coinPubs.filter((pub) => !contributions.get(pub));
+ if (!missing.length) return contributions;
+ for (const { coinPub, history } of await tx.getCoinHistoriesByPubs(missing)) {
+ const spends = history
+ .filter((entry) => entry.transactionId === paymentId)
+ .filter((entry) => entry.type === "spend");
+ if (spends.length === 1) contributions.set(coinPub, spends[0].amount);
+ }
+ return contributions;
+}
+
+interface RefundGroupRecovery {
+ refundGroup: WalletRefundGroup;
+ creditByCoin: Map<string, AmountJson>;
+}
+
+/** Attribute each new receipt to its original refund group and record it on the purchase. */
export async function accountMerchantRefunds(
wex: WalletExecutionContext,
tx: WalletDbTransaction,
purchase: WalletPurchase,
paymentId: TransactionIdStr,
accounted: AccountedCoinRefunds,
- items: WalletRefundItem[],
-): Promise<Map<string, CoinRefreshRequest[]>> {
- const requests = new Map<string, CoinRefreshRequest[]>();
- if (!items.length) return requests;
- const byCoin = new Map<string, WalletRefundItem[]>();
- for (const item of items) {
- const batch = byCoin.get(item.coinPub);
- if (batch) batch.push(item);
- else byCoin.set(item.coinPub, [item]);
+ confirmed: WalletRefundItem[],
+): Promise<Map<string, RefundGroupRecovery>> {
+ const groups = new Map<string, RefundGroupRecovery>();
+ for (const refundGroup of await tx.getRefundGroupsByProposal(
+ purchase.proposalId,
+ )) {
+ groups.set(refundGroup.refundGroupId, {
+ refundGroup,
+ creditByCoin: new Map(),
+ });
}
- const contributions = new Map<string, AmountString>();
- const selection = purchase.payInfo?.payCoinSelection;
- selection?.coinPubs.forEach((pub, i) => {
- contributions.set(pub, selection.coinContributions[i]);
- });
- // A repaired selection or a legacy purchase can omit the spent coin.
- const pubs = Array.from(byCoin.keys());
- const missing = pubs.filter((pub) => !contributions.get(pub));
- if (missing.length) {
- for (const history of await tx.getCoinHistoriesByPubs(missing)) {
- const spends = history.history.filter(
- (e) => e.type === "spend" && e.transactionId === paymentId,
- );
- if (spends.length === 1 && spends[0].type === "spend") {
- contributions.set(history.coinPub, spends[0].amount);
- }
- }
+ if (!confirmed.length) return groups;
+
+ const refundsByCoin: Record<string, WalletRefundItem[]> = Object.create(null);
+ for (const item of confirmed) {
+ (refundsByCoin[item.coinPub] ??= []).push(item);
}
- const coins = await tx.getCoinsByPubs(pubs);
- checkDbInvariant(coins.length === pubs.length, "refunded coin not found");
+
+ const coinPubs = Object.keys(refundsByCoin);
+ const contributions = await getRefundContributions(
+ tx,
+ purchase,
+ paymentId,
+ coinPubs,
+ );
+ const coins = await tx.getCoinsByPubs(coinPubs);
+ checkDbInvariant(coins.length === coinPubs.length, "refunded coin not found");
const denominations = await getDenomInfos(wex, tx, coins);
for (const coin of coins) {
const denom = denominations.get(denomRefKey(coin));
checkDbInvariant(!!denom, "refunded denomination not found");
- const receipts = (accounted[coin.coinPub] ??= {});
- const previous = Amounts.sumOrZero(
+ const { coinPub } = coin;
+ const receipts = (accounted[coinPub] ??= {});
+ const priorGross = Amounts.sumOrZero(
Amounts.currencyOf(denom.value),
Object.values(receipts),
);
- checkDbInvariant(!previous.saturated, "stored gross refunds overflow");
- let totalGross = previous.amount;
- const creditByGroup = new Map<string, AmountJson>();
- // Multiple pending groups can settle in one response. Attribute the waiver
- // in execution order, breaking timestamp ties with the coin's refund ID.
- const batch = byCoin.get(coin.coinPub)!;
- batch.sort(
+ checkDbInvariant(!priorGross.saturated, "stored gross refunds overflow");
+ let confirmedGross = priorGross.amount;
+ // Apply receipts in execution order so a fee returned across several
+ // groups goes to the same group regardless of database or response order.
+ const refunds = refundsByCoin[coinPub].sort(
(a, b) => a.executionTime - b.executionTime || a.rtxid - b.rtxid,
);
- for (const item of batch) {
- const result = calculateCoinRefund({
- contribution: contributions.get(coin.coinPub),
- previousGross: totalGross,
+ for (const item of refunds) {
+ const group = groups.get(item.refundGroupId);
+ checkDbInvariant(!!group, "refund does not belong to this payment");
+ const { credit, totalGross } = calculateCoinRefund({
+ contribution: contributions.get(coinPub),
+ previousGross: confirmedGross,
grossRefund: item.refundAmount,
refundFee: denom.feeRefund,
depositFee: denom.feeDeposit,
});
- totalGross = result.totalGross;
- const sum = Amounts.add(
- creditByGroup.get(item.refundGroupId) ??
- Amounts.zeroOfAmount(totalGross),
- result.credit,
+ const groupTotal = Amounts.add(
+ group.creditByCoin.get(coinPub) ?? Amounts.zeroOfAmount(confirmedGross),
+ credit,
);
- checkDbInvariant(!sum.saturated, "refund recovery amount overflows");
- creditByGroup.set(item.refundGroupId, sum.amount);
+ checkDbInvariant(
+ !groupTotal.saturated,
+ "refund recovery amount overflows",
+ );
+ group.creditByCoin.set(coinPub, groupTotal.amount);
+ confirmedGross = totalGross;
receipts[item.rtxid] = item.refundAmount;
}
- for (const [groupId, credit] of creditByGroup) {
- const group = requests.get(groupId) ?? [];
- group.push({ coinPub: coin.coinPub, amount: Amounts.stringify(credit) });
- requests.set(groupId, group);
- }
}
- return requests;
+ return groups;
}