commit a2e28c585d64de213c11e0627c7125326181bf2a
parent 5a163b8eaa1023ff0a4f9fe36054022b9ed73bf3
Author: Florian Dold <dold@taler.net>
Date: Tue, 17 Nov 2026 19:00:09 +0100
wallet recoup: retry coins skipped by older wallets
Recheck dormant coins and requests sent to unsupported endpoints.
When coins share a parent, subtract credits already scheduled for
refresh.
Diffstat:
7 files changed, 358 insertions(+), 4 deletions(-)
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -305,6 +305,8 @@ export type KycAuthTransferOptionRaw = TransferOptionRaw & {
* in the same transaction that inserts the WalletRecoupGroup.
*/
export interface WalletRecoupGroup {
+ /** Aggregate credits already scheduled by the legacy group being reconciled. */
+ legacyRefreshCredits?: Record<string, AmountString>;
/** Actual credited value per coin; zero also records an already spent coin. */
recoveredAmounts?: Record<string, AmountString>;
/** Durable reason for a permanent failure. */
@@ -2191,6 +2193,7 @@ export enum PurchaseStatus {
}
export enum ConfigRecordKey {
+ RecoupRecoveryVersion = "recoupRecoveryVersion",
WalletBackupState = "walletBackupState",
CurrencyDefaultsApplied = "currencyDefaultsApplied",
// Only for testing, do not use!
@@ -2265,6 +2268,7 @@ export type ConfigRecord =
| { key: ConfigRecordKey.LastResumed; value: DbProtocolTimestamp }
| { key: ConfigRecordKey.MaterializedTransactionsVersion; value: number }
| { key: ConfigRecordKey.CoinAvailabilityVersion; value: number }
+ | { key: ConfigRecordKey.RecoupRecoveryVersion; value: number }
| { key: ConfigRecordKey.DonauConfig; value: DonauConfig }
| { key: ConfigRecordKey.RefreshBalanceGeneration; value: string }
| { key: ConfigRecordKey.RefreshBalance; value: WalletRefreshBalance };
diff --git a/packages/taler-wallet-core/src/db/sqlite/schema.ts b/packages/taler-wallet-core/src/db/sqlite/schema.ts
@@ -85,7 +85,7 @@
*
* Bump this when adding a migration to {@link schemaMigrations}.
*/
-export const SQLITE_SCHEMA_VERSION = 28;
+export const SQLITE_SCHEMA_VERSION = 29;
/**
* Tables of the IndexedDB emulation, children before parents.
@@ -1552,6 +1552,13 @@ export const schemaMigrations: SchemaMigration[] = [
"ALTER TABLE refresh_groups ADD COLUMN recoup_group_per_coin TEXT",
],
},
+ {
+ version: 29,
+ name: "legacy-recoup-credits",
+ statements: [
+ "ALTER TABLE recoup_groups ADD COLUMN legacy_refresh_credits TEXT",
+ ],
+ },
];
/** Native tables that contain wallet records (not schema bookkeeping). */
diff --git a/packages/taler-wallet-core/src/db/sqlite/transaction.ts b/packages/taler-wallet-core/src/db/sqlite/transaction.ts
@@ -5540,6 +5540,9 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
private rowToRecoupGroup(row: ResultRow): WalletRecoupGroup {
return {
+ ...(row.legacy_refresh_credits == null
+ ? {}
+ : { legacyRefreshCredits: dbToJson(row.legacy_refresh_credits) }),
...(row.recovered_amounts == null
? {}
: { recoveredAmounts: dbToJson(row.recovered_amounts) }),
@@ -5585,13 +5588,14 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
async upsertRecoupGroup(rec: WalletRecoupGroup): Promise<void> {
await this.run(
- `INSERT INTO recoup_groups (recovered_amounts,
+ `INSERT INTO recoup_groups (legacy_refresh_credits, recovered_amounts,
recoup_group_id, exchange_base_url, operation_status,
timestamp_started, timestamp_finished, coin_pubs,
recoup_finished_per_coin, failed_coin_pubs, successful_coin_pubs,
schedule_refresh_coins, fail_reason
- ) VALUES ($amounts, $id, $url, $status, $started, $finished, $pubs, $fin, $failed, $success, $sched, $fail_reason)
+ ) VALUES ($legacyCredits, $amounts, $id, $url, $status, $started, $finished, $pubs, $fin, $failed, $success, $sched, $fail_reason)
ON CONFLICT(recoup_group_id) DO UPDATE SET
+ legacy_refresh_credits = excluded.legacy_refresh_credits,
recovered_amounts = excluded.recovered_amounts,
exchange_base_url = excluded.exchange_base_url,
operation_status = excluded.operation_status,
@@ -5604,6 +5608,10 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
schedule_refresh_coins = excluded.schedule_refresh_coins,
fail_reason = excluded.fail_reason`,
{
+ legacyCredits:
+ rec.legacyRefreshCredits == null
+ ? null
+ : jsonToDb(rec.legacyRefreshCredits),
amounts:
rec.recoveredAmounts == null ? null : jsonToDb(rec.recoveredAmounts),
fail_reason: rec.failReason == null ? null : jsonToDb(rec.failReason),
diff --git a/packages/taler-wallet-core/src/db/testing/conformance-cases.ts b/packages/taler-wallet-core/src/db/testing/conformance-cases.ts
@@ -4447,6 +4447,7 @@ export const conformanceCases: ConformanceCase[] = [
async run(t, runner) {
const rc = makeRecoupGroup("rc-1", "https://rex/");
rc.recoveredAmounts = { [ck("recoup-coin")]: "TESTKUDOS:0.3" };
+ rc.legacyRefreshCredits = { [ck("parent")]: "TESTKUDOS:0.1" };
await runner.runReadWriteTx((tx) => tx.upsertRecoupGroup(rc));
const got = await runner.runReadWriteTx((tx) =>
tx.getRecoupGroup("rc-1"),
diff --git a/packages/taler-wallet-core/src/recoup.test.ts b/packages/taler-wallet-core/src/recoup.test.ts
@@ -708,6 +708,107 @@ for (const [spent, replay] of [
});
}
+test("startup releases stale reward claims and preserves other recoup claims", async () => {
+ const { repairLegacyRecoupState } = await import("./recoup.js");
+ let refresh = {
+ oldCoinPubs: ["reward", "withdrawn"],
+ recoupGroupPerCoin: { 0: "finished", 1: "pending" },
+ };
+ let version = 2;
+ const tx = {
+ getConfig: async () => ({ value: version }),
+ upsertConfig: async (c: { value: number }) => {
+ version = c.value;
+ },
+ listAllRefreshGroups: async () => [structuredClone(refresh)],
+ getCoin: async (pub: string) => ({
+ coinSource: {
+ type:
+ pub === "reward"
+ ? R.CoinSourceType.Reward
+ : R.CoinSourceType.Withdraw,
+ },
+ }),
+ upsertRefreshGroup: async (r: typeof refresh) => {
+ refresh = r;
+ },
+ };
+ await repairLegacyRecoupState({
+ runWalletDbTx: async (f: any) => f(tx),
+ } as import("./wallet.js").WalletExecutionContext);
+ assert.deepEqual(refresh.recoupGroupPerCoin, { 1: "pending" });
+ assert.equal(version, 3);
+});
+
+test("startup repair retries old skipped and unsupported recoups exactly once", async (t) => {
+ const U = await import("@gnu-taler/taler-util");
+ const { repairLegacyRecoupState, RecoupTransactionContext } =
+ await import("./recoup.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const groups = ["skipped", "unsupported", "success", "invalid"].map(
+ (name) => ({
+ recoupGroupId: name,
+ exchangeBaseUrl: "https://exchange.example/",
+ coinPubs: [name],
+ recoupFinishedPerCoin: [true],
+ operationStatus: R.RecoupOperationStatus.Finished,
+ scheduleRefreshCoins: [],
+ successfulCoinPubs: name === "success" ? [name] : [],
+ failedCoinPubs: ["unsupported", "invalid"].includes(name) ? [name] : [],
+ failReason: {
+ errorsPerCoin: {
+ [name]: {
+ code:
+ name === "unsupported"
+ ? U.TalerErrorCode.EXCHANGE_GENERIC_OPERATION_UNKNOWN
+ : U.TalerErrorCode.GENERIC_PARAMETER_MALFORMED,
+ },
+ },
+ },
+ }),
+ ) as unknown as R.WalletRecoupGroup[];
+ let marker: R.ConfigRecord | undefined;
+ const tx = {
+ listAllRefreshGroups: async () => [],
+ getConfig: async () => marker,
+ upsertConfig: async (c: R.ConfigRecord) => {
+ marker = c;
+ },
+ listAllRecoupGroups: async () => [...groups],
+ upsertRecoupGroup: async (g: R.WalletRecoupGroup) => {
+ groups.push(g);
+ },
+ upsertCoin: async () => {},
+ getCoin: async () => ({
+ status: U.CoinStatus.Dormant,
+ coinSource: { type: R.CoinSourceType.Withdraw },
+ }),
+ };
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ } as unknown as import("./wallet.js").WalletExecutionContext;
+ await repairLegacyRecoupState(wex);
+ assert.deepStrictEqual(
+ groups.slice(4).map((g) => g.coinPubs),
+ [["skipped"], ["unsupported"]],
+ );
+ assert.ok(
+ groups
+ .slice(4)
+ .every(
+ (g) =>
+ g.operationStatus === R.RecoupOperationStatus.Pending &&
+ !g.recoupFinishedPerCoin[0],
+ ),
+ );
+ await repairLegacyRecoupState(wex);
+ assert.equal(groups.length, 6);
+});
+
test("deleting recoup history does not requeue credited, rejected or reward coins", async () => {
const { createRecoupGroup, RecoupTransactionContext } =
await import("./recoup.js");
@@ -751,3 +852,101 @@ test("deleting recoup history does not requeue credited, rejected or reward coin
coins.map((c) => c.coinPub),
);
});
+
+test("legacy repair reconciles every sibling without scheduling an old credit twice", async (t) => {
+ const {
+ repairLegacyRecoupState,
+ RecoupTransactionContext,
+ recordRecoupCredit,
+ recoupRefreshRequests,
+ } = await import("./recoup.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const coins = new Map(
+ ["recovered", "skipped", "known"].map((pub) => [
+ pub,
+ {
+ coinPub: pub,
+ recoupGroupId: "legacy",
+ coinSource: { type: R.CoinSourceType.Refresh, oldCoinPub: "parent" },
+ } as R.WalletCoin,
+ ]),
+ );
+ coins.set("parent", { coinPub: "parent" } as R.WalletCoin);
+ const legacy = {
+ recoupGroupId: "legacy",
+ timestampStarted: 1000 as R.DbPreciseTimestamp,
+ timestampFinished: 2000 as R.DbPreciseTimestamp,
+ exchangeBaseUrl: "https://exchange.example/",
+ coinPubs: ["recovered", "skipped", "known"],
+ recoupFinishedPerCoin: [true, true, true],
+ operationStatus: R.RecoupOperationStatus.Finished,
+ successfulCoinPubs: [],
+ recoveredAmounts: { known: "TESTKUDOS:0.5" },
+ scheduleRefreshCoins: [{ coinPub: "parent", amount: "TESTKUDOS:1.5" }],
+ } as R.WalletRecoupGroup;
+ const groups = new Map([["legacy", legacy]]);
+ let marker = { key: R.ConfigRecordKey.RecoupRecoveryVersion, value: 1 };
+ const tx = {
+ getConfig: async () => marker,
+ upsertConfig: async (c: typeof marker) => {
+ marker = c;
+ },
+ listAllRecoupGroups: async () => structuredClone([...groups.values()]),
+ listAllRefreshGroups: async () => [],
+ getCoin: async (pub: string) => structuredClone(coins.get(pub)),
+ upsertCoin: async (c: R.WalletCoin) => {
+ coins.set(c.coinPub, structuredClone(c));
+ },
+ getRecoupGroup: async (id: string) => structuredClone(groups.get(id)),
+ upsertRecoupGroup: async (g: R.WalletRecoupGroup) => {
+ groups.set(g.recoupGroupId, structuredClone(g));
+ },
+ } as unknown as import("./db/transaction.js").WalletDbTransaction;
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ } as import("./wallet.js").WalletExecutionContext;
+ await repairLegacyRecoupState(wex);
+ const repair = [...groups.values()].find(
+ (g) => g.recoupGroupId !== "legacy",
+ )!;
+ assert.deepStrictEqual(repair.coinPubs, ["recovered", "skipped"]);
+ assert.deepStrictEqual(repair.legacyRefreshCredits, {
+ parent: "TESTKUDOS:1",
+ });
+ assert.equal(coins.get("skipped")!.recoupGroupId, undefined);
+ await recordRecoupCredit(
+ wex,
+ tx,
+ repair.recoupGroupId,
+ 0,
+ coins.get("recovered")!,
+ "TESTKUDOS:1",
+ );
+ // Replaying the persisted success after restart must not add it twice.
+ await recordRecoupCredit(
+ wex,
+ tx,
+ repair.recoupGroupId,
+ 0,
+ coins.get("recovered")!,
+ "TESTKUDOS:1",
+ );
+ await recordRecoupCredit(
+ wex,
+ tx,
+ repair.recoupGroupId,
+ 1,
+ coins.get("skipped")!,
+ "TESTKUDOS:0.4",
+ );
+ assert.deepStrictEqual(
+ recoupRefreshRequests(groups.get(repair.recoupGroupId)!),
+ [{ coinPub: "parent", amount: "TESTKUDOS:0.4" }],
+ );
+ await repairLegacyRecoupState(wex);
+ assert.equal(groups.size, 2);
+});
diff --git a/packages/taler-wallet-core/src/recoup.ts b/packages/taler-wallet-core/src/recoup.ts
@@ -68,6 +68,7 @@ import {
constructTaskIdentifier,
} from "./common.js";
import {
+ ConfigRecordKey,
RecoupOperationStatus,
CoinSourceType,
WithdrawalGroupStatus,
@@ -500,6 +501,22 @@ export async function recordRecoupCredit(
await putGroupAsFinished(wex, tx, group, coinIndex);
}
+/** Exclude credits already handed to a successor by a legacy recoup group. */
+export function recoupRefreshRequests(group: WalletRecoupGroup) {
+ return group.scheduleRefreshCoins
+ .map((request) => ({
+ ...request,
+ amount: Amounts.stringify(
+ Amounts.sub(
+ request.amount,
+ group.legacyRefreshCredits?.[request.coinPub] ??
+ Amounts.zeroOfAmount(request.amount),
+ ).amount,
+ ),
+ }))
+ .filter((request) => Amounts.isNonZero(request.amount));
+}
+
export async function processRecoupGroup(
wex: WalletExecutionContext,
recoupGroupId: string,
@@ -653,7 +670,7 @@ export async function completeRecoupGroup(
rg2.operationStatus = rg2.failedCoinPubs?.length
? RecoupOperationStatus.Failed
: RecoupOperationStatus.Finished;
- const refreshRequests = rg2.scheduleRefreshCoins;
+ const refreshRequests = recoupRefreshRequests(rg2);
if (refreshRequests.length > 0) {
await createRefreshGroup(
wex,
@@ -1209,3 +1226,118 @@ async function usesBatchRecoup(
42
);
}
+
+/** One-time durable repair: network work remains owned by normal recoup tasks. */
+export async function repairLegacyRecoupState(
+ wex: WalletExecutionContext,
+): Promise<void> {
+ await wex.runWalletDbTx(async (tx) => {
+ const version = (await tx.getConfig(ConfigRecordKey.RecoupRecoveryVersion))
+ ?.value;
+ if (version === 3) return;
+ // Commit the version with both repairs, so an interruption retries them.
+ await tx.upsertConfig({
+ key: ConfigRecordKey.RecoupRecoveryVersion,
+ value: 3,
+ });
+ for (const refresh of await tx.listAllRefreshGroups()) {
+ const bindings = refresh.recoupGroupPerCoin;
+ if (!bindings) continue;
+ let changed = false;
+ for (const index of Object.keys(bindings).map(Number)) {
+ const coin = await tx.getCoin(refresh.oldCoinPubs[index]);
+ if (coin?.coinSource.type === CoinSourceType.Reward) {
+ delete bindings[index];
+ changed = true;
+ }
+ }
+ if (changed) await tx.upsertRefreshGroup(refresh);
+ }
+ if (version === 2) return;
+ const groups = await tx.listAllRecoupGroups();
+ for (const group of [...groups]) {
+ if (group.legacyRefreshCredits !== undefined) continue;
+ const retryCoins: string[] = [];
+ const legacyRefreshCredits = Object.fromEntries(
+ group.scheduleRefreshCoins.map((c) => [c.coinPub, c.amount]),
+ );
+ for (let i = 0; i < group.coinPubs.length; i++) {
+ const pub = group.coinPubs[i];
+ const coin = await tx.getCoin(pub);
+ if (!coin || coin.coinSource.type === CoinSourceType.Reward) continue;
+ const amount = group.recoveredAmounts?.[pub];
+ if (amount !== undefined || group.successfulCoinPubs?.includes(pub)) {
+ coin.recoupGroupId ??= group.recoupGroupId;
+ await tx.upsertCoin(coin);
+ if (
+ amount !== undefined &&
+ coin.coinSource.type === CoinSourceType.Refresh
+ ) {
+ const parent = coin.coinSource.oldCoinPub;
+ if (legacyRefreshCredits[parent])
+ legacyRefreshCredits[parent] = Amounts.stringify(
+ Amounts.sub(legacyRefreshCredits[parent], amount).amount,
+ );
+ }
+ continue;
+ }
+ // The v1 repair inferred individual success from a shared parent credit.
+ // Clear that unproven marker; reconcile every ambiguous sibling instead.
+ if (coin.recoupGroupId === group.recoupGroupId) {
+ delete coin.recoupGroupId;
+ await tx.upsertCoin(coin);
+ }
+ if (!group.recoupFinishedPerCoin[i]) continue;
+ const reason = (
+ group.failReason?.errorsPerCoin as
+ | Record<string, TalerErrorDetail>
+ | undefined
+ )?.[pub];
+ if (
+ group.failedCoinPubs?.includes(pub) &&
+ reason?.code !== TalerErrorCode.GENERIC_ENDPOINT_UNKNOWN &&
+ reason?.code !== TalerErrorCode.EXCHANGE_GENERIC_OPERATION_UNKNOWN
+ )
+ continue;
+ if (
+ groups.some(
+ (g) =>
+ g !== group &&
+ g.coinPubs.includes(pub) &&
+ (g.operationStatus === RecoupOperationStatus.Pending ||
+ g.operationStatus === RecoupOperationStatus.Suspended ||
+ g.recoveredAmounts?.[pub] !== undefined ||
+ g.successfulCoinPubs?.includes(pub)),
+ )
+ )
+ continue;
+ retryCoins.push(pub);
+ }
+ if (retryCoins.length) {
+ const repair: WalletRecoupGroup = {
+ recoupGroupId: encodeCrock(getRandomBytes(32)),
+ exchangeBaseUrl: group.exchangeBaseUrl,
+ timestampStarted: timestampPreciseToDb(TalerPreciseTimestamp.now()),
+ timestampFinished: undefined,
+ operationStatus:
+ group.operationStatus === RecoupOperationStatus.Suspended
+ ? RecoupOperationStatus.Suspended
+ : RecoupOperationStatus.Pending,
+ coinPubs: retryCoins,
+ recoupFinishedPerCoin: retryCoins.map(() => false),
+ recoveredAmounts: {},
+ legacyRefreshCredits,
+ successfulCoinPubs: [],
+ failedCoinPubs: [],
+ scheduleRefreshCoins: [],
+ };
+ await tx.upsertRecoupGroup(repair);
+ await new RecoupTransactionContext(
+ wex,
+ repair.recoupGroupId,
+ ).updateTransactionMeta(tx);
+ groups.push(repair);
+ }
+ }
+ });
+}
diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts
@@ -15,6 +15,8 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { repairLegacyRecoupState } from "./recoup.js";
+
/**
* High-level wallet operations that should be independent from the underlying
* browser extension interface.
@@ -1069,6 +1071,7 @@ async function handleSetWalletRunConfig(
await migrateCoinAvailability(wex);
if (!wex.ws.initCalled) {
+ await repairLegacyRecoupState(wex);
await cleanupFailedClaimsOnStartup(wex);
await collectLeftoverClaims(wex);
await deleteEphemeralExchanges(wex);