commit b8e65e4d9088c51e74b3e5f018d164f61d820508
parent 93d5c7c4e17c896f9ad1f3f728cec60799bf15fc
Author: Florian Dold <dold@taler.net>
Date: Tue, 24 Nov 2026 16:44:45 +0100
wallet-core: stop refund collection when deleting a payment
Once the payment is gone, the wallet can no longer collect a pending
refund. Stop the pending items in the same transaction that deletes the
payment, and keep the confirmed amount available when the refund URI is
scanned again.
Issue: https://bugs.taler.net/n/10663
Diffstat:
4 files changed, 192 insertions(+), 95 deletions(-)
diff --git a/packages/taler-util/src/types-taler-wallet-observations.ts b/packages/taler-util/src/types-taler-wallet-observations.ts
@@ -206,6 +206,7 @@ export interface ObservedPeerPullDebitTransaction extends ObservedTransactionCom
}
export interface ObservedRefundTransaction extends ObservedTransactionCommon {
+ amountUncollected?: AmountString;
type: TransactionType.Refund;
refundedTransactionId: string;
paymentInfo: RefundPaymentInfo | undefined;
@@ -487,6 +488,7 @@ export function observedTransaction(
refundedTransactionId: transaction.refundedTransactionId,
paymentInfo: transaction.paymentInfo,
isAbortRecovery: transaction.isAbortRecovery,
+ amountUncollected: transaction.amountUncollected,
};
case TransactionType.Refresh:
return {
diff --git a/packages/taler-util/src/types-taler-wallet-transactions.ts b/packages/taler-util/src/types-taler-wallet-transactions.ts
@@ -925,6 +925,8 @@ export interface RefundPaymentInfo {
}
export interface TransactionRefund extends TransactionCommon {
+ /** Face value of items still unconfirmed when collection stopped. */
+ amountUncollected?: AmountString;
/** Recovery already included in the unsuccessful payment's final cost. */
isAbortRecovery?: boolean;
type: TransactionType.Refund;
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -697,16 +697,10 @@ for (const makeRunner of runnerFactories) {
const runner = await makeRunner();
const proposalId = "refunded-purchase";
const refundGroupId = "refund-after-purchase-delete";
- const contractTermsHash = "refunded-purchase-contract";
- const purchase = claimPurchase(proposalId, PurchaseStatus.Done);
- const key = encodeCrock(new Uint8Array(32).fill(7));
- purchase.noncePriv = purchase.noncePub = purchase.secretSeed = key;
- purchase.payInfo = { totalPayCost: "TESTKUDOS:1.1" };
- purchase.download = {
- contractTermsHash,
- contractTermsMerchantSig: "merchant-signature",
- currency: "TESTKUDOS",
- };
+ const purchase = makeDownloadedPurchase(
+ proposalId,
+ PurchaseStatus.AbortedRefunded,
+ );
const wex = {
ws: { notify: () => {} },
runWalletDbTx: <T>(f: (tx: WalletDbTransaction) => Promise<T>) =>
@@ -716,44 +710,19 @@ for (const makeRunner of runnerFactories) {
const refundCtx = new RefundTransactionContext(wex, refundGroupId);
try {
await runner.runReadWriteTx(async (tx) => {
- await tx.upsertContractTerms({
- h: contractTermsHash,
- contractTermsRaw: {
- version: MerchantContractVersion.V0,
- amount: "TESTKUDOS:1",
- max_fee: "TESTKUDOS:0",
- order_id: purchase.orderId,
- nonce: "nonce",
- merchant_base_url: purchase.merchantBaseUrl,
- h_wire: "wire-hash",
- wire_method: "iban",
- summary: "Refund test",
- fulfillment_url: "https://merchant.example/fulfillment",
- fulfillment_message: "Enjoy",
- pay_deadline: { t_s: 300 },
- refund_deadline: { t_s: 600 },
- wire_transfer_deadline: { t_s: 86400 },
- timestamp: { t_s: 1 },
- merchant: { name: "sandbox merchant" },
- merchant_pub: "merchant-pub",
- exchanges: [],
- },
+ // The version marker predates these recovered records. Deletion must
+ // capture the history even when startup has no outstanding migration.
+ await tx.upsertConfig({
+ key: ConfigRecordKey.RefundPurchaseSnapshotsVersion,
+ value: 2,
});
+ await upsertTestContractTerms(tx, purchase);
await tx.upsertPurchase(purchase);
- await tx.upsertRefundGroup({
- proposalId,
- refundGroupId,
- status: RefundGroupStatus.Done,
- timestampCreated: timestampPreciseToDb({ t_s: 2 }),
- refundReason: RefundReason.NormalRefund,
- amountRaw: "TESTKUDOS:1",
- amountEffective: "TESTKUDOS:1",
- });
+ await tx.upsertRefundGroup(
+ makeTestRefundGroup(proposalId, refundGroupId),
+ );
await paymentCtx.updateTransactionMeta(tx);
- await refundCtx.updateTransactionMeta(tx);
});
- await migrateRefundPurchaseSnapshots(wex);
-
await paymentCtx.userDeleteTransaction();
assert.strictEqual(
@@ -766,7 +735,7 @@ for (const makeRunner of runnerFactories) {
const storedRefund = await runner.runReadWriteTx((tx) =>
tx.getRefundGroup(refundGroupId),
);
- assert.strictEqual(storedRefund?.refundReason, RefundReason.NormalRefund);
+ assert.strictEqual(storedRefund?.refundReason, RefundReason.AbortRefund);
assert.strictEqual(
storedRefund?.purchaseSnapshot?.merchantBaseUrl,
purchase.merchantBaseUrl,
@@ -775,9 +744,9 @@ for (const makeRunner of runnerFactories) {
storedRefund?.purchaseSnapshot?.orderId,
purchase.orderId,
);
- const refundDetails = await runner.runReadWriteTx((tx) =>
- refundCtx.lookupFullTransaction(tx),
- );
+ const refundDetails = await getTransactionById(wex, {
+ transactionId: refundCtx.transactionId,
+ });
assert.strictEqual(refundDetails?.type, TransactionType.Refund);
if (refundDetails?.type !== TransactionType.Refund) {
assert.fail("refund must survive deletion of the purchase history");
@@ -788,6 +757,7 @@ for (const makeRunner of runnerFactories) {
);
assert.strictEqual(refundDetails.paymentInfo?.summary, "Refund test");
+ assert.strictEqual(refundDetails.isAbortRecovery, true);
await refundCtx.userDeleteTransaction();
assert.strictEqual(
await runner.runReadWriteTx((tx) => tx.getPurchase(proposalId)),
@@ -834,6 +804,89 @@ for (const makeRunner of runnerFactories) {
}
});
+ test(`${makeRunner.name}: deleting a payment stops only unconfirmed refund items`, async () => {
+ const runner = await makeRunner();
+ const purchase = makeDownloadedPurchase(
+ "partly-refunded",
+ PurchaseStatus.PendingAcceptRefund,
+ );
+ purchase.timestampFirstSuccessfulPay = timestampPreciseToDb({ t_s: 1 });
+ const wex = {
+ ws: { notify() {} },
+ taskScheduler: { resetTask() {}, stopShepherdTask() {} },
+ runWalletDbTx: <T>(f: (tx: WalletDbTransaction) => Promise<T>) =>
+ runner.runReadWriteTx(f),
+ } as unknown as WalletExecutionContext;
+ const payment = new PayMerchantTransactionContext(wex, purchase.proposalId);
+ const group = makeTestRefundGroup(
+ purchase.proposalId,
+ "partial",
+ RefundGroupStatus.Pending,
+ );
+ group.amountRaw = "TESTKUDOS:3";
+ group.amountEffective = "TESTKUDOS:2.9";
+ group.transactionAmounts = { refreshOutputs: { settled: "TESTKUDOS:2.9" } };
+ try {
+ await runner.runReadWriteTx(async (tx) => {
+ await upsertTestContractTerms(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ await tx.upsertRefundGroup(group);
+ for (const [i, status] of [
+ RefundItemStatus.Done,
+ RefundItemStatus.Pending,
+ RefundItemStatus.Failed,
+ ].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 payment.userAbortTransaction();
+ const readGroup = () =>
+ runner.runReadWriteTx((tx) => tx.getRefundGroup(group.refundGroupId));
+ assert.equal((await readGroup())?.status, RefundGroupStatus.Pending);
+ await assert.rejects(
+ runner.runReadWriteTx(async (tx) => {
+ await payment.deleteTransactionInTx(tx);
+ throw Error("rollback deletion");
+ }),
+ /rollback deletion/,
+ );
+ assert.equal((await readGroup())?.status, RefundGroupStatus.Pending);
+ await deleteTransaction(wex, payment.transactionId);
+ const retained = await startRefundQueryForUri(
+ wex,
+ "taler://refund/merchant.example/order/",
+ );
+ const details = await getTransactionById(wex, retained);
+ assert.ok(details.type === TransactionType.Refund);
+ assert.equal(details.txState.major, TransactionMajorState.Aborted);
+ assert.equal(details.amountRaw, "TESTKUDOS:3");
+ assert.equal(details.amountEffectiveFinal, "TESTKUDOS:2.9");
+ assert.equal(details.amountUncollected, "TESTKUDOS:2");
+ assert.equal(details.isAbortRecovery, false);
+ const items = await runner.runReadWriteTx((tx) =>
+ tx.getRefundItemsByGroup(group.refundGroupId),
+ );
+ assert.deepEqual(
+ items.sort((a, b) => a.rtxid - b.rtxid).map((item) => item.status),
+ [
+ RefundItemStatus.Done,
+ RefundItemStatus.Aborted,
+ RefundItemStatus.Failed,
+ ],
+ );
+ } finally {
+ await runner.close();
+ }
+ });
+
test(`${makeRunner.name}: repeated refund URI returns the retained refund without network access`, async () => {
const runner = await makeRunner();
const proposalId = "retained-refund-parent";
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -166,6 +166,7 @@ import {
recoverRefundSnapshot,
refundScopes,
resolveRefundSnapshot,
+ retainRefundHistory,
writeRefundMeta,
} from "./refund-history.js";
import { refundReasonForPurchase } from "./transaction-amounts.js";
@@ -531,7 +532,7 @@ export class PayMerchantTransactionContext implements TransactionContext {
async userDeleteTransaction(): Promise<void> {
await this.wex.runWalletDbTx(async (tx) => {
- return this.deleteTransactionInTx(tx);
+ return this.deleteTransactionInTx(tx, { userRequested: true });
});
cancelFailedClaimCleanup(this.wex, this.proposalId);
}
@@ -539,6 +540,7 @@ export class PayMerchantTransactionContext implements TransactionContext {
async deleteTransactionInTx(
tx: WalletDbTransaction,
opts: {
+ userRequested?: boolean;
keepRelated?: boolean;
causeHint?: string;
errorInfo?: ErrorInfoSummary;
@@ -548,6 +550,21 @@ export class PayMerchantTransactionContext implements TransactionContext {
if (!rec) {
return;
}
+ if (
+ opts.userRequested &&
+ !computePayMerchantTransactionActions(rec).includes(
+ TransactionAction.Delete,
+ )
+ ) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_REQUEST_TRANSACTION_STATE_UNSUPPORTED,
+ {
+ txState: computePayMerchantTransactionState(rec),
+ debugStateNum: rec.purchaseStatus,
+ },
+ "payment no longer allows deletion",
+ );
+ }
let relatedTransactions: WalletPurchase[] = [];
// Automatically delete transactions that are a repurchase of this transaction,
// as they're typically hidden.
@@ -580,6 +597,9 @@ export class PayMerchantTransactionContext implements TransactionContext {
this.transactionId,
rec.payInfo?.payTokenSelection?.tokenPubs ?? [],
);
+ for (const refund of await tx.getRefundGroupsByProposal(rec.proposalId)) {
+ await retainRefundHistory(tx, refund, rec, true);
+ }
await h.update(undefined, opts.causeHint ?? "delete", undefined, {
errorInfo: opts.errorInfo,
});
@@ -939,12 +959,31 @@ export class RefundTransactionContext implements TransactionContext {
const paymentInfo = purchaseSnapshot?.paymentInfo;
const currency = Amounts.currencyOf(refundRecord.amountEffective);
const scopes = await refundScopes(tx, currency, purchaseSnapshot);
+ const stoppedItems =
+ refundRecord.status === RefundGroupStatus.Aborted
+ ? (await tx.getRefundItemsByGroup(refundRecord.refundGroupId)).filter(
+ (item) => item.status === RefundItemStatus.Aborted,
+ )
+ : [];
return {
type: TransactionType.Refund,
scopes,
// Failed groups can still contain authenticated successful items.
amountEffective: refundRecord.amountEffective,
amountRaw: refundRecord.amountRaw,
+ ...(stoppedItems.length &&
+ stoppedItems.every(
+ (item) => Amounts.currencyOf(item.refundAmount) === currency,
+ )
+ ? {
+ amountUncollected: Amounts.stringify(
+ Amounts.sumOrZero(
+ currency,
+ stoppedItems.map((item) => item.refundAmount),
+ ).amount,
+ ),
+ }
+ : {}),
refundedTransactionId: constructTransactionIdentifier({
tag: TransactionType.Payment,
proposalId: refundRecord.proposalId,
@@ -6164,44 +6203,57 @@ export async function startRefundQueryForUri(
talerUri,
TalerUriAction.Refund,
);
- const purchase = await wex.runWalletDbTx(async (tx) =>
- tx.getPurchaseByUrlAndOrderId(parsedUri.merchantBaseUrl, parsedUri.orderId),
- );
- if (purchase) {
- await startQueryRefund(wex, purchase.proposalId);
- return {
- transactionId: constructTransactionIdentifier({
- tag: TransactionType.Payment,
- proposalId: purchase.proposalId,
- }),
- };
- }
-
- const matchingGroups = await wex.runWalletDbTx(async (tx) =>
- (await tx.listAllRefundGroups()).filter(
+ return wex.runWalletDbTx(async (tx) => {
+ const purchase = await tx.getPurchaseByUrlAndOrderId(
+ parsedUri.merchantBaseUrl,
+ parsedUri.orderId,
+ );
+ if (purchase) {
+ const ctx = new PayMerchantTransactionContext(wex, purchase.proposalId);
+ await startQueryRefundInTx(ctx, tx);
+ return { transactionId: ctx.transactionId };
+ }
+ const matchingGroups = (await tx.listAllRefundGroups()).filter(
(group) =>
group.purchaseSnapshot?.merchantBaseUrl === parsedUri.merchantBaseUrl &&
group.purchaseSnapshot.orderId === parsedUri.orderId,
- ),
- );
- const existingGroup = selectRelevantRefundGroup(matchingGroups);
- if (!existingGroup) {
- // Scanning a refund QR code for an order that was paid with a different
- // wallet is a normal user mistake, so the caller must be able to tell it
- // apart from an internal failure.
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_PURCHASE_NOT_FOUND,
- {
- merchantBaseUrl: parsedUri.merchantBaseUrl,
- orderId: parsedUri.orderId,
- },
- "no purchase found for the refund",
);
- }
+ const existingGroup = selectRelevantRefundGroup(matchingGroups);
+ if (!existingGroup) {
+ // Scanning a refund QR code for an order that was paid with a different
+ // wallet is a normal user mistake, so the caller must be able to tell it
+ // apart from an internal failure.
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_PURCHASE_NOT_FOUND,
+ {
+ merchantBaseUrl: parsedUri.merchantBaseUrl,
+ orderId: parsedUri.orderId,
+ },
+ "no purchase found for the refund",
+ );
+ }
+ return {
+ transactionId: makeRefundTransactionId(existingGroup.refundGroupId),
+ };
+ });
+}
- return {
- transactionId: makeRefundTransactionId(existingGroup.refundGroupId),
- };
+async function startQueryRefundInTx(
+ ctx: PayMerchantTransactionContext,
+ tx: WalletDbTransaction,
+): Promise<void> {
+ const [purchase, handle] = await ctx.getRecordHandle(tx);
+ if (!purchase) {
+ logger.warn(`purchase ${ctx.proposalId} does not exist anymore`);
+ return;
+ }
+ if (purchase.purchaseStatus === PurchaseStatus.Done) {
+ purchase.purchaseStatus = PurchaseStatus.PendingQueryingRefund;
+ await handle.update(purchase, "start-query-refund");
+ }
+ tx.scheduleOnCommit(() =>
+ ctx.wex.taskScheduler.startShepherdTask(ctx.taskId),
+ );
}
export async function startQueryRefund(
@@ -6209,19 +6261,7 @@ export async function startQueryRefund(
proposalId: string,
): Promise<void> {
const ctx = new PayMerchantTransactionContext(wex, proposalId);
- await wex.runWalletDbTx(async (tx) => {
- const [p, h] = await ctx.getRecordHandle(tx);
- if (!p) {
- logger.warn(`purchase ${proposalId} does not exist anymore`);
- return;
- }
- if (p.purchaseStatus !== PurchaseStatus.Done) {
- return;
- }
- p.purchaseStatus = PurchaseStatus.PendingQueryingRefund;
- await h.update(p, "start-query-refund");
- });
- wex.taskScheduler.startShepherdTask(ctx.taskId);
+ await wex.runWalletDbTx((tx) => startQueryRefundInTx(ctx, tx));
}
async function computeRefreshRequest(