commit f0aa4d7173ec0f3afda622d916a9913314223a95
parent 1634d090373b06953db5bdded07c57f31b11b46e
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 18:09:17 +0100
wallet-core: update a coin's refresh fields together
Completing a refresh meant updating the same slot in several arrays. Use
a view keyed by the coin index that identifies its saved session to
update the amounts, status and recovery data together without changing
the database format.
Diffstat:
9 files changed, 490 insertions(+), 203 deletions(-)
diff --git a/packages/taler-wallet-core/src/autoRefreshBalance.ts b/packages/taler-wallet-core/src/autoRefreshBalance.ts
@@ -12,6 +12,7 @@
see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { RefreshInput } from "./refresh-input.js";
import {
AbsoluteTime,
Amounts,
@@ -291,8 +292,8 @@ export async function addRefreshBalanceInfo(
);
const retry = await tx.getOperationRetry(`refresh:${rg.refreshGroupId}`);
for (const coin of coins) {
- const coinIndex = rg.oldCoinPubs.indexOf(coin.coinPub);
- if (rg.statusPerCoin[coinIndex] === RefreshCoinStatus.Finished) continue;
+ const input = new RefreshInput(rg, rg.oldCoinPubs.indexOf(coin.coinPub));
+ if (input.status === RefreshCoinStatus.Finished) continue;
const d = oldDenoms.get(denomRefKey(coin));
if (!d) continue;
const b = await balanceFor(
@@ -303,12 +304,7 @@ export async function addRefreshBalanceInfo(
);
if (b)
markUnavailable(stringifyScopeInfo(b.scopeInfo), "pending-refresh");
- await riskFor(
- d,
- rg.inputPerCoin[coinIndex],
- retry?.lastError ?? rg.failReason,
- true,
- );
+ await riskFor(d, input.amount, retry?.lastError ?? rg.failReason, true);
}
}
for (const [scope, b] of byScope) {
diff --git a/packages/taler-wallet-core/src/deposits.ts b/packages/taler-wallet-core/src/deposits.ts
@@ -21,6 +21,7 @@
/**
* Imports.
*/
+import { finishedRefreshOutputs } from "./refresh-input.js";
import {
AbsoluteTime,
AmountJson,
@@ -101,7 +102,6 @@ import {
DepositElementStatus,
DepositOperationStatus,
KycAuthTransferOptionRaw,
- RefreshCoinStatus,
WalletDepositGroup,
WalletDepositInfoPerExchange,
WalletDepositTrackingInfo,
@@ -1133,12 +1133,7 @@ export function computeDepositAbortAmountEffective(
grossCoinInput: AmountString,
relatedRefreshes: WalletRefreshGroup[],
): AmountString {
- const recoveredOutputs = relatedRefreshes.flatMap((refreshGroup) =>
- refreshGroup.expectedOutputPerCoin.filter(
- (_amount, index) =>
- refreshGroup.statusPerCoin[index] === RefreshCoinStatus.Finished,
- ),
- );
+ const recoveredOutputs = relatedRefreshes.flatMap(finishedRefreshOutputs);
const recoveredAmount = Amounts.sumOrZero(
Amounts.currencyOf(grossCoinInput),
recoveredOutputs,
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -24,6 +24,7 @@
/**
* Imports.
*/
+import { RefreshInput } from "./refresh-input.js";
import {
readVerifiedCoinHistory,
recordConflictingCoinHistory,
@@ -5961,14 +5962,14 @@ export function classifyMerchantAbortRecoveryEvidence(
if (abortCoinIndex < 0) {
return "failed";
}
- const abortCoinStatus = abortRefresh.statusPerCoin[abortCoinIndex];
- if (abortCoinStatus !== RefreshCoinStatus.Finished) {
- return abortCoinStatus === RefreshCoinStatus.Pending ||
- abortCoinStatus === RefreshCoinStatus.PendingRedenominate
+ const input = new RefreshInput(abortRefresh, abortCoinIndex);
+ if (input.status !== RefreshCoinStatus.Finished) {
+ return input.status === RefreshCoinStatus.Pending ||
+ input.status === RefreshCoinStatus.PendingRedenominate
? "pending"
: "failed";
}
- const abortOutput = abortRefresh.expectedOutputPerCoin[abortCoinIndex];
+ const abortOutput = input.expectedOutput;
if (!abortOutput) {
return "failed";
}
@@ -6012,19 +6013,19 @@ export function classifyMerchantAbortRecoveryEvidence(
) {
return "failed";
}
+ const refundInput = new RefreshInput(refundRefresh, refundCoinIndex);
const refundRecovery = classifyRecoveryRefresh(
refundRefresh.operationStatus,
);
if (
refundRecovery === "pending" ||
- refundRefresh.statusPerCoin[refundCoinIndex] === RefreshCoinStatus.Pending
+ refundInput.status === RefreshCoinStatus.Pending
) {
return "pending";
}
if (
refundRecovery !== "recovered" ||
- refundRefresh.statusPerCoin[refundCoinIndex] !==
- RefreshCoinStatus.Finished
+ refundInput.status !== RefreshCoinStatus.Finished
) {
return "failed";
}
diff --git a/packages/taler-wallet-core/src/recoup.ts b/packages/taler-wallet-core/src/recoup.ts
@@ -24,6 +24,7 @@
/**
* Imports.
*/
+import { RefreshInput } from "./refresh-input.js";
import { getHttpResponseErrorDetails } from "@gnu-taler/taler-util/http";
import { addPermanentCoinFailure } from "./transaction-reasons.js";
import {
@@ -1238,9 +1239,10 @@ export async function repairLegacyRecoupState(
if (!bindings) continue;
let changed = false;
for (const index of Object.keys(bindings).map(Number)) {
- const coin = await tx.getCoin(refresh.oldCoinPubs[index]);
+ const input = new RefreshInput(refresh, index);
+ const coin = await tx.getCoin(input.coinPub);
if (coin?.coinSource.type === CoinSourceType.Reward) {
- delete bindings[index];
+ input.update({ recoupGroupId: null });
changed = true;
}
}
diff --git a/packages/taler-wallet-core/src/refresh-input.test.ts b/packages/taler-wallet-core/src/refresh-input.test.ts
@@ -0,0 +1,185 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+import { CoinStatus, RefreshReason } from "@gnu-taler/taler-util";
+import {
+ RefreshCoinStatus,
+ RefreshOperationStatus,
+ timestampPreciseToDb,
+ WalletRefreshGroup,
+} from "./db/records.js";
+import { makeCoin } from "./db/testing/conformance-cases.js";
+import { runnerFactories } from "./db/testing/runners.js";
+import { RefreshInput } from "./refresh-input.js";
+import { bindRefreshesToRecoup, settleRefreshesForRecoup } from "./refresh.js";
+import type { WalletExecutionContext } from "./wallet.js";
+import type { WalletDbTransaction } from "./db/transaction.js";
+
+for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: settling one refresh input preserves its sibling across restart`, async () => {
+ const directory = await mkdtemp(join(tmpdir(), "wallet-refresh-inputs-"));
+ const filename = join(directory, "wallet.db");
+ let runner = await makeRunner(filename);
+ const wex = {
+ ws: { notify() {} },
+ runWalletDbTx: <T>(f: (tx: WalletDbTransaction) => Promise<T>) =>
+ runner.runReadWriteTx(f),
+ } as unknown as WalletExecutionContext;
+ const coins = ["pending", "settled"].map(makeCoin);
+ const [pending, settled] = coins;
+ const group: WalletRefreshGroup = {
+ refreshGroupId: "two-inputs",
+ operationStatus: RefreshOperationStatus.Pending,
+ currency: "TESTKUDOS",
+ reason: RefreshReason.Scheduled,
+ oldCoinPubs: coins.map((c) => c.coinPub),
+ inputPerCoin: ["TESTKUDOS:8", "TESTKUDOS:4"],
+ expectedOutputPerCoin: ["TESTKUDOS:7", "TESTKUDOS:3"],
+ statusPerCoin: [RefreshCoinStatus.Pending, RefreshCoinStatus.Pending],
+ refundRequests: {},
+ infoPerExchange: {
+ [pending.exchangeBaseUrl]: { outputEffective: "TESTKUDOS:10" },
+ },
+ timestampCreated: timestampPreciseToDb({ t_s: 1 }),
+ timestampFinished: undefined,
+ };
+ const { refreshGroupId } = group;
+ const permission = {
+ h_contract_terms: pending.coinEvHash,
+ merchant_pub: pending.coinPub,
+ merchant_sig: pending.coinEvHash,
+ rtransaction_id: 1,
+ refund_amount: "TESTKUDOS:2",
+ } as const;
+ try {
+ // Start from the stored parallel arrays, without any optional recovery maps.
+ await runner.runReadWriteTx(async (tx) => {
+ await tx.upsertRefreshGroup(group);
+ for (const [i, coin] of coins.entries()) {
+ await tx.upsertCoin({ ...coin, status: CoinStatus.Dormant });
+ await tx.upsertRefreshSession({
+ refreshGroupId,
+ coinIndex: i,
+ newDenoms: [{ denomPubHash: coin.denomPubHash, count: 1 }],
+ sessionPublicSeed: coin.coinPriv,
+ amountRefreshOutput: group.expectedOutputPerCoin[i],
+ });
+ }
+ await tx.upsertCoinAvailability({
+ exchangeBaseUrl: pending.exchangeBaseUrl,
+ exchangeMasterPub: pending.exchangeMasterPub,
+ denomPubHash: pending.denomPubHash,
+ currency: group.currency,
+ value: "TESTKUDOS:1",
+ maxAge: 0,
+ freshCoinCount: 0,
+ visibleCoinCount: 0,
+ hasFreshCoins: 0,
+ pendingRefreshOutputCount: 2,
+ });
+ const saved = (await tx.getRefreshGroup(refreshGroupId))!;
+ new RefreshInput(saved, 0).update({
+ recoupGroupId: null,
+ reportedMeltCommitment: null,
+ });
+ assert.equal(saved.recoupGroupPerCoin, undefined);
+ assert.equal(saved.autoRefresh?.reportedMeltCommitments, undefined);
+ });
+ assert.ok(await bindRefreshesToRecoup(wex, pending, "recoup-a", []));
+ assert.ok(await bindRefreshesToRecoup(wex, settled, "recoup-b", []));
+ await runner.runReadWriteTx(async (tx) => {
+ const saved = (await tx.getRefreshGroup(refreshGroupId))!;
+ new RefreshInput(saved, 0).update({
+ refundRequest: permission,
+ reportedMeltCommitment: pending.coinEvHash,
+ });
+ const sibling = new RefreshInput(saved, 1);
+ sibling.update({
+ refundRequest: { ...permission, rtransaction_id: 2 },
+ reportedMeltCommitment: settled.coinEvHash,
+ });
+ sibling.update({ refundRequest: null, reportedMeltCommitment: null });
+ await tx.upsertRefreshGroup(saved);
+ await settleRefreshesForRecoup(
+ wex,
+ tx,
+ settled.coinPub,
+ "recoup-b",
+ true,
+ );
+ });
+ await runner.close();
+ runner = await makeRunner(filename);
+ await runner.runReadWriteTx(async (tx) => {
+ const saved = (await tx.getRefreshGroup(refreshGroupId))!;
+ assert.deepEqual(saved.oldCoinPubs, group.oldCoinPubs);
+ assert.deepEqual(saved.inputPerCoin, group.inputPerCoin);
+ assert.deepEqual(saved.statusPerCoin, [
+ RefreshCoinStatus.Pending,
+ RefreshCoinStatus.Finished,
+ ]);
+ assert.deepEqual(saved.expectedOutputPerCoin, [
+ "TESTKUDOS:7",
+ "TESTKUDOS:0",
+ ]);
+ assert.deepEqual(saved.recoupGroupPerCoin, {
+ 0: "recoup-a",
+ 1: "recoup-b",
+ });
+ assert.deepEqual(saved.refundRequests, { 0: permission });
+ assert.deepEqual(saved.autoRefresh?.reportedMeltCommitments, {
+ 0: pending.coinEvHash,
+ });
+ assert.equal(
+ saved.infoPerExchange?.[pending.exchangeBaseUrl].outputEffective,
+ "TESTKUDOS:7",
+ );
+ const sessions = await tx.getRefreshSessionsByGroup(refreshGroupId);
+ assert.deepEqual(
+ sessions.map((s) => [
+ s.coinIndex,
+ s.sessionPublicSeed,
+ s.amountRefreshOutput,
+ ]),
+ [[0, pending.coinPriv, "TESTKUDOS:7"]],
+ );
+ assert.equal(
+ (await tx.getCoinAvailability(pending))?.pendingRefreshOutputCount,
+ 1,
+ );
+ // A failed recoup releases only the remaining binding, preserving its refund.
+ await settleRefreshesForRecoup(
+ wex,
+ tx,
+ pending.coinPub,
+ "recoup-a",
+ false,
+ );
+ const released = (await tx.getRefreshGroup(refreshGroupId))!;
+ assert.deepEqual(released.recoupGroupPerCoin, { 1: "recoup-b" });
+ assert.deepEqual(released.refundRequests, { 0: permission });
+ });
+ } finally {
+ await runner.close();
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+}
diff --git a/packages/taler-wallet-core/src/refresh-input.ts b/packages/taler-wallet-core/src/refresh-input.ts
@@ -0,0 +1,107 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import {
+ AmountString,
+ checkDbInvariant,
+ ExchangeRefundRequest,
+ HashCodeString,
+} from "@gnu-taler/taler-util";
+import { RefreshCoinStatus, WalletRefreshGroup } from "./db/records.js";
+
+interface RefreshInputUpdate {
+ amount?: AmountString;
+ expectedOutput?: AmountString;
+ status?: RefreshCoinStatus;
+ refundRequest?: ExchangeRefundRequest | null;
+ recoupGroupId?: string | null;
+ reportedMeltCommitment?: HashCodeString | null;
+ recoveryNoticeAmount?: AmountString;
+}
+
+/** A live view of one stored input. Its index also keys its refresh session. */
+export class RefreshInput {
+ constructor(
+ private readonly group: WalletRefreshGroup,
+ readonly index: number,
+ ) {}
+
+ static *all(group: WalletRefreshGroup): IterableIterator<RefreshInput> {
+ for (const index of group.oldCoinPubs.keys())
+ yield new RefreshInput(group, index);
+ }
+
+ get coinPub(): string {
+ return this.group.oldCoinPubs[this.index];
+ }
+ get amount(): AmountString {
+ return this.group.inputPerCoin[this.index];
+ }
+ get expectedOutput(): AmountString {
+ return this.group.expectedOutputPerCoin[this.index];
+ }
+ get status(): RefreshCoinStatus {
+ return this.group.statusPerCoin[this.index];
+ }
+ get refundRequest(): ExchangeRefundRequest | undefined {
+ return this.group.refundRequests?.[this.index];
+ }
+ get recoupGroupId(): string | undefined {
+ return this.group.recoupGroupPerCoin?.[this.index];
+ }
+ get reportedMeltCommitment(): HashCodeString | undefined {
+ return this.group.autoRefresh?.reportedMeltCommitments?.[this.index];
+ }
+
+ /** Mutate only supplied fields. A null optional reference clears only this input. */
+ update(patch: RefreshInputUpdate): void {
+ const { group, index } = this;
+ checkDbInvariant(
+ Number.isInteger(index) && index >= 0 && index < group.oldCoinPubs.length,
+ "invalid refresh input index",
+ );
+ if (patch.amount !== undefined) group.inputPerCoin[index] = patch.amount;
+ if (patch.expectedOutput !== undefined)
+ group.expectedOutputPerCoin[index] = patch.expectedOutput;
+ if (patch.status !== undefined) group.statusPerCoin[index] = patch.status;
+ if (patch.refundRequest === null) delete group.refundRequests?.[index];
+ else if (patch.refundRequest !== undefined)
+ (group.refundRequests ??= {})[index] = patch.refundRequest;
+ if (patch.recoupGroupId === null) delete group.recoupGroupPerCoin?.[index];
+ else if (patch.recoupGroupId !== undefined)
+ (group.recoupGroupPerCoin ??= {})[index] = patch.recoupGroupId;
+ if (patch.reportedMeltCommitment === null)
+ delete group.autoRefresh?.reportedMeltCommitments?.[index];
+ else if (patch.reportedMeltCommitment !== undefined) {
+ const auto = (group.autoRefresh ??= {});
+ (auto.reportedMeltCommitments ??= {})[index] =
+ patch.reportedMeltCommitment;
+ }
+ if (patch.recoveryNoticeAmount !== undefined) {
+ const auto = (group.autoRefresh ??= {});
+ (auto.recoveryInputs ??= {})[index] = patch.recoveryNoticeAmount;
+ }
+ }
+}
+
+/** Only finished inputs contribute to settled refresh output. */
+export function finishedRefreshOutputs(
+ group: WalletRefreshGroup,
+): AmountString[] {
+ return group.expectedOutputPerCoin.filter(
+ (_, i) => new RefreshInput(group, i).status === RefreshCoinStatus.Finished,
+ );
+}
diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts
@@ -14,6 +14,7 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { RefreshInput } from "./refresh-input.js";
import {
checkRefreshAllowed,
getRefreshBlocked,
@@ -582,8 +583,8 @@ async function initRefreshSession(
logger.trace(
`creating refresh session for coin ${coinIndex} in refresh group ${refreshGroupId}`,
);
- const oldCoinPub = refreshGroup.oldCoinPubs[coinIndex];
- const oldCoin = await tx.getCoin(oldCoinPub);
+ const input = new RefreshInput(refreshGroup, coinIndex);
+ const oldCoin = await tx.getCoin(input.coinPub);
if (!oldCoin) {
throw Error("Can't refresh, coin not found");
}
@@ -604,7 +605,7 @@ async function initRefreshSession(
if (!oldRecord) return;
const evaluation = evaluateAutoRefresh({
now: AbsoluteTime.now(),
- inputAmount: refreshGroup.inputPerCoin[coinIndex],
+ inputAmount: input.amount,
oldDenom: oldRecord,
withdrawableDenoms: await tx.getDenominationsByMasterPub(
oldCoin.exchangeMasterPub,
@@ -615,16 +616,12 @@ async function initRefreshSession(
// output. Leave it pending so key/power changes can produce a valid plan.
if (!evaluation.rule || !evaluation.plan) return;
plannedOutput = evaluation.plan;
- refreshGroup.expectedOutputPerCoin[coinIndex] =
- plannedOutput.totalCoinValue;
+ input.update({ expectedOutput: plannedOutput.totalCoinValue });
}
const currency = refreshGroup.currency;
- const availableAmount = Amounts.sub(
- refreshGroup.inputPerCoin[coinIndex],
- oldDenom.feeRefresh,
- ).amount;
+ const availableAmount = Amounts.sub(input.amount, oldDenom.feeRefresh).amount;
const newCoinDenoms =
plannedOutput ??
selectWithdrawalDenominations(
@@ -641,10 +638,10 @@ async function initRefreshSession(
availableAmount,
)} too small`,
);
- refreshGroup.statusPerCoin[coinIndex] = RefreshCoinStatus.Finished;
- refreshGroup.expectedOutputPerCoin[coinIndex] = Amounts.stringify(
- Amounts.zeroOfCurrency(currency),
- );
+ input.update({
+ status: RefreshCoinStatus.Finished,
+ expectedOutput: Amounts.stringify(Amounts.zeroOfCurrency(currency)),
+ });
return;
}
@@ -1071,9 +1068,10 @@ export async function prepareAutoRefreshSession(
): Promise<boolean> {
const rg = await tx.getRefreshGroup(refreshGroupId);
const session = await tx.getRefreshSession(refreshGroupId, coinIndex);
- if (rg?.recoupGroupPerCoin?.[coinIndex]) return false;
+ if (!rg) return true;
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.recoupGroupId) return false;
if (
- !rg ||
!session ||
rg.reason !== RefreshReason.Scheduled ||
session.norevealIndex !== undefined
@@ -1085,7 +1083,7 @@ export async function prepareAutoRefreshSession(
(session.autoRefreshMeltStarted === undefined && session.sessionPublicSeed)
)
return true;
- const coin = await tx.getCoin(rg.oldCoinPubs[coinIndex]);
+ const coin = await tx.getCoin(input.coinPub);
if (!coin || coin.status !== CoinStatus.Dormant) return false;
const history = await tx.getCoinHistory(coin.coinPub);
if (
@@ -1107,7 +1105,7 @@ export async function prepareAutoRefreshSession(
return false;
const evaluation = evaluateAutoRefresh({
now: AbsoluteTime.now(),
- inputAmount: rg.inputPerCoin[coinIndex],
+ inputAmount: input.amount,
oldDenom: old,
withdrawableDenoms: await tx.getDenominationsByMasterPub(
coin.exchangeMasterPub,
@@ -1121,7 +1119,7 @@ export async function prepareAutoRefreshSession(
) {
await destroyRefreshSession(tx, rg, session);
await initRefreshSession(wex, tx, rg, coinIndex, evaluation.plan);
- rg.expectedOutputPerCoin[coinIndex] = evaluation.plan.totalCoinValue;
+ input.update({ expectedOutput: evaluation.plan.totalCoinValue });
if (rg.infoPerExchange)
rg.infoPerExchange[coin.exchangeBaseUrl] = {
outputEffective: Amounts.stringify(
@@ -1155,7 +1153,8 @@ async function authorizeScheduledMelt(
if (session.autoRefreshMeltStarted ?? !!session.sessionPublicSeed)
return "retry";
if (!hasAllocation) return;
- const coin = await tx.getCoin(rg.oldCoinPubs[coinIndex]);
+ const input = new RefreshInput(rg, coinIndex);
+ const coin = await tx.getCoin(input.coinPub);
if (!coin || coin.status !== CoinStatus.Dormant) return;
const old = await tx.getDenomination(coin);
if (!old) return;
@@ -1165,7 +1164,7 @@ async function authorizeScheduledMelt(
const now = AbsoluteTime.now();
const evaluation = evaluateAutoRefresh({
now,
- inputAmount: rg.inputPerCoin[coinIndex],
+ inputAmount: input.amount,
oldDenom: old,
withdrawableDenoms: await tx.getDenominationsByMasterPub(
coin.exchangeMasterPub,
@@ -1185,8 +1184,7 @@ async function authorizeScheduledMelt(
const plan = evaluation.plan;
rg.autoRefresh ??= {};
const previous = rg.autoRefresh.recovery;
- const recoveryInputs = (rg.autoRefresh.recoveryInputs ??= {});
- recoveryInputs[coinIndex] = rg.inputPerCoin[coinIndex];
+ input.update({ recoveryNoticeAmount: input.amount });
rg.autoRefresh.recovery = {
warningId: rg.refreshGroupId,
exchangeBaseUrl: coin.exchangeBaseUrl,
@@ -1194,7 +1192,7 @@ async function authorizeScheduledMelt(
amount: Amounts.stringify(
Amounts.add(
Amounts.zeroOfCurrency(rg.currency),
- ...Object.values(recoveryInputs),
+ ...Object.values(rg.autoRefresh.recoveryInputs ?? {}),
).amount,
),
oldDepositExpiration: timestampProtocolFromDb(old.stampExpireDeposit),
@@ -1405,10 +1403,9 @@ async function refreshMelt(
const submission = await wex.runWalletDbTx(async (tx) => {
// Recoup can claim or finish this input while the melt waits for the lock.
const rg = await tx.getRefreshGroup(refreshGroupId);
- if (
- rg?.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending ||
- rg.recoupGroupPerCoin?.[coinIndex]
- )
+ if (!rg) return;
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending || input.recoupGroupId)
return;
if ((await tx.getConfig(ConfigRecordKey.RefreshBlocked))?.value)
throw new RefreshBlockedError();
@@ -1448,8 +1445,7 @@ async function refreshMelt(
return {
attempt,
pin,
- reportedMelt:
- rg.autoRefresh?.reportedMeltCommitments?.[coinIndex] === derived.hash,
+ reportedMelt: input.reportedMeltCommitment === derived.hash,
};
});
if (!submission) return false;
@@ -1540,13 +1536,14 @@ async function refreshMelt(
await wex.runWalletDbTx(async (tx) => {
const rg = await tx.getRefreshGroup(refreshGroupId);
const rs = await tx.getRefreshSession(refreshGroupId, coinIndex);
+ if (!rg) return;
+ const input = new RefreshInput(rg, coinIndex);
if (
- rg?.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending ||
+ input.status !== RefreshCoinStatus.Pending ||
rs?.sessionPublicSeed !== refreshSession.sessionPublicSeed
)
return;
- const state = (rg.autoRefresh ??= {});
- (state.reportedMeltCommitments ??= {})[coinIndex] = derived.hash;
+ input.update({ reportedMeltCommitment: derived.hash });
await tx.upsertRefreshGroup(rg);
});
throwUnexpectedRequestError(resp.response, resp.detail!);
@@ -1570,7 +1567,8 @@ async function refreshMelt(
if (rg.timestampFinished) {
return false;
}
- if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) {
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending) {
return false;
}
const rs = await tx.getRefreshSession(refreshGroupId, coinIndex);
@@ -1582,7 +1580,7 @@ async function refreshMelt(
}
rs.norevealIndex = norevealIndex;
await tx.upsertRefreshSession(rs);
- await wakePurseResiduals(wex, tx, rg, [rg.oldCoinPubs[coinIndex]]);
+ await wakePurseResiduals(wex, tx, rg, [input.coinPub]);
return true;
});
}
@@ -1647,10 +1645,11 @@ async function handleRefreshMeltGone(
if (rg.timestampFinished) {
return;
}
- if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) {
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending) {
return;
}
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.PendingRedenominate;
+ input.update({ status: RefreshCoinStatus.PendingRedenominate });
const refreshSession = await tx.getRefreshSession(
ctx.refreshGroupId,
coinIndex,
@@ -1672,8 +1671,8 @@ async function reconcileRefreshRefund(
group: WalletRefreshGroup,
coinIndex: number,
coin: WalletCoin,
+ request: ExchangeRefundRequest,
): Promise<"refunded" | "refused" | "retry"> {
- const request = group.refundRequests[coinIndex];
await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl);
const response = await walletExchangeClient(
coin.exchangeBaseUrl,
@@ -1709,11 +1708,10 @@ async function reconcileRefreshRefund(
}
await wex.runWalletDbTx(async (tx) => {
const current = await tx.getRefreshGroup(group.refreshGroupId);
- if (
- current &&
- current.refundRequests[coinIndex]?.merchant_sig === request.merchant_sig
- ) {
- delete current.refundRequests[coinIndex];
+ if (!current) return;
+ const input = new RefreshInput(current, coinIndex);
+ if (input.refundRequest?.merchant_sig === request.merchant_sig) {
+ input.update({ refundRequest: null });
await tx.upsertRefreshGroup(current);
}
});
@@ -1737,12 +1735,14 @@ export async function handleRefreshMeltConflict(
)} failed in refresh group ${ctx.refreshGroupId} due to conflict`,
);
- if (refreshGroup.refundRequests[coinIndex]) {
+ const request = new RefreshInput(refreshGroup, coinIndex).refundRequest;
+ if (request) {
const result = await reconcileRefreshRefund(
ctx.wex,
refreshGroup,
coinIndex,
oldCoin,
+ request,
);
if (result !== "refused") return;
}
@@ -1768,7 +1768,8 @@ export async function handleRefreshMeltConflict(
if (rg.timestampFinished) {
return;
}
- if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) {
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending) {
return;
}
await recordConflictingCoinHistory(
@@ -1789,10 +1790,8 @@ export async function handleRefreshMeltConflict(
const info = rg.infoPerExchange?.[oldCoin.exchangeBaseUrl];
if (info)
info.outputEffective = Amounts.stringify(
- Amounts.sub(info.outputEffective, rg.expectedOutputPerCoin[coinIndex])
- .amount,
+ Amounts.sub(info.outputEffective, input.expectedOutput).amount,
);
- rg.expectedOutputPerCoin[coinIndex] = correctedBalance;
if (rg.reason === RefreshReason.AbortPay) {
// A coin selected for a partially completed payment can legitimately
// have no balance left: the merchant deposited it before the wallet
@@ -1801,14 +1800,20 @@ export async function handleRefreshMeltConflict(
// coin has no output and is complete rather than failed.
await destroyRefreshSession(tx, rg, refreshSession);
await tx.deleteRefreshSession(ctx.refreshGroupId, coinIndex);
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Finished;
+ input.update({
+ status: RefreshCoinStatus.Finished,
+ expectedOutput: correctedBalance,
+ });
await h.update(rg, "melt-conflict-abort-pay-spent");
} else {
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Failed;
+ input.update({
+ status: RefreshCoinStatus.Failed,
+ expectedOutput: correctedBalance,
+ });
rg.failReason = addPermanentCoinFailure(
rg.failReason,
TalerErrorCode.WALLET_REFRESH_GROUP_FAILED,
- rg.oldCoinPubs[coinIndex],
+ input.coinPub,
errDetails,
);
refreshSession.lastError = errDetails;
@@ -1818,7 +1823,6 @@ export async function handleRefreshMeltConflict(
}
} else {
// Try again with new denoms!
- rg.inputPerCoin[coinIndex] = correctedBalance;
const refreshSession = await tx.getRefreshSession(
ctx.refreshGroupId,
coinIndex,
@@ -1834,17 +1838,18 @@ export async function handleRefreshMeltConflict(
rg.currency,
[{ coinPub: oldCoin.coinPub, amount: correctedBalance }],
);
- const previousOutput = rg.expectedOutputPerCoin[coinIndex];
- rg.expectedOutputPerCoin[coinIndex] = Amounts.stringify(
- correctedOutput.outputPerCoin[0],
- );
+ const previousOutput = input.expectedOutput;
+ input.update({
+ amount: correctedBalance,
+ expectedOutput: Amounts.stringify(correctedOutput.outputPerCoin[0]),
+ });
await initRefreshSession(ctx.wex, tx, rg, coinIndex);
const info = rg.infoPerExchange?.[oldCoin.exchangeBaseUrl];
if (info) {
info.outputEffective = Amounts.stringify(
Amounts.add(
Amounts.sub(info.outputEffective, previousOutput).amount,
- rg.expectedOutputPerCoin[coinIndex],
+ input.expectedOutput,
).amount,
);
}
@@ -1881,12 +1886,14 @@ async function wakePurseResiduals(
)) {
if (
group.operationStatus !== RefreshOperationStatus.Pending ||
- !group.oldCoinPubs.some(
- (pub, i) =>
+ !group.oldCoinPubs.some((pub, i) => {
+ const input = new RefreshInput(group, i);
+ return (
settled.has(pub) &&
- isAwaitingPurseBalance(group.statusPerCoin[i]) &&
- !group.recoupGroupPerCoin?.[i],
- )
+ isAwaitingPurseBalance(input.status) &&
+ !input.recoupGroupId
+ );
+ })
)
continue;
const { taskId } = new RefreshTransactionContext(wex, group.refreshGroupId);
@@ -1905,15 +1912,18 @@ export async function getUnconfirmedPurseChangeCoins(
transactionId,
)) {
if (!isPurseChange(group)) continue;
- for (const [i, pub] of group.oldCoinPubs.entries()) {
+ for (const input of RefreshInput.all(group)) {
if (
- !coinPubs.has(pub) ||
- (group.statusPerCoin[i] !== RefreshCoinStatus.Pending &&
- group.statusPerCoin[i] !== RefreshCoinStatus.PendingRedenominate)
+ !coinPubs.has(input.coinPub) ||
+ (input.status !== RefreshCoinStatus.Pending &&
+ input.status !== RefreshCoinStatus.PendingRedenominate)
)
continue;
- const session = await tx.getRefreshSession(group.refreshGroupId, i);
- if (session?.norevealIndex == null) pending.add(pub);
+ const session = await tx.getRefreshSession(
+ group.refreshGroupId,
+ input.index,
+ );
+ if (session?.norevealIndex == null) pending.add(input.coinPub);
}
}
return pending;
@@ -1942,14 +1952,15 @@ async function handleRefreshMeltNotFound(
if (rg.timestampFinished) {
return;
}
- if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) {
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending) {
return;
}
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Failed;
+ input.update({ status: RefreshCoinStatus.Failed });
rg.failReason = addPermanentCoinFailure(
rg.failReason,
TalerErrorCode.WALLET_REFRESH_GROUP_FAILED,
- rg.oldCoinPubs[coinIndex],
+ input.coinPub,
errDetails,
);
const refreshSession = await tx.getRefreshSession(
@@ -2158,7 +2169,7 @@ async function refreshReveal(
coinIndex: newCoinIndex,
envelopeHashes: planchets[norevealIndex].map((p) => p.coinEvHash),
},
- oldCoinPub: refreshGroup.oldCoinPubs[coinIndex],
+ oldCoinPub: oldCoin.coinPub,
nonce:
pc.coinEv.cipher === DenomKeyType.ClauseSchnorr
? pc.coinEv.cs_nonce
@@ -2180,16 +2191,19 @@ async function refreshReveal(
logger.warn("no refresh session found");
return;
}
- if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) {
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending) {
return;
}
const rs = await tx.getRefreshSession(refreshGroupId, coinIndex);
if (!rs) {
return;
}
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Finished;
// Once issued, retain the actual session output for final accounting.
- rg.expectedOutputPerCoin[coinIndex] = rs.amountRefreshOutput;
+ input.update({
+ status: RefreshCoinStatus.Finished,
+ expectedOutput: rs.amountRefreshOutput,
+ });
const existingCoins = await tx.getCoinsByPubs(
coins.map((coin) => coin.coinPub),
);
@@ -2237,14 +2251,15 @@ export async function handleRefreshRevealError(
if (rg.timestampFinished) {
return;
}
- if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) {
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.status !== RefreshCoinStatus.Pending) {
return;
}
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Failed;
+ input.update({ status: RefreshCoinStatus.Failed });
rg.failReason = addPermanentCoinFailure(
rg.failReason,
TalerErrorCode.WALLET_REFRESH_GROUP_FAILED,
- rg.oldCoinPubs[coinIndex],
+ input.coinPub,
errDetails,
);
const refreshSession = await tx.getRefreshSession(
@@ -2297,14 +2312,9 @@ export async function processRefreshGroup(
// If any redenomination is pending, first make sure the
// info about exchanges is recent enough.
{
- let shouldReloadExchanges = false;
- for (let i = 0; i < refreshGroup.statusPerCoin.length; i++) {
- if (
- refreshGroup.statusPerCoin[i] === RefreshCoinStatus.PendingRedenominate
- ) {
- shouldReloadExchanges = true;
- }
- }
+ const shouldReloadExchanges = refreshGroup.statusPerCoin.includes(
+ RefreshCoinStatus.PendingRedenominate,
+ );
if (shouldReloadExchanges && refreshGroup.infoPerExchange != null) {
for (const e of Object.keys(refreshGroup.infoPerExchange)) {
@@ -2365,8 +2375,8 @@ export async function processRefreshGroup(
if (isPurseChange(rg)) {
const settled = rg.oldCoinPubs.filter(
(_, i) =>
- isPendingRefreshCoin(refreshGroup.statusPerCoin[i]) &&
- !isPendingRefreshCoin(rg.statusPerCoin[i]),
+ isPendingRefreshCoin(new RefreshInput(refreshGroup, i).status) &&
+ !isPendingRefreshCoin(new RefreshInput(rg, i).status),
);
await wakePurseResiduals(wex, tx, rg, settled);
}
@@ -2466,7 +2476,10 @@ export async function bindRefreshesToRecoup(
}[] = [];
for (const group of await tx.listAllRefreshGroups()) {
const index = group.oldCoinPubs.indexOf(coin.coinPub);
- if (index < 0 || !isPendingRefreshCoin(group.statusPerCoin[index]))
+ if (
+ index < 0 ||
+ !isPendingRefreshCoin(new RefreshInput(group, index).status)
+ )
continue;
const session = await tx.getRefreshSession(group.refreshGroupId, index);
result.push({ group, index, session });
@@ -2475,12 +2488,15 @@ export async function bindRefreshesToRecoup(
});
const unaccepted: typeof candidates = [];
for (const candidate of candidates) {
- if (candidate.group.refundRequests?.[candidate.index]) {
+ const refundRequest = new RefreshInput(candidate.group, candidate.index)
+ .refundRequest;
+ if (refundRequest) {
const result = await reconcileRefreshRefund(
wex,
candidate.group,
candidate.index,
coin,
+ refundRequest,
);
// A granted refund changes the residual. Read a fresh history next time.
if (result !== "refused") return false;
@@ -2532,15 +2548,15 @@ export async function bindRefreshesToRecoup(
for (const { group, index } of unaccepted) {
const current = await tx.getRefreshGroup(group.refreshGroupId);
const rs = await tx.getRefreshSession(group.refreshGroupId, index);
+ if (!current || rs?.norevealIndex != null) continue;
+ const input = new RefreshInput(current, index);
if (
- !current ||
- (current.recoupGroupPerCoin?.[index] !== undefined &&
- current.recoupGroupPerCoin[index] !== recoupGroupId) ||
- rs?.norevealIndex != null ||
- !isPendingRefreshCoin(current.statusPerCoin[index])
+ (input.recoupGroupId !== undefined &&
+ input.recoupGroupId !== recoupGroupId) ||
+ !isPendingRefreshCoin(input.status)
)
continue;
- (current.recoupGroupPerCoin ??= {})[index] = recoupGroupId;
+ input.update({ recoupGroupId });
await tx.upsertRefreshGroup(current);
}
});
@@ -2557,16 +2573,21 @@ export async function settleRefreshesForRecoup(
): Promise<void> {
for (const group of await tx.listAllRefreshGroups()) {
const index = group.oldCoinPubs.indexOf(coinPub);
- if (index < 0 || group.recoupGroupPerCoin?.[index] !== recoupGroupId)
+ if (index < 0) continue;
+ const bound = new RefreshInput(group, index);
+ if (
+ bound.recoupGroupId !== recoupGroupId ||
+ !isPendingRefreshCoin(bound.status)
+ )
continue;
- if (!isPendingRefreshCoin(group.statusPerCoin[index])) continue;
const ctx = new RefreshTransactionContext(wex, group.refreshGroupId);
const [current, handle] = await ctx.getRecordHandle(tx);
checkDbInvariant(!!current, "refresh disappeared during recoup");
- if (!recovered || current.refundRequests?.[index]) {
+ const input = new RefreshInput(current, index);
+ if (!recovered || input.refundRequest) {
// Older wallets could have posted recoup with a refund still in flight.
// Keep the refresh and its durable merchant permission actionable.
- delete current.recoupGroupPerCoin![index];
+ input.update({ recoupGroupId: null });
} else {
const session = await tx.getRefreshSession(group.refreshGroupId, index);
checkDbInvariant(
@@ -2577,20 +2598,20 @@ export async function settleRefreshesForRecoup(
await destroyRefreshSession(tx, current, session);
await tx.deleteRefreshSession(group.refreshGroupId, index);
}
- const output = current.expectedOutputPerCoin[index];
- current.expectedOutputPerCoin[index] = Amounts.stringify(
- Amounts.zeroOfAmount(output),
- );
+ const output = input.expectedOutput;
+ input.update({
+ expectedOutput: Amounts.stringify(Amounts.zeroOfAmount(output)),
+ status: RefreshCoinStatus.Finished,
+ });
const coin = await tx.getCoin(coinPub);
const info = coin && current.infoPerExchange?.[coin.exchangeBaseUrl];
if (info)
info.outputEffective = Amounts.stringify(
Amounts.sub(info.outputEffective, output).amount,
);
- current.statusPerCoin[index] = RefreshCoinStatus.Finished;
}
await handle.update(current, "recoup-refresh-input");
- if (!isPendingRefreshCoin(current.statusPerCoin[index]))
+ if (!isPendingRefreshCoin(input.status))
await wakePurseResiduals(wex, tx, current, [coinPub]);
}
}
@@ -2600,7 +2621,7 @@ async function preparePurseResidualRefresh(
group: WalletRefreshGroup,
coinIndex: number,
): Promise<WalletRefreshSession | undefined> {
- const coinPub = group.oldCoinPubs[coinIndex];
+ const { coinPub, status } = new RefreshInput(group, coinIndex);
const parent = group.originatingTransactionId;
checkDbInvariant(
!!parent,
@@ -2621,7 +2642,6 @@ async function preparePurseResidualRefresh(
});
if (!input) return;
const response = await readVerifiedCoinHistory(wex, input.coin, input.denom);
- const status = group.statusPerCoin[coinIndex];
if (
response.case !== "ok" &&
status === RefreshCoinStatus.PendingPurseBalance
@@ -2636,13 +2656,9 @@ async function preparePurseResidualRefresh(
return wex.runWalletDbTx(async (tx) => {
const ctx = new RefreshTransactionContext(wex, group.refreshGroupId);
const [rg, handle] = await ctx.getRecordHandle(tx);
- if (
- rg?.operationStatus !== RefreshOperationStatus.Pending ||
- rg.recoupGroupPerCoin?.[coinIndex] ||
- rg.statusPerCoin[coinIndex] !== status
- )
- return;
- rg.inputPerCoin[coinIndex] = balance;
+ if (rg?.operationStatus !== RefreshOperationStatus.Pending) return;
+ const residual = new RefreshInput(rg, coinIndex);
+ if (residual.recoupGroupId || residual.status !== status) return;
const coinHistory = await tx.getCoinHistory(coinPub);
const allocation = coinHistory?.history.find(
(h) => h.type === "refresh" && h.transactionId === ctx.transactionId,
@@ -2653,10 +2669,10 @@ async function preparePurseResidualRefresh(
);
allocation.amount = balance;
await tx.upsertCoinHistory(coinHistory);
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Pending;
+ residual.update({ amount: balance, status: RefreshCoinStatus.Pending });
const session = await initRefreshSession(wex, tx, rg, coinIndex);
if (session) {
- rg.expectedOutputPerCoin[coinIndex] = session.amountRefreshOutput;
+ residual.update({ expectedOutput: session.amountRefreshOutput });
const info = rg.infoPerExchange?.[input.coin.exchangeBaseUrl];
checkDbInvariant(!!info, "missing purse recovery exchange");
info.outputEffective = Amounts.stringify(
@@ -2679,25 +2695,23 @@ async function processRefreshSession(
let { refreshGroup, refreshSession } = await wex.runWalletDbTx(async (tx) => {
const rg = await tx.getRefreshGroup(refreshGroupId);
let rs = await tx.getRefreshSession(refreshGroupId, coinIndex);
- if (rg?.recoupGroupPerCoin?.[coinIndex])
+ if (!rg) return { refreshGroup: rg, refreshSession: rs };
+ const input = new RefreshInput(rg, coinIndex);
+ if (input.recoupGroupId)
return { refreshGroup: rg, refreshSession: undefined };
if (
- rg &&
rs &&
- rg.statusPerCoin[coinIndex] === RefreshCoinStatus.PendingRedenominate &&
+ input.status === RefreshCoinStatus.PendingRedenominate &&
(rs.norevealIndex !== undefined ||
(rg.reason === RefreshReason.Scheduled && rs.autoRefreshMeltStarted))
) {
// A commitment that might have been accepted must survive key expiry or
// a contradictory later response. Continue its existing melt/reveal.
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Pending;
+ input.update({ status: RefreshCoinStatus.Pending });
await tx.upsertRefreshGroup(rg);
}
- if (
- rg != null &&
- rg.statusPerCoin[coinIndex] === RefreshCoinStatus.PendingRedenominate
- ) {
+ if (input.status === RefreshCoinStatus.PendingRedenominate) {
if (rs != null) {
await destroyRefreshSession(tx, rg, rs);
}
@@ -2705,7 +2719,7 @@ async function processRefreshSession(
// Set the status before initializing the session, as the
// initialization marks the coin as finished when the remaining
// amount is too small to be refreshed at all.
- rg.statusPerCoin[coinIndex] = RefreshCoinStatus.Pending;
+ input.update({ status: RefreshCoinStatus.Pending });
await initRefreshSession(wex, tx, rg, coinIndex);
await tx.upsertRefreshGroup(rg);
// The old session has been replaced, don't act on it anymore.
@@ -2713,9 +2727,9 @@ async function processRefreshSession(
}
if (
- rg?.reason === RefreshReason.Scheduled &&
+ rg.reason === RefreshReason.Scheduled &&
!rs &&
- rg.statusPerCoin[coinIndex] === RefreshCoinStatus.Pending
+ input.status === RefreshCoinStatus.Pending
) {
await initRefreshSession(wex, tx, rg, coinIndex);
await tx.upsertRefreshGroup(rg);
@@ -2727,18 +2741,16 @@ async function processRefreshSession(
refreshSession: rs,
};
});
- if (!refreshGroup || refreshGroup.recoupGroupPerCoin?.[coinIndex]) {
- return;
- }
- if (isAwaitingPurseBalance(refreshGroup.statusPerCoin[coinIndex])) {
+ if (!refreshGroup) return;
+ const input = new RefreshInput(refreshGroup, coinIndex);
+ if (input.recoupGroupId) return;
+ if (isAwaitingPurseBalance(input.status)) {
refreshSession = await preparePurseResidualRefresh(
wex,
refreshGroup,
coinIndex,
);
- } else if (
- refreshGroup.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending
- ) {
+ } else if (input.status !== RefreshCoinStatus.Pending) {
// Finished, or failed for good. A failed coin keeps its session
// record, but melting it again would only hand the exchange a coin
// whose fresh coins the wallet no longer stores.
@@ -3050,15 +3062,6 @@ export async function createRefreshGroup(
await applyRefreshToOldCoins(tx, loadedCoins, refreshGroupId);
- const refundRequests: { [n: number]: ExchangeRefundRequest } = {};
-
- for (let i = 0; i < oldCoinPubs.length; i++) {
- const req = oldCoinPubs[i].refundRequest;
- if (req != null) {
- refundRequests[i] = req;
- }
- }
-
const refreshGroup: WalletRefreshGroup = {
...(refreshReason === RefreshReason.Scheduled ? { autoRefresh: {} } : {}),
operationStatus: RefreshOperationStatus.Pending,
@@ -3075,7 +3078,7 @@ export async function createRefreshGroup(
expectedOutputPerCoin: estimatedOutputPerCoin.map((x) =>
Amounts.stringify(x),
),
- refundRequests,
+ refundRequests: {},
infoPerExchange: outInfo.perExchangeInfo,
timestampCreated: timestampPreciseToDb(TalerPreciseTimestamp.now()),
};
@@ -3088,14 +3091,18 @@ export async function createRefreshGroup(
refreshGroup.operationStatus = RefreshOperationStatus.Finished;
}
- for (let i = 0; i < oldCoinPubs.length; i++) {
- if (oldCoinPubs[i].awaitPurseChange) continue;
+ for (const [i, request] of oldCoinPubs.entries()) {
+ if (request.refundRequest)
+ new RefreshInput(refreshGroup, i).update({
+ refundRequest: request.refundRequest,
+ });
+ if (request.awaitPurseChange) continue;
await initRefreshSession(
wex,
tx,
refreshGroup,
i,
- plannedOutputs?.get(oldCoinPubs[i].coinPub),
+ plannedOutputs?.get(request.coinPub),
);
}
@@ -3152,11 +3159,8 @@ async function redenominateRefresh(
return TaskRunResult.finished();
}
const inputs: CoinRefreshRequest[] = [];
- for (let i = 0; i < refreshGroup.oldCoinPubs.length; i++) {
- inputs.push({
- amount: refreshGroup.inputPerCoin[i],
- coinPub: refreshGroup.oldCoinPubs[i],
- });
+ for (const { coinPub, amount } of RefreshInput.all(refreshGroup)) {
+ inputs.push({ coinPub, amount });
}
const outInfo = await calculateRefreshOutput(
@@ -3172,18 +3176,19 @@ async function redenominateRefresh(
);
logger.info(`new out info: ${j2s(outInfo)}`);
- for (let i = 0; i < refreshGroup.oldCoinPubs.length; i++) {
+ for (const input of RefreshInput.all(refreshGroup)) {
+ const output = outInfo.outputPerCoin[input.index];
if (
- !refreshGroup.recoupGroupPerCoin?.[i] &&
- Amounts.isZero(refreshGroup.expectedOutputPerCoin[i]) &&
- Amounts.isNonZero(outInfo.outputPerCoin[i]) &&
- refreshGroup.statusPerCoin[i] === RefreshCoinStatus.Finished
+ !input.recoupGroupId &&
+ Amounts.isZero(input.expectedOutput) &&
+ Amounts.isNonZero(output) &&
+ input.status === RefreshCoinStatus.Finished
) {
- refreshGroup.expectedOutputPerCoin[i] = Amounts.stringify(
- outInfo.outputPerCoin[i],
- );
- refreshGroup.statusPerCoin[i] = RefreshCoinStatus.Pending;
- await initRefreshSession(wex, tx, refreshGroup, i);
+ input.update({
+ expectedOutput: Amounts.stringify(output),
+ status: RefreshCoinStatus.Pending,
+ });
+ await initRefreshSession(wex, tx, refreshGroup, input.index);
}
}
diff --git a/packages/taler-wallet-core/src/refreshBalance.ts b/packages/taler-wallet-core/src/refreshBalance.ts
@@ -12,6 +12,7 @@
see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { RefreshInput } from "./refresh-input.js";
import {
AbsoluteTime,
BalancesResponse,
@@ -96,10 +97,10 @@ async function loadRefreshBalanceSnapshot(
);
const pendingCurrencies = new Map<string, string>();
for (const group of pending) {
- group.oldCoinPubs.forEach((pub, i) => {
- if (group.statusPerCoin[i] !== RefreshCoinStatus.Finished)
- pendingCurrencies.set(pub, group.currency);
- });
+ for (const input of RefreshInput.all(group)) {
+ if (input.status !== RefreshCoinStatus.Finished)
+ pendingCurrencies.set(input.coinPub, group.currency);
+ }
}
const allCoins = await tx.getCoinsByPubs([...pendingCurrencies.keys()]);
const resolver = await BalanceScopeResolver.load(tx);
@@ -270,13 +271,13 @@ export async function processRefreshBalance(
const pending = new Set<string>();
for (const g of await tx.listAllRefreshGroups()) {
if (g.operationStatus === RefreshOperationStatus.Finished) continue;
- g.oldCoinPubs.forEach((pub, i) => {
+ for (const input of RefreshInput.all(g)) {
if (
- g.statusPerCoin[i] !== RefreshCoinStatus.Finished &&
- !Amounts.isZero(g.inputPerCoin[i])
+ input.status !== RefreshCoinStatus.Finished &&
+ !Amounts.isZero(input.amount)
)
- pending.add(pub);
- });
+ pending.add(input.coinPub);
+ }
}
const coins = await tx.getCoinsByPubs([...pending]);
const denoms = await tx.getDenominationsByRefs([...available, ...coins]);
diff --git a/packages/taler-wallet-core/src/transaction-amounts.ts b/packages/taler-wallet-core/src/transaction-amounts.ts
@@ -4,6 +4,7 @@
SPDX-License-Identifier: GPL-3.0-or-later
*/
+import { finishedRefreshOutputs } from "./refresh-input.js";
import {
Amounts,
AmountString,
@@ -18,7 +19,6 @@ import { WalletDbTransaction } from "./db/transaction.js";
import {
OPERATION_STATUS_DONE_FIRST,
OPERATION_STATUS_DONE_LAST,
- RefreshCoinStatus,
PurchaseStatus,
RefundReason,
WalletRefreshGroup,
@@ -208,12 +208,7 @@ export function settledRefreshOutput(
): AmountString | undefined {
if (!terminal(r.operationStatus)) return;
if (r.statusPerCoin.length !== r.expectedOutputPerCoin.length) return;
- return sum(
- r.currency,
- r.expectedOutputPerCoin.filter(
- (_, i) => r.statusPerCoin[i] === RefreshCoinStatus.Finished,
- ),
- );
+ return sum(r.currency, finishedRefreshOutputs(r));
}
/**