commit 5b1d5b17e65d095c66e7b37b6119377ae2ce2ed3
parent 29bf4495560dc0293862fc4047b9fe23ab0153cc
Author: Florian Dold <dold@taler.net>
Date: Fri, 27 Nov 2026 18:14:31 +0100
wallet-core: resume confirmed payment aborts without contacting the merchant
Retry when the merchant has no exchange response. Save its final abort
result with the refund receipts so a restarted wallet can finish from
local evidence.
Issue: https://bugs.taler.net/n/12291
Diffstat:
3 files changed, 179 insertions(+), 1 deletion(-)
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -956,6 +956,10 @@ export interface WalletTokenSelection {
export type AccountedCoinRefunds = Record<string, Record<number, AmountString>>;
export interface WalletPurchasePayInfo {
+ /** Final merchant response persisted before waiting for the exchange melts. */
+ merchantAbortStatus?:
+ | PurchaseStatus.AbortedRefunded
+ | PurchaseStatus.AbortedOrderDeleted;
/** Distinguishes an explicit pause from a legacy 451 with no retry record. */
suspendedByUser?: boolean;
accountedRefunds?: AccountedCoinRefunds;
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -1567,6 +1567,134 @@ async function seedRefundExchange(
}
for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: a verified abort receipt survives a key gap and restart`, async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: 150_000 });
+ const directory = await mkdtemp(join(tmpdir(), "wallet-abort-refund-"));
+ const filename = join(directory, "wallet.db");
+ let runner = await makeRunner(filename);
+ t.after(async () => {
+ await runner.close();
+ await rm(directory, { recursive: true, force: true });
+ });
+ const wex = refundTestWallet((f) => runner.runReadWriteTx(f));
+ const purchase = makeDownloadedPurchase(
+ "refused",
+ PurchaseStatus.AbortingWithRefund,
+ );
+ const coin = makeCoin("refused");
+ const signPub = encodeCrock(new Uint8Array(32).fill(9));
+ purchase.payInfo!.payCoinSelection = {
+ coinPubs: [coin.coinPub],
+ coinContributions: ["TESTKUDOS:10"],
+ };
+ await runner.runReadWriteTx(async (tx) => {
+ await upsertTestContractTerms(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ await seedRefundExchange(tx, coin, signPub, false);
+ await tx.upsertCoin({ ...coin, status: CoinStatus.Dormant });
+ });
+ let requests = 0;
+ const receipt = signedRefund(signPub, coin.coinPub, 0, "TESTKUDOS:10");
+ Object.assign(wex, {
+ http: {
+ async fetch(url: string) {
+ assert.ok(url.endsWith("/abort"));
+ const unavailable = ++requests === 1;
+ return {
+ status: unavailable ? 502 : 200,
+ headers: new HeadersImpl(),
+ json: async () => ({
+ refunds: [
+ unavailable
+ ? {
+ type: "failure",
+ exchange_status: 0,
+ exchange_code: TalerErrorCode.GENERIC_INVALID_RESPONSE,
+ }
+ : receipt,
+ ],
+ }),
+ };
+ },
+ },
+ });
+ const run = () => processPurchase(wex, purchase.proposalId);
+ assert.equal((await run()).type, TaskRunResultType.Backoff);
+ await runner.runReadWriteTx(async (tx) => {
+ const item = await tx.getRefundItemByCoinAndRtxid(coin.coinPub, 0);
+ assert.equal(item?.status, RefundItemStatus.Pending);
+ const current = (await tx.getPurchase(purchase.proposalId))!;
+ assert.equal(current.payInfo?.merchantAbortStatus, undefined);
+ // The precautionary refresh wins before the merchant can confirm its refund.
+ const abort = (await tx.getRefreshGroup(current.abortRefreshGroupId!))!;
+ abort.statusPerCoin[0] = RefreshCoinStatus.Finished;
+ abort.operationStatus = RefreshOperationStatus.Finished;
+ abort.expectedOutputPerCoin[0] = "TESTKUDOS:9.9";
+ abort.paymentRecovery!.settledPerCoin[0] = { melted: "TESTKUDOS:10" };
+ await tx.upsertRefreshGroup(abort);
+ });
+ assert.equal((await run()).type, TaskRunResultType.Backoff);
+ await runner.close();
+ runner = await makeRunner(filename);
+ assert.equal((await run()).type, TaskRunResultType.Backoff);
+ await runner.runReadWriteTx(async (tx) => {
+ const item = await tx.getRefundItemByCoinAndRtxid(coin.coinPub, 0);
+ assert.equal(item?.status, RefundItemStatus.Done);
+ const groups = await tx.getRefreshGroupsByOriginatingTransaction(
+ new PayMerchantTransactionContext(wex, purchase.proposalId)
+ .transactionId,
+ );
+ assert.equal(groups.length, 2);
+ const g = groups.find((g) => g.reason === RefreshReason.Refund)!;
+ assert.equal(g.paymentRecovery?.refundGroupId, item!.refundGroupId);
+ assert.deepEqual(g.inputPerCoin, ["TESTKUDOS:10.1"]);
+ assert.equal(g.statusPerCoin[0], RefreshCoinStatus.Pending);
+ assert.equal(await tx.getRefreshSession(g.refreshGroupId, 0), undefined);
+ assert.equal(
+ (await tx.getPurchase(purchase.proposalId))!.payInfo!.accountedRefunds![
+ coin.coinPub
+ ][0],
+ "TESTKUDOS:10",
+ );
+ // The refund's own refresh sees only the amount below the smallest denomination.
+ g.statusPerCoin[0] = RefreshCoinStatus.Finished;
+ g.operationStatus = RefreshOperationStatus.Finished;
+ g.inputPerCoin[0] = "TESTKUDOS:0.1";
+ g.paymentRecovery!.settledPerCoin[0] = {
+ melted: "TESTKUDOS:0",
+ dust: "TESTKUDOS:0.1",
+ };
+ await tx.upsertRefreshGroup(g);
+ // Wallets predating the saved abort status can resume from the verified receipts.
+ const legacy = (await tx.getPurchase(purchase.proposalId))!;
+ assert.equal(
+ legacy.payInfo?.merchantAbortStatus,
+ PurchaseStatus.AbortedRefunded,
+ );
+ delete legacy.payInfo!.merchantAbortStatus;
+ await tx.upsertPurchase(legacy);
+ const refund = (await tx.getRefundGroup(item!.refundGroupId))!;
+ delete refund.refundReason;
+ await tx.upsertRefundGroup(refund);
+ });
+ await runner.close();
+ runner = await makeRunner(filename);
+ wex.ws.networkAvailable = false;
+ assert.equal(
+ (await processPurchase(wex, purchase.proposalId)).type,
+ TaskRunResultType.Progress,
+ );
+ assert.equal(requests, 2);
+ await runner.runReadWriteTx(async (tx) => {
+ const rec = await tx.getPurchase(purchase.proposalId);
+ assert.equal(rec?.purchaseStatus, PurchaseStatus.AbortedRefunded);
+ const [refund] = await tx.getRefundGroupsByProposal(purchase.proposalId);
+ assert.equal(refund.amountRaw, "TESTKUDOS:10");
+ assert.equal(refund.amountEffective, "TESTKUDOS:9.9");
+ assert.equal(refund.transactionAmounts?.final, "TESTKUDOS:9.9");
+ });
+ });
+
test(`${makeRunner.name}: an undeposited reply reserves the combined remainder exactly once`, async (t) => {
const runner = await makeRunner();
t.after(() => runner.close());
@@ -1611,10 +1739,12 @@ for (const makeRunner of runnerFactories) {
await tx.upsertPurchase(purchase);
});
+ let requests = 0;
Object.assign(wex, {
http: {
async fetch(url: string) {
assert.ok(url.endsWith("/abort"));
+ requests++;
return {
status: 200,
headers: new HeadersImpl(),
@@ -1625,6 +1755,7 @@ for (const makeRunner of runnerFactories) {
});
const run = () => processPurchase(wex, purchase.proposalId);
assert.equal((await run()).type, TaskRunResultType.Backoff);
+ wex.ws.networkAvailable = false;
assert.equal((await run()).type, TaskRunResultType.Backoff);
await runner.runReadWriteTx(async (tx) => {
const groups =
@@ -1647,6 +1778,7 @@ for (const makeRunner of runnerFactories) {
await tx.upsertRefreshGroup(combined);
});
assert.equal((await run()).type, TaskRunResultType.Progress);
+ assert.equal(requests, 1);
assert.equal(
(await runner.runReadWriteTx((tx) => tx.getPurchase(purchase.proposalId)))
?.purchaseStatus,
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -3818,6 +3818,10 @@ export async function processPurchase(
};
}
+ if (purchase.purchaseStatus === PurchaseStatus.AbortingWithRefund) {
+ const saved = savedMerchantAbortStatus(purchase);
+ if (saved) return waitForRefreshOnAbortedPayment(wex, purchase, saved);
+ }
if (!wex.ws.networkAvailable) {
return TaskRunResult.networkRequired();
}
@@ -5486,6 +5490,27 @@ async function processPurchaseAutoRefund(
return TaskRunResult.progress();
}
+function savedMerchantAbortStatus(purchase: WalletPurchase) {
+ if (!purchase.abortRefreshGroupId) return undefined;
+ const info = purchase.payInfo;
+ if (info?.merchantAbortStatus) return info.merchantAbortStatus;
+ // In older wallets a verified full refund for every selected coin also
+ // settles the merchant side. Undeposited replies had no durable record.
+ const selection = info?.payCoinSelection;
+ const receipts =
+ info?.accountedRefunds ?? purchase.download?.accountedRefunds;
+ if (
+ selection?.coinPubs.length &&
+ selection.coinPubs.every(
+ (pub, i) =>
+ receipts?.[pub]?.[0] !== undefined &&
+ Amounts.cmp(receipts[pub][0], selection.coinContributions[i]) === 0,
+ )
+ )
+ return PurchaseStatus.AbortedRefunded;
+ return undefined;
+}
+
async function processPurchaseAbortingRefund(
wex: WalletExecutionContext,
purchase: WalletPurchase,
@@ -5684,7 +5709,16 @@ async function waitForRefreshOnAbortedPayment(
| PurchaseStatus.AbortedRefunded,
): Promise<TaskRunResult> {
const abortRefreshGroupId = await wex.runWalletDbTx(async (tx) => {
- return (await tx.getPurchase(purchase.proposalId))?.abortRefreshGroupId;
+ const rec = await tx.getPurchase(purchase.proposalId);
+ if (
+ rec?.purchaseStatus === PurchaseStatus.AbortingWithRefund &&
+ rec.payInfo &&
+ rec.payInfo.merchantAbortStatus === undefined
+ ) {
+ rec.payInfo.merchantAbortStatus = finalStatus;
+ await tx.upsertPurchase(rec);
+ }
+ return rec?.abortRefreshGroupId;
});
checkLogicInvariant(!!abortRefreshGroupId);
@@ -6231,6 +6265,7 @@ export function getRefundGroupFailure(
export function isTransientRefundStatus(status: number): boolean {
return (
+ status === 0 || // The merchant received no exchange response.
status === HttpStatusCode.RequestTimeout ||
status === HttpStatusCode.TooManyRequests ||
(status >= 500 && status <= 599)
@@ -6549,6 +6584,13 @@ export async function storeRefunds(
);
if (!hasPendingRefunds) {
+ if (
+ isAborting &&
+ reason === RefundReason.AbortRefund &&
+ myPurchase.payInfo
+ ) {
+ myPurchase.payInfo.merchantAbortStatus = PurchaseStatus.AbortedRefunded;
+ }
if (!isAborting) {
myPurchase.purchaseStatus = shouldCheckAutoRefund
? PurchaseStatus.FinalizingQueryingAutoRefund