commit 2ec810501896ec0fb14aee48d54afa3e1a509708
parent d6a69d07fcff552c8d9f834ff85a34fdfdd71f47
Author: Florian Dold <dold@taler.net>
Date: Fri, 27 Nov 2026 18:12:45 +0100
wallet-core: resume legacy payment aborts after importing a wallet
Recover suspended refusals in the import transaction and wake the task
scheduler when the wallet is already running.
Issue: https://bugs.taler.net/n/12291
Diffstat:
4 files changed, 116 insertions(+), 5 deletions(-)
diff --git a/packages/taler-wallet-core/src/observable-wrappers.ts b/packages/taler-wallet-core/src/observable-wrappers.ts
@@ -101,8 +101,8 @@ export class ObservableTaskScheduler implements TaskScheduler {
return this.impl.resetTask(taskId);
}
- async reload(): Promise<void> {
- return this.impl.reload();
+ async reload(options?: { onlyIfRunning?: boolean }): Promise<void> {
+ return this.impl.reload(options);
}
}
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -38,6 +38,8 @@ import {
MerchantContractOutputType,
MerchantContractVersion,
NotificationType,
+ openPromise,
+ SetTimeoutTimerAPI,
RefreshReason,
SelectedCoin,
SignedTokenEnvelope,
@@ -130,7 +132,8 @@ import {
} from "./pay-merchant.js";
import { deleteExchange } from "./exchanges.js";
import { makeIdbRunner, runnerFactories } from "./db/testing/runners.js";
-import type { WalletExecutionContext } from "./wallet.js";
+import { Wallet, type WalletExecutionContext } from "./wallet.js";
+import { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronousWorkerFactoryPlain.js";
import { nativeCrypto } from "./crypto/cryptoImplementation.js";
import { HeadersImpl } from "@gnu-taler/taler-util/http";
import { dispatchRequestInternal } from "./requests.js";
@@ -2673,6 +2676,111 @@ for (const makeRunner of runnerFactories) {
});
}
+for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: importing a legacy refusal wakes the running wallet and submits its abort`, async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: 150_000 });
+ const source = await makeRunner();
+ const target = await makeRunner();
+ const abort = openPromise<unknown>();
+ const paths: string[] = [];
+ const wallet = await Wallet.create(
+ target,
+ () => ({
+ async fetch(url, options) {
+ const path = new URL(url).pathname;
+ paths.push(path);
+ if (path.endsWith("/abort")) abort.resolve(options?.body);
+ throw Error("test transport offline");
+ },
+ }),
+ new SetTimeoutTimerAPI(),
+ new SynchronousCryptoWorkerFactoryPlain(),
+ );
+ const purchase = makeDownloadedPurchase(
+ "imported",
+ PurchaseStatus.SuspendedPaying,
+ );
+ const coin = makeCoin("selected-before-import");
+ purchase.payInfo!.payCoinSelection = {
+ coinPubs: [coin.coinPub],
+ coinContributions: ["TESTKUDOS:1"],
+ };
+ const reason = {
+ code: TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LEGALLY_REFUSED,
+ };
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await source.runReadWriteTx(async (tx) => {
+ const url = coin.exchangeBaseUrl;
+ const denom = makeDenomination(url, coin.denomPubHash);
+ await tx.upsertExchangeDetails(
+ makeExchangeDetails(url, coin.exchangeMasterPub),
+ );
+ await tx.upsertExchange({
+ ...makeExchange(url),
+ detailsPointer: {
+ masterPublicKey: coin.exchangeMasterPub,
+ currency: denom.currency,
+ updateClock: purchase.timestamp,
+ },
+ });
+ denom.denominationFamilySerial = await tx.upsertDenominationFamily({
+ familyParams: {
+ exchangeBaseUrl: url,
+ exchangeMasterPub: coin.exchangeMasterPub,
+ value: denom.value,
+ ...denom.fees,
+ },
+ });
+ await tx.upsertDenomination(denom);
+ await tx.upsertCoin({ ...coin, status: CoinStatus.Dormant });
+ await upsertTestContractTerms(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ await tx.upsertOperationRetry({
+ id: TaskIdentifiers.forPay(purchase),
+ lastError: reason,
+ retryInfo: DbRetryInfo.reset(),
+ });
+ });
+ await wallet.client.call(WalletApiOperation.SetWalletRunConfig, {
+ config: {
+ testing: { skipDefaults: true },
+ features: { migrateNativeDb: false },
+ },
+ });
+ await wallet.client.call(WalletApiOperation.ImportDb, {
+ dump: await source.exportDatabase(),
+ });
+ const request = await Promise.race([
+ abort.promise,
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(
+ () => reject(Error("imported payment did not request /abort")),
+ 5000,
+ );
+ }),
+ ]);
+ assert.deepEqual(request, {
+ h_contract: purchase.download!.contractTermsHash,
+ coins: [{ coin_pub: coin.coinPub, exchange_url: coin.exchangeBaseUrl }],
+ });
+ const restored = await target.runReadWriteTx((tx) =>
+ tx.getPurchase(purchase.proposalId),
+ );
+ assert.equal(restored?.purchaseStatus, PurchaseStatus.AbortingWithRefund);
+ assert.deepEqual(restored?.abortReason, reason);
+ assert.deepEqual(
+ restored?.payInfo?.payCoinSelection,
+ purchase.payInfo!.payCoinSelection,
+ );
+ assert.ok(!paths.some((path) => path.endsWith("/pay")));
+ } finally {
+ clearTimeout(timeout);
+ await wallet.shutdown();
+ await source.close();
+ }
+ });
+}
test("already-paid recovery retains the paid-by-other terminal state", () => {
assert.strictEqual(
diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts
@@ -2032,6 +2032,7 @@ async function importDbDump(
};
const finalize = async (tx: WalletDbTransaction): Promise<void> => {
report("verify");
+ await recoverSuspendedLegalRefusalsInTx(wex, tx);
await migrateRefundPurchaseSnapshotsInTx(tx);
await rematerializeTransactionsAtCurrentVersion(wex, tx);
await recomputeCoinAvailabilityAtCurrentVersion(tx);
@@ -2075,6 +2076,7 @@ async function importDbDump(
await wex.runWalletDbTx((tx) => scheduleAttentionExpirations(wex, tx));
wex.ws.notify({ type: NotificationType.UserAttentionChanged });
wex.ws.clearAllCaches();
+ await wex.taskScheduler.reload({ onlyIfRunning: true });
return {};
}
diff --git a/packages/taler-wallet-core/src/shepherd.ts b/packages/taler-wallet-core/src/shepherd.ts
@@ -209,7 +209,7 @@ export interface TaskScheduler {
* Restart a task and reset retry counter.
*/
resetTask(taskId: TaskIdStr): Promise<void>;
- reload(): Promise<void>;
+ reload(options?: { onlyIfRunning?: boolean }): Promise<void>;
getActiveTasks(): TaskIdStr[];
isIdle(): boolean;
shutdown(): Promise<void>;
@@ -328,7 +328,8 @@ export class TaskSchedulerImpl implements TaskScheduler {
*
* Mostly useful to interrupt all waits when time-travelling.
*/
- async reload(): Promise<void> {
+ async reload(options?: { onlyIfRunning?: boolean }): Promise<void> {
+ if (options?.onlyIfRunning && !this.isRunning) return;
logger.info("reloading all shepherd tasks");
await this.ensureRunning();
const tasksIds = [...this.sheps.keys()];