commit 5a163b8eaa1023ff0a4f9fe36054022b9ed73bf3
parent 98a3a1c2ab7d6ba246df62c81cbdb0e7d4d39f9e
Author: Florian Dold <dold@taler.net>
Date: Tue, 17 Nov 2026 19:00:09 +0100
wallet recoup: recover the unspent value of revoked coins
Check signed coin history for previous recoups and accepted melts.
Submit pending refunds before recoup. Use the confirmed credit to
withdraw from the source reserve or refresh the parent coin.
Diffstat:
14 files changed, 2239 insertions(+), 321 deletions(-)
diff --git a/packages/taler-harness/src/harness/faultInjection.ts b/packages/taler-harness/src/harness/faultInjection.ts
@@ -144,6 +144,9 @@ export class FaultProxy {
}'`,
);
+ // Long polls can still be open when test services are stopped.
+ // Propagate a disconnected upstream instead of crashing the worker.
+ proxyRequest.on("error", () => res.destroy());
if (faultReqContext.requestBody) {
proxyRequest.write(faultReqContext.requestBody);
}
diff --git a/packages/taler-harness/src/integrationtests/test-denom-revoked-balance.ts b/packages/taler-harness/src/integrationtests/test-denom-revoked-balance.ts
@@ -37,7 +37,7 @@ import {
createSimpleTestkudosEnvironmentV3,
withdrawViaBankV4,
} from "../harness/environments.js";
-import { GlobalTestState } from "../harness/harness.js";
+import { GlobalTestState, delayMs } from "../harness/harness.js";
const logger = new Logger("test-denom-revoked-balance");
@@ -60,24 +60,45 @@ export async function runDenomRevokedBalanceTest(t: GlobalTestState) {
messages: [
[/^denomination [A-Z0-9]+ is a loss$/, 1],
[
- /^processRecoup failed: TalerError: \{"code":7005,.*"requestUrl":"http:\/\/localhost:8081\/coins\/[A-Z0-9]+\/recoup".*"httpStatusCode":404,.*"code":1001,.*"detail":"recoup"\}\}$/,
- 1,
+ /^processRecoup failed: TalerError: .*recoup-withdraw.*"httpStatusCode":503.*$/,
+ 20,
],
],
justification:
- "the test revokes one denomination and exercises the currently disabled recoup endpoint (exchange FIXME 9828), then verifies the resulting lost balance",
+ "the test revokes one denomination and pauses recoup while verifying that the revoked coins cannot be spent",
});
- const { bank, walletClient, exchange } =
+ const { bank, walletClient, exchange, faultyExchange } =
await createSimpleTestkudosEnvironmentV3(
t,
makeNoFeeCoinConfig("TESTKUDOS"),
+ { faultInjection: true },
);
+ let blockRecoup = true;
+ faultyExchange.faultProxy.addFault({
+ async modifyRequest(ctx) {
+ if (
+ blockRecoup &&
+ new URL(ctx.requestUrl).pathname === "/recoup-withdraw"
+ ) {
+ ctx.dropRequest = true;
+ ctx.substituteResponseStatusCode = 503;
+ ctx.substituteResponseHeaders = { "content-type": "application/json" };
+ ctx.substituteResponseBody = Buffer.from(
+ JSON.stringify({
+ code: TalerErrorCode.GENERIC_INTERNAL_INVARIANT_FAILURE,
+ hint: "recoup paused for coin selection test",
+ }),
+ );
+ }
+ },
+ });
+
const wres = await withdrawViaBankV4(t, {
walletClient,
bank,
- exchange,
+ exchange: faultyExchange,
amount: initialAmount,
});
await wres.withdrawalFinishedCond;
@@ -148,11 +169,11 @@ export async function runDenomRevokedBalanceTest(t: GlobalTestState) {
// Make the wallet notice the revocation. UpdateExchangeEntry only kicks
// off the update task, so wait for it to actually run.
await walletClient.call(WalletApiOperation.UpdateExchangeEntry, {
- exchangeBaseUrl: exchange.baseUrl,
+ exchangeBaseUrl: faultyExchange.baseUrl,
force: true,
});
await walletClient.call(WalletApiOperation.TestingWaitExchangeReady, {
- exchangeBaseUrl: exchange.baseUrl,
+ exchangeBaseUrl: faultyExchange.baseUrl,
forceUpdate: true,
});
@@ -261,6 +282,18 @@ export async function runDenomRevokedBalanceTest(t: GlobalTestState) {
}
t.assertDeepEqual(coin.coinStatus, CoinStatus.DenomLoss);
}
+
+ blockRecoup = false;
+ let recovered = false;
+ for (let i = 0; i < 200; i++) {
+ if (Amounts.cmp(await getAvailableBalance(), revokedAmount) === 0) {
+ recovered = true;
+ break;
+ }
+ await delayMs(50);
+ }
+ t.assertTrue(recovered);
+ t.assertTrue(!(await getFreshCoinsByDenom()).has(revokedDenomPubHash));
}
runDenomRevokedBalanceTest.suites = ["wallet"];
diff --git a/packages/taler-harness/src/integrationtests/test-revocation.ts b/packages/taler-harness/src/integrationtests/test-revocation.ts
@@ -47,6 +47,7 @@ async function revokeAllWalletCoins(req: {
walletClient: WalletClient;
exchange: ExchangeService;
merchant: MerchantService;
+ round: number;
}): Promise<void> {
const { walletClient, exchange, merchant } = req;
const coinDump = await walletClient.call(WalletApiOperation.DumpCoins, {});
@@ -62,6 +63,10 @@ async function revokeAllWalletCoins(req: {
await exchange.keyup();
await delayMs(1000);
await merchant.stop();
+ // The key updater limits downloads to one per five minutes. Move only
+ // the merchant's test clock so it can discover the replacement keys.
+ merchant.setTimetravel(req.round * 6 * 60 * 1000);
+ await merchant.runExchangekeyupdateOnce();
await merchant.start();
await merchant.pingUntilAvailable();
}
@@ -168,6 +173,7 @@ async function createTestEnvironment(
t,
{
name: "default",
+ config: { testing: { devModeActive: true } },
},
);
@@ -190,6 +196,13 @@ async function createTestEnvironment(
* Test wallet recoup after revoking freshly withdrawn and refreshed coins.
*/
export async function runRevocationTest(t: GlobalTestState) {
+ t.allowLogs({
+ file: "wallet-default-stderr.log",
+ level: "WARNING",
+ messages: [[/^denomination [A-Z0-9]+ is a loss$/, 4]],
+ justification:
+ "the test intentionally revokes four generations of denomination keys",
+ });
// Set up test environment
const { bank, walletClient, exchange, merchant, merchantAdminAccessToken } =
@@ -206,7 +219,7 @@ export async function runRevocationTest(t: GlobalTestState) {
await wres.withdrawalFinishedCond;
console.log("revoking first time");
- await revokeAllWalletCoins({ walletClient, exchange, merchant });
+ await revokeAllWalletCoins({ walletClient, exchange, merchant, round: 1 });
// FIXME: this shouldn't be necessary once https://bugs.taler.net/n/6565
// is implemented.
@@ -214,9 +227,13 @@ export async function runRevocationTest(t: GlobalTestState) {
exchangeBaseUrl: exchange.baseUrl,
force: true,
});
+ await walletClient.call(WalletApiOperation.TestingWaitExchangeReady, {
+ exchangeBaseUrl: exchange.baseUrl,
+ });
await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
const bal = await walletClient.call(WalletApiOperation.GetBalances, {});
console.log("wallet balance", bal);
+ t.assertAmountEquals(bal.balances[0].available, "TESTKUDOS:15");
const order = {
summary: "Buy me!",
@@ -233,23 +250,24 @@ export async function runRevocationTest(t: GlobalTestState) {
await walletClient.call(WalletApiOperation.ClearDb, {});
- await withdrawViaBankV4(t, {
+ const secondWithdrawal = await withdrawViaBankV4(t, {
walletClient,
bank,
exchange,
amount: "TESTKUDOS:15",
});
+ await secondWithdrawal.withdrawalFinishedCond;
const coinDump = await walletClient.call(WalletApiOperation.DumpCoins, {});
console.log(coinDump);
const coinPubList = coinDump.coins.map((x) => x.coinPub);
await walletClient.call(WalletApiOperation.ForceRefresh, {
refreshCoinSpecs: coinPubList.map((x) => ({ coinPub: x })),
});
- await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
+ await walletClient.call(WalletApiOperation.TestingWaitRefreshesFinal, {});
console.log("revoking second time");
- await revokeAllWalletCoins({ walletClient, exchange, merchant });
+ await revokeAllWalletCoins({ walletClient, exchange, merchant, round: 2 });
// FIXME: this shouldn't be necessary once https://bugs.taler.net/n/6565
// is implemented.
@@ -257,10 +275,15 @@ export async function runRevocationTest(t: GlobalTestState) {
exchangeBaseUrl: exchange.baseUrl,
force: true,
});
+ await walletClient.call(WalletApiOperation.TestingWaitExchangeReady, {
+ exchangeBaseUrl: exchange.baseUrl,
+ });
await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
+ await walletClient.call(WalletApiOperation.TestingWaitRefreshesFinal, {});
{
const bal = await walletClient.call(WalletApiOperation.GetBalances, {});
console.log("wallet balance", bal);
+ t.assertAmountEquals(bal.balances[0].available, "TESTKUDOS:15");
}
await makeTestPaymentV2(t, {
@@ -269,13 +292,69 @@ export async function runRevocationTest(t: GlobalTestState) {
order,
merchantAdminAccessToken,
});
+
+ // A refresh marks its input dormant before submitting /melt. Revoke it
+ // in that window and require recoup to recover the value and settle the
+ // original refresh without counting its promised outputs a second time.
+ await walletClient.call(WalletApiOperation.ClearDb, {});
+ const thirdWithdrawal = await withdrawViaBankV4(t, {
+ walletClient,
+ bank,
+ exchange,
+ amount: "TESTKUDOS:15",
+ });
+ await thirdWithdrawal.withdrawalFinishedCond;
+ await walletClient.call(WalletApiOperation.ApplyDevExperiment, {
+ devExperimentUri: "taler://dev-experiment/start-block-refresh",
+ });
+ const dormantCoins = await walletClient.call(
+ WalletApiOperation.DumpCoins,
+ {},
+ );
+ await walletClient.call(WalletApiOperation.ForceRefresh, {
+ refreshCoinSpecs: dormantCoins.coins.map((c) => ({ coinPub: c.coinPub })),
+ });
+ await revokeAllWalletCoins({ walletClient, exchange, merchant, round: 3 });
+ await walletClient.call(WalletApiOperation.UpdateExchangeEntry, {
+ exchangeBaseUrl: exchange.baseUrl,
+ force: true,
+ });
+ await walletClient.call(WalletApiOperation.TestingWaitExchangeReady, {
+ exchangeBaseUrl: exchange.baseUrl,
+ });
+ let recovered = false;
+ for (let i = 0; i < 200; i++) {
+ const balance = await walletClient.call(WalletApiOperation.GetBalances, {});
+ if (balance.balances[0]?.available === "TESTKUDOS:15") {
+ recovered = true;
+ break;
+ }
+ await delayMs(50);
+ }
+ t.assertTrue(recovered);
+ await walletClient.call(WalletApiOperation.ApplyDevExperiment, {
+ devExperimentUri: "taler://dev-experiment/stop-block-refresh",
+ });
+ await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
+ await walletClient.call(WalletApiOperation.TestingWaitRefreshesFinal, {});
+ let finalBalance = await walletClient.call(
+ WalletApiOperation.GetBalances,
+ {},
+ );
+ // Recoup settles the superseded refresh when the source is credited. Its
+ // hidden replacement withdrawal can still be running after both waits.
+ for (let i = 0; i < 200; i++) {
+ if (
+ finalBalance.balances[0]?.available === "TESTKUDOS:15" &&
+ finalBalance.balances[0]?.pendingIncoming === "TESTKUDOS:0"
+ )
+ break;
+ await delayMs(50);
+ finalBalance = await walletClient.call(WalletApiOperation.GetBalances, {});
+ }
+ t.assertAmountEquals(finalBalance.balances[0].available, "TESTKUDOS:15");
+ t.assertAmountEquals(finalBalance.balances[0].pendingIncoming, "TESTKUDOS:0");
}
runRevocationTest.timeoutMs = 120000;
runRevocationTest.suites = ["wallet"];
-runRevocationTest.experimental = true;
-// The exchange deliberately leaves the legacy /coins/$COIN_PUB/recoup and
-// /recoup-refresh handlers disabled until exchange issue #9828 is resolved.
-// Keep the scenario visible without treating that known protocol gap as a
-// harness regression.
-runRevocationTest.todo = "https://bugs.taler.net/n/9828";
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -403,6 +403,8 @@ export interface WalletRefreshGroupPerExchangeInfo {
* currency.
*/
export interface WalletRefreshGroup {
+ /** Recoup claimed these particular pending inputs before its first request. */
+ recoupGroupPerCoin?: Record<number, string>;
/** DD71 metadata; notices are exposed only after successful completion. */
autoRefresh?: {
dismissed?: boolean;
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 = 27;
+export const SQLITE_SCHEMA_VERSION = 28;
/**
* Tables of the IndexedDB emulation, children before parents.
@@ -1545,6 +1545,13 @@ export const schemaMigrations: SchemaMigration[] = [
"ALTER TABLE coins ADD COLUMN recoup_group_id TEXT",
],
},
+ {
+ version: 28,
+ name: "refresh-recoup-associations",
+ statements: [
+ "ALTER TABLE refresh_groups ADD COLUMN recoup_group_per_coin 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
@@ -3794,6 +3794,9 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
private rowToRefreshGroup(row: ResultRow): WalletRefreshGroup {
return {
+ ...(row.recoup_group_per_coin == null
+ ? {}
+ : { recoupGroupPerCoin: dbToJson(row.recoup_group_per_coin) }),
...(row.auto_refresh == null
? {}
: { autoRefresh: dbToJson(row.auto_refresh) }),
@@ -3838,16 +3841,17 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
async upsertRefreshGroup(rec: WalletRefreshGroup): Promise<void> {
await this.run(
- `INSERT INTO refresh_groups (transaction_amounts,
+ `INSERT INTO refresh_groups (recoup_group_per_coin, transaction_amounts,
refresh_group_id, operation_status, currency, reason, auto_refresh,
originating_transaction_id, old_coin_pubs, input_per_coin,
expected_output_per_coin, info_per_exchange, status_per_coin,
refund_requests, timestamp_created, fail_reason, timestamp_finished
- ) VALUES ($transactionAmounts,
+ ) VALUES ($recoupGroups, $transactionAmounts,
$id, $status, $cur, $reason, $ar, $otid, $ocp, $ipc, $eopc, $ipe,
$spc, $rr, $created, $fail, $finished
)
ON CONFLICT(refresh_group_id) DO UPDATE SET
+ recoup_group_per_coin = excluded.recoup_group_per_coin,
transaction_amounts = excluded.transaction_amounts,
operation_status = excluded.operation_status,
currency = excluded.currency,
@@ -3868,6 +3872,10 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
rec.transactionAmounts === undefined
? null
: jsonToDb(rec.transactionAmounts),
+ recoupGroups:
+ rec.recoupGroupPerCoin == null
+ ? null
+ : jsonToDb(rec.recoupGroupPerCoin),
id: rec.refreshGroupId,
status: rec.operationStatus,
cur: rec.currency,
diff --git a/packages/taler-wallet-core/src/db/testing/conformance-cases.ts b/packages/taler-wallet-core/src/db/testing/conformance-cases.ts
@@ -29,6 +29,7 @@ import {
decodeCrock,
DenomLossEventType,
encodeCrock,
+ hashCoinEv,
MerchantContractTokenKind,
RefreshReason,
ScopeType,
@@ -805,8 +806,244 @@ function interruptBefore(
});
}
+/** The database is real; these cases only stub caches and task scheduling. */
+function makeRecoveryTestContext(started: string[]) {
+ return {
+ taskScheduler: {
+ startShepherdTask(id: string) {
+ started.push(id);
+ },
+ },
+ ws: {
+ denomInfoCache: {
+ getOrPut: async (_key: string, f: () => Promise<unknown>) => f(),
+ },
+ },
+ } as unknown as import("../../wallet.js").WalletExecutionContext;
+}
+
+async function seedRecoveryExchange(tx: WalletDbTransaction, baseUrl: string) {
+ const exchange = makeExchange(baseUrl);
+ const details = makeExchangeDetails(baseUrl, "atomic-master");
+ await tx.upsertExchangeDetails(details);
+ exchange.detailsPointer = {
+ masterPublicKey: details.masterPublicKey,
+ currency: details.currency,
+ updateClock: tsPrecise(1000),
+ };
+ await tx.upsertExchange(exchange);
+}
+
export const conformanceCases: ConformanceCase[] = [
{
+ name: "recoup credit and superseded refresh commit or roll back together",
+ async run(t, runner) {
+ const { recordRecoupCredit } = await import("../../recoup.js");
+ const coin = makeCoin("atomic-recoup-coin");
+ coin.status = CoinStatus.Dormant;
+ const recoup = makeRecoupGroup("atomic-recoup", coin.exchangeBaseUrl);
+ recoup.coinPubs = [coin.coinPub];
+ const refresh = makeRefreshGroup("atomic-refresh");
+ refresh.oldCoinPubs = [coin.coinPub];
+ refresh.inputPerCoin = [amt("TESTKUDOS:1")];
+ refresh.expectedOutputPerCoin = [amt("TESTKUDOS:0.9")];
+ refresh.statusPerCoin = [RefreshCoinStatus.Pending];
+ refresh.recoupGroupPerCoin = { 0: recoup.recoupGroupId };
+ const session = makeRefreshSession(refresh.refreshGroupId, 0);
+ const availability = {
+ exchangeMasterPub: coin.exchangeMasterPub,
+ denomPubHash: session.newDenoms[0].denomPubHash,
+ maxAge: 0,
+ freshCoinCount: 0,
+ visibleCoinCount: 0,
+ pendingRefreshOutputCount: 2,
+ currency: "TESTKUDOS",
+ value: amt("TESTKUDOS:1"),
+ exchangeBaseUrl: coin.exchangeBaseUrl,
+ hasFreshCoins: 0 as const,
+ };
+ await runner.runReadWriteTx(async (tx) => {
+ const exchange = makeExchange(coin.exchangeBaseUrl);
+ await tx.upsertExchangeDetails(
+ makeExchangeDetails(exchange.baseUrl, coin.exchangeMasterPub),
+ );
+ exchange.detailsPointer = {
+ masterPublicKey: coin.exchangeMasterPub,
+ currency: "TESTKUDOS",
+ updateClock: tsPrecise(1000),
+ };
+ await tx.upsertExchange(exchange);
+ await tx.upsertCoin(coin);
+ await tx.upsertRecoupGroup(recoup);
+ await tx.upsertRefreshGroup(refresh);
+ await tx.upsertRefreshSession(session);
+ await tx.upsertCoinAvailability(availability);
+ });
+ const wex = {
+ ws: {
+ denomInfoCache: {
+ getOrPut: async (_key: string, f: () => Promise<unknown>) => f(),
+ },
+ },
+ } as unknown as import("../../wallet.js").WalletExecutionContext;
+ try {
+ await runner.runReadWriteTx((tx) =>
+ recordRecoupCredit(
+ wex,
+ interruptBefore(tx, "upsertRecoupGroup"),
+ recoup.recoupGroupId,
+ 0,
+ coin,
+ "TESTKUDOS:1",
+ ),
+ );
+ t.fail("expected interruption");
+ } catch (e) {
+ t.equal((e as Error).message, "interrupted between writes");
+ }
+ await runner.runReadWriteTx(async (tx) => {
+ t.equal((await tx.getCoin(coin.coinPub))!.recoupGroupId, undefined);
+ t.deepEqual(
+ (await tx.getRecoupGroup(recoup.recoupGroupId))!
+ .recoupFinishedPerCoin,
+ [false],
+ );
+ t.deepEqual(
+ (await tx.getRefreshGroup(refresh.refreshGroupId))!
+ .expectedOutputPerCoin,
+ ["TESTKUDOS:0.9"],
+ );
+ t.equal(
+ !!(await tx.getRefreshSession(refresh.refreshGroupId, 0)),
+ true,
+ );
+ t.equal(
+ (await tx.getCoinAvailability(availability))!
+ .pendingRefreshOutputCount,
+ 2,
+ );
+ await recordRecoupCredit(
+ wex,
+ tx,
+ recoup.recoupGroupId,
+ 0,
+ coin,
+ "TESTKUDOS:1",
+ );
+ });
+ await runner.runReadWriteTx(async (tx) => {
+ t.equal(
+ (await tx.getCoin(coin.coinPub))!.recoupGroupId,
+ recoup.recoupGroupId,
+ );
+ t.deepEqual(
+ (await tx.getRecoupGroup(recoup.recoupGroupId))!
+ .recoupFinishedPerCoin,
+ [true],
+ );
+ t.deepEqual(
+ (await tx.getRefreshGroup(refresh.refreshGroupId))!.statusPerCoin,
+ [RefreshCoinStatus.Finished],
+ );
+ t.deepEqual(
+ (await tx.getRefreshGroup(refresh.refreshGroupId))!
+ .expectedOutputPerCoin,
+ ["TESTKUDOS:0"],
+ );
+ t.equal(
+ await tx.getRefreshSession(refresh.refreshGroupId, 0),
+ undefined,
+ );
+ t.equal(
+ (await tx.getCoinAvailability(availability))!
+ .pendingRefreshOutputCount,
+ 0,
+ );
+ await recordRecoupCredit(
+ wex,
+ tx,
+ recoup.recoupGroupId,
+ 0,
+ coin,
+ "TESTKUDOS:1",
+ );
+ t.equal(
+ (await tx.getCoinAvailability(availability))!
+ .pendingRefreshOutputCount,
+ 0,
+ );
+ });
+ },
+ },
+ {
+ name: "recoup recovery: withdrawal and parent transition commit together",
+ async run(t, runner) {
+ const { completeRecoupGroup } = await import("../../recoup.js");
+ const started: string[] = [];
+ const wex = makeRecoveryTestContext(started);
+ const withdrawal = makeWithdrawalGroup("atomic-recoup-withdrawal");
+ withdrawal.status = WithdrawalGroupStatus.PendingQueryingStatus;
+ withdrawal.exchangeBaseUrl = "https://recoup.exchange.test/";
+ withdrawal.effectiveWithdrawalAmount = amt("TESTKUDOS:1");
+ withdrawal.wgInfo = { withdrawalType: WithdrawalRecordType.Recoup };
+ const prep = {
+ withdrawalGroup: withdrawal,
+ transactionId: txnId(`txn:withdrawal:${withdrawal.withdrawalGroupId}`),
+ };
+ const parent = makeRecoupGroup(
+ "atomic-parent-recoup",
+ withdrawal.exchangeBaseUrl,
+ );
+ // Coin reconciliation has finished; only successor creation remains.
+ parent.coinPubs = [];
+ parent.recoupFinishedPerCoin = [];
+ await runner.runReadWriteTx(async (tx) => {
+ await seedRecoveryExchange(tx, withdrawal.exchangeBaseUrl!);
+ await tx.upsertRecoupGroup(parent);
+ });
+ const finish = (tx: WalletDbTransaction) =>
+ completeRecoupGroup(wex, tx, parent.recoupGroupId, [prep]);
+ try {
+ await runner.runReadWriteTx((tx) =>
+ finish(interruptBefore(tx, "upsertRecoupGroup")),
+ );
+ t.fail("expected interruption");
+ } catch (e) {
+ t.equal((e as Error).message, "interrupted between writes");
+ }
+ t.deepEqual(started, []);
+ await runner.runReadWriteTx(async (tx) => {
+ t.equal(
+ await tx.getWithdrawalGroup(withdrawal.withdrawalGroupId),
+ undefined,
+ );
+ t.equal(
+ (await tx.getRecoupGroup(parent.recoupGroupId))!.operationStatus,
+ RecoupOperationStatus.Pending,
+ );
+ await finish(tx);
+ t.deepEqual(started, [], "task must wait for commit");
+ });
+ t.equal(started.length, 1);
+ await runner.runReadWriteTx(async (tx) => {
+ t.ok(await tx.getWithdrawalGroup(withdrawal.withdrawalGroupId));
+ t.equal(
+ (await tx.getRecoupGroup(parent.recoupGroupId))!.operationStatus,
+ RecoupOperationStatus.Finished,
+ );
+
+ await finish(tx);
+ t.equal(
+ (await tx.listAllWithdrawalGroups()).filter(
+ (g) => g.withdrawalGroupId === withdrawal.withdrawalGroupId,
+ ).length,
+ 1,
+ );
+ });
+ t.equal(started.length, 1, "replay must not start another withdrawal");
+ },
+ },
+ {
name: "permanent recoup and refund reasons survive storage and replacement",
async run(t, runner) {
const reason = {
@@ -2933,6 +3170,85 @@ export const conformanceCases: ConformanceCase[] = [
// -------------------------------------------------- withdrawal groups
{
+ name: "deleting a received peer payment preserves recoup for a pre-upgrade coin",
+ async run(t, runner) {
+ const { PeerPullCreditTransactionContext } =
+ await import("../../pay-peer-pull-credit.js");
+ const { hashWithdrawalPlanchets } = await import("../../withdraw.js");
+ const parent = makePeerPullCredit("paid-purse");
+ const group = makeWithdrawalGroup("received-withdrawal");
+ group.status = WithdrawalGroupStatus.Done;
+ group.wgInfo = {
+ withdrawalType: WithdrawalRecordType.PeerPullCredit,
+ contractPriv: parent.contractPriv,
+ };
+ delete group.batches;
+ parent.status = PeerPullPaymentCreditStatus.Done;
+ parent.withdrawalGroupId = group.withdrawalGroupId;
+
+ const planchet = makePlanchet(
+ "received-coin",
+ group.withdrawalGroupId,
+ 0,
+ );
+ planchet.coinEv = {
+ cipher: DenomKeyType.Rsa,
+ rsa_blinded_planchet: ck("envelope"),
+ };
+ planchet.planchetStatus = PlanchetStatus.WithdrawalDone;
+ planchet.coinEvHash = encodeCrock(
+ hashCoinEv(planchet.coinEv, planchet.denomPubHash),
+ );
+ const commitment = hashWithdrawalPlanchets(
+ [planchet.coinEv],
+ [planchet.denomPubHash],
+ );
+ const coin = makeCoin("received-coin");
+ coin.coinEvHash = planchet.coinEvHash;
+ coin.denomPubHash = planchet.denomPubHash;
+ coin.sourceTransactionId = txnId(
+ `txn:withdrawal:${group.withdrawalGroupId}`,
+ );
+ coin.coinSource = {
+ type: CoinSourceType.Withdraw,
+ withdrawalGroupId: group.withdrawalGroupId,
+ reservePub: group.reservePub,
+ coinIndex: 0,
+ hPlanchets: commitment,
+ };
+ await runner.runReadWriteTx(async (tx) => {
+ await tx.upsertPeerPullCredit(parent);
+ await tx.upsertWithdrawalGroup(group);
+ await tx.upsertPlanchet(planchet);
+ await tx.upsertCoin(coin);
+ });
+
+ const wex = makeRecoveryTestContext([]);
+ wex.runWalletDbTx = runner.runReadWriteTx.bind(runner);
+ await new PeerPullCreditTransactionContext(
+ wex,
+ parent.pursePub,
+ ).userDeleteTransaction();
+ await runner.runReadWriteTx(async (tx) => {
+ t.equal(await tx.getPeerPullCredit(parent.pursePub), undefined);
+ t.equal(
+ await tx.getWithdrawalGroup(group.withdrawalGroupId),
+ undefined,
+ );
+ t.deepEqual(await tx.getPlanchetsByGroup(group.withdrawalGroupId), []);
+ const retained = (await tx.getCoin(coin.coinPub))?.coinSource;
+ t.deepEqual(
+ retained?.type === CoinSourceType.Withdraw && retained.recoupBatch,
+ {
+ commitment,
+ coinIndex: 0,
+ envelopeHashes: [coin.coinEvHash],
+ },
+ );
+ });
+ },
+ },
+ {
name: "withdrawal group: rejection and planchet error commit or roll back together",
async run(t, runner) {
const { recordWithdrawalBatchError } = await import("../../withdraw.js");
@@ -3964,6 +4280,7 @@ export const conformanceCases: ConformanceCase[] = [
name: "refresh group: round trip, active range and originating lookup",
async run(t, runner) {
const rg = makeRefreshGroup("rg-1");
+ rg.recoupGroupPerCoin = { 1: "recoup-association" };
rg.originatingTransactionId = "txn:orig:1";
rg.autoRefresh = {
dismissed: false,
diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts
@@ -3775,12 +3775,6 @@ async function handleRecoup(
// We never even knew about the revoked denomination, all good.
continue;
}
- if (oldDenom.isRevoked) {
- // We already marked the denomination as revoked,
- // this implies we revoked all coins
- logger.trace("denom already revoked");
- continue;
- }
logger.info("revoking denom", recoupInfo.h_denom_pub);
oldDenom.isRevoked = true;
await tx.upsertDenomination(oldDenom);
diff --git a/packages/taler-wallet-core/src/recoup.test.ts b/packages/taler-wallet-core/src/recoup.test.ts
@@ -14,6 +14,7 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
import assert from "node:assert";
+import * as R from "./db/records.js";
import { test } from "node:test";
import { DenomKeyType, encodeCrock } from "@gnu-taler/taler-util";
import { nativeCrypto } from "./crypto/cryptoImplementation.js";
@@ -142,3 +143,611 @@ test("recoup withdrawal identities are deterministic per reserve", () => {
first,
);
});
+
+for (const version of ["34:0:8", "42:0:8"]) {
+ test(`withdraw recoup preserves request and credits actual recovery (${version})`, async (t) => {
+ const U = await import("@gnu-taler/taler-util");
+ const { recoupWithdrawCoin, RecoupTransactionContext } =
+ await import("./recoup.js");
+ const { CoinSourceType, RecoupOperationStatus, timestampProtocolToDb } =
+ await import("./db/records.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const priv = new Uint8Array(32).fill(13);
+ const pub = U.encodeCrock(U.eddsaGetPublic(priv));
+ const coin = {
+ coinPub: U.encodeCrock(U.eddsaGetPublic(U.decodeCrock(crock(2)))),
+ coinPriv: crock(2),
+ blindingKey: crock(3),
+ denomPubHash: crock(4, 64),
+ coinEvHash: crock(5, 64),
+ exchangeBaseUrl: "https://exchange.example/",
+ denomSig: { cipher: U.DenomKeyType.Rsa, rsa_signature: "signature" },
+ exchangeWithdrawValues: { cipher: U.DenomKeyType.Rsa },
+ coinSource: {
+ type: CoinSourceType.Withdraw,
+ reservePub: crock(6),
+ withdrawalGroupId: "wg",
+ coinIndex: 0,
+ // The old wallet kept this commitment when deleting the withdrawal.
+ hPlanchets: U.encodeCrock(U.hash(U.decodeCrock(crock(5, 64)))),
+ },
+ } as import("./db/records.js").WalletCoin;
+ const source =
+ coin.coinSource as import("./db/records.js").WalletWithdrawCoinSource;
+ let group: WalletRecoupGroup = {
+ recoupGroupId: "rg",
+ exchangeBaseUrl: coin.exchangeBaseUrl,
+ operationStatus: RecoupOperationStatus.Pending,
+ coinPubs: [coin.coinPub],
+ recoupFinishedPerCoin: [false],
+ scheduleRefreshCoins: [],
+ timestampStarted: R.timestampPreciseToDb(
+ U.TalerPreciseTimestamp.fromSeconds(0),
+ ),
+ timestampFinished: undefined,
+ };
+ const now = { t_s: Math.floor(Date.now() / 1000) };
+ const creditedAt = { t_s: now.t_s - 86400 };
+ const amount = "TESTKUDOS:0.4";
+ const hc = U.createHashContext();
+ hc.update(U.decodeCrock(coin.coinPub));
+ hc.update(U.bufferFromAmount(U.Amounts.parseOrThrow(amount)));
+ const payload = U.buildSigPS(
+ U.TalerSignaturePurpose.EXCHANGE_CONFIRM_RECOUP_WITHDRAW_BATCH,
+ )
+ .put(U.timestampRoundedToBuffer(creditedAt))
+ .put(U.decodeCrock(source.reservePub))
+ .put(U.decodeCrock(source.hPlanchets!))
+ .put(U.bufferFromAmount(U.Amounts.parseOrThrow(amount)))
+ .put(hc.finish())
+ .build();
+ const response = version.startsWith("42")
+ ? {
+ reserve_pub: source.reservePub,
+ planchets_h: source.hPlanchets,
+ timestamp: creditedAt,
+ total_amount: amount,
+ recoups: [{ coin_pub: coin.coinPub, amount }],
+ exchange_pub: pub,
+ exchange_sig: U.encodeCrock(U.eddsaSign(payload, priv)),
+ }
+ : { reserve_pub: source.reservePub };
+ const requests: { url: string; body: unknown }[] = [];
+ let failStatus: number | undefined;
+ let failCode = U.TalerErrorCode.EXCHANGE_GENERIC_OPERATION_UNKNOWN;
+ const tx = {
+ getWithdrawalGroup: async () => undefined,
+ getPlanchetsByGroup: async () => [],
+ getCoinsByExchange: async () => [coin],
+ listAllRefreshGroups: async () => [],
+ getPlanchetByGroupAndIndex: async () => undefined,
+ getExchange: async () => undefined,
+ getExchangeDetails: async () => ({
+ protocolVersionRange: version,
+ rowId: 1,
+ }),
+ getExchangeSignKeysByDetailsRowId: async () => [
+ {
+ signkeyPub: pub,
+ stampStart: timestampProtocolToDb({ t_s: now.t_s - 60 }),
+ stampExpire: timestampProtocolToDb({ t_s: now.t_s + 600 }),
+ },
+ ],
+ getRecoupGroup: async () => structuredClone(group),
+ upsertRecoupGroup: async (g: WalletRecoupGroup) => {
+ group = structuredClone(g);
+ },
+ getCoin: async () => coin,
+ upsertCoin: async () => {},
+ };
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ ws: {
+ denomInfoCache: {
+ getOrPut: async () => ({
+ value: "TESTKUDOS:1",
+ denomPub: { cipher: U.DenomKeyType.Rsa },
+ }),
+ },
+ },
+ cryptoApi: { createRecoupRequest: nativeCrypto.createRecoupRequest },
+ cancellationToken: U.CancellationToken.CONTINUE,
+ http: {
+ fetch: async (url: string, opts: any) => {
+ requests.push({ url, body: structuredClone(opts.body) });
+ if (requests.length === 1) throw Error("response lost");
+ return {
+ status: failStatus ?? 200,
+ requestUrl: url,
+ requestMethod: "POST",
+ headers: { get: () => "application/json" },
+ json: async () =>
+ failStatus
+ ? {
+ code: failCode,
+ }
+ : response,
+ };
+ },
+ },
+ } as unknown as import("./wallet.js").WalletExecutionContext;
+ await assert.rejects(
+ recoupWithdrawCoin(wex, "rg", 0, coin, source),
+ /response lost/,
+ );
+ assert.deepStrictEqual(group.recoupFinishedPerCoin, [false]);
+ for (failStatus of [404, 408, 412, 429, 500]) {
+ await assert.rejects(recoupWithdrawCoin(wex, "rg", 0, coin, source));
+ assert.deepStrictEqual(group.recoupFinishedPerCoin, [false]);
+ assert.equal(group.failedCoinPubs?.length ?? 0, 0);
+ }
+ if (version.startsWith("42")) {
+ const pending = structuredClone(group);
+ failStatus = 404;
+ failCode = U.TalerErrorCode.EXCHANGE_RECOUP_WITHDRAW_NOT_FOUND;
+ await recoupWithdrawCoin(wex, "rg", 0, coin, source);
+ assert.deepEqual(group.failedCoinPubs, [coin.coinPub]);
+ assert.deepEqual(group.recoupFinishedPerCoin, [true]);
+ group = pending;
+ }
+ failStatus = undefined;
+ if (version.startsWith("42")) {
+ const originalSig = response.exchange_sig;
+ response.exchange_sig = crock(99, 64);
+ await assert.rejects(
+ recoupWithdrawCoin(wex, "rg", 0, coin, source),
+ /invalid recoup batch confirmation signature/,
+ );
+ assert.deepStrictEqual(group.recoupFinishedPerCoin, [false]);
+ response.exchange_sig = originalSig;
+ }
+ await recoupWithdrawCoin(wex, "rg", 0, coin, source);
+ assert.ok(
+ requests.every((r) => JSON.stringify(r) === JSON.stringify(requests[0])),
+ );
+ assert.equal(
+ new URL(requests[0].url).pathname,
+ version.startsWith("42")
+ ? "/recoup-withdraw"
+ : `/coins/${coin.coinPub}/recoup`,
+ );
+ assert.equal(
+ group.recoveredAmounts?.[coin.coinPub],
+ version.startsWith("42") ? amount : "TESTKUDOS:1",
+ );
+ assert.deepStrictEqual(group.recoupFinishedPerCoin, [true]);
+ });
+}
+
+test("a missing original melt finishes only its recoup input", async (t) => {
+ const U = await import("@gnu-taler/taler-util");
+ const { processRecoupForCoin, RecoupTransactionContext } =
+ await import("./recoup.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const coin = {
+ coinPub: "refreshed",
+ exchangeBaseUrl: "https://exchange.example/",
+ coinEvHash: "envelope",
+ exchangeWithdrawValues: { cipher: DenomKeyType.Rsa },
+ coinSource: {
+ type: R.CoinSourceType.Refresh,
+ oldCoinPub: "parent",
+ recoupBatch: {
+ commitment: "rc",
+ coinIndex: 0,
+ envelopeHashes: ["envelope"],
+ },
+ },
+ } as R.WalletCoin;
+ const group = {
+ recoupGroupId: "rg",
+ operationStatus: R.RecoupOperationStatus.Pending,
+ coinPubs: ["credited", coin.coinPub],
+ recoupFinishedPerCoin: [true, false],
+ recoveredAmounts: { credited: "TESTKUDOS:1" },
+ } as unknown as WalletRecoupGroup;
+ const tx = {
+ getCoin: async () => coin,
+ getRecoupGroup: async () => structuredClone(group),
+ upsertRecoupGroup: async (g: WalletRecoupGroup) => Object.assign(group, g),
+ getExchange: async () => undefined,
+ getExchangeDetails: async () => ({ protocolVersionRange: "42:0:8" }),
+ listAllRefreshGroups: async () => [],
+ };
+ let failCode = U.TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN;
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ ws: {
+ denomInfoCache: { getOrPut: async () => ({ value: "TESTKUDOS:2" }) },
+ },
+ cancellationToken: U.CancellationToken.CONTINUE,
+ cryptoApi: {
+ signCoinHistoryRequest: async () => ({ sig: "authorization" }),
+ createRecoupRefreshRequest: async () => ({ coin_sig: "signature" }),
+ },
+ http: {
+ fetch: async (url: string, opts: { method: string }) => ({
+ status: 404,
+ requestUrl: url,
+ requestMethod: opts.method,
+ headers: { get: () => "application/json" },
+ json: async () => ({
+ code: url.endsWith("/recoup-refresh")
+ ? failCode
+ : U.TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN,
+ }),
+ }),
+ },
+ } as unknown as import("./wallet.js").WalletExecutionContext;
+ await assert.rejects(processRecoupForCoin(wex, "rg", 1));
+ assert.deepEqual(group.recoupFinishedPerCoin, [true, false]);
+ failCode = U.TalerErrorCode.EXCHANGE_RECOUP_REFRESH_MELT_NOT_FOUND;
+ await processRecoupForCoin(wex, "rg", 1);
+ assert.deepEqual(group.recoupFinishedPerCoin, [true, true]);
+ assert.deepEqual(group.failedCoinPubs, [coin.coinPub]);
+ assert.deepEqual(group.recoveredAmounts, { credited: "TESTKUDOS:1" });
+});
+
+test("recoup awaits each coin lock and processes siblings before reporting a failure", async (t) => {
+ const { processRecoupGroup, RecoupTransactionContext } =
+ await import("./recoup.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const group = {
+ operationStatus: R.RecoupOperationStatus.Pending,
+ coinPubs: ["missing", "reward"],
+ recoupFinishedPerCoin: [false, false],
+ } as WalletRecoupGroup;
+ const tx = {
+ getRecoupGroup: async () => structuredClone(group),
+ upsertRecoupGroup: async (g: WalletRecoupGroup) => Object.assign(group, g),
+ getCoin: async (pub: string) =>
+ pub === "reward"
+ ? { coinSource: { type: R.CoinSourceType.Reward } }
+ : undefined,
+ };
+ let outstanding = 0;
+ let peak = 0;
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ ws: {
+ networkAvailable: true,
+ runSequentialized: async (_lock: string[], f: () => Promise<void>) => {
+ peak = Math.max(peak, ++outstanding);
+ try {
+ await f();
+ } finally {
+ outstanding--;
+ }
+ },
+ },
+ } as unknown as import("./wallet.js").WalletExecutionContext;
+ await assert.rejects(processRecoupGroup(wex, "rg"), /Coin missing not found/);
+ assert.equal(peak, 1);
+ assert.equal(outstanding, 0);
+ assert.deepEqual(group.recoupFinishedPerCoin, [false, true]);
+});
+
+test("recoup skips a legacy reward before claiming its pending refresh", async (t) => {
+ const { processRecoupForCoin, RecoupTransactionContext } =
+ await import("./recoup.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const group = {
+ operationStatus: R.RecoupOperationStatus.Pending,
+ coinPubs: ["reward"],
+ recoupFinishedPerCoin: [false],
+ } as WalletRecoupGroup;
+ const tx = {
+ getRecoupGroup: async () => structuredClone(group),
+ getCoin: async () => ({ coinSource: { type: R.CoinSourceType.Reward } }),
+ upsertRecoupGroup: async (g: WalletRecoupGroup) => Object.assign(group, g),
+ upsertRefreshGroup: async () =>
+ assert.fail("reward recoup must leave the refresh alone"),
+ };
+ await processRecoupForCoin(
+ {
+ runWalletDbTx: async (f: any) => f(tx),
+ } as import("./wallet.js").WalletExecutionContext,
+ "legacy",
+ 0,
+ );
+ assert.deepEqual(group.recoupFinishedPerCoin, [true]);
+});
+
+test("deleted withdrawal proofs require all sibling envelopes in their original order", async () => {
+ const U = await import("@gnu-taler/taler-util");
+ const { reconstructWithdrawalRecoupBatches } = await import("./withdraw.js");
+ const plans = [rsaPlanchet(4), rsaPlanchet(5)];
+ const commitment = hashWithdrawalPlanchets(
+ plans.map((p) => p.coinEv),
+ plans.map((p) => p.denomPubHash),
+ );
+ const coins = plans.map(
+ (p) =>
+ ({
+ coinPub: crock(p.coinIdx),
+ coinEvHash: encodeCrock(U.hashCoinEv(p.coinEv, p.denomPubHash)),
+ coinSource: {
+ type: R.CoinSourceType.Withdraw,
+ coinIndex: p.coinIdx,
+ hPlanchets: commitment,
+ },
+ }) as R.WalletCoin,
+ );
+ const proofs = reconstructWithdrawalRecoupBatches(
+ [...coins].reverse(),
+ undefined,
+ [],
+ );
+ for (const [coinIndex, coin] of coins.entries()) {
+ assert.deepEqual(proofs.get(coin.coinPub), {
+ coinIndex,
+ commitment,
+ envelopeHashes: coins.map((c) => c.coinEvHash),
+ });
+ }
+ assert.equal(
+ reconstructWithdrawalRecoupBatches([coins[0]], undefined, []).size,
+ 0,
+ );
+});
+
+for (const [spent, replay] of [
+ ["TESTKUDOS:1", false],
+ ["TESTKUDOS:0.6", false],
+ ["TESTKUDOS:0", false],
+ ["TESTKUDOS:0.6", true],
+ ["TESTKUDOS:0", true],
+] as const) {
+ test(`recoup reconciles a signed melt of ${spent}, previous recoup: ${replay}`, async (t) => {
+ const U = await import("@gnu-taler/taler-util");
+ const { processRecoupForCoin, RecoupTransactionContext } =
+ await import("./recoup.js");
+ t.mock.method(
+ RecoupTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const coinPriv = crock(71);
+ const coinPub = U.encodeCrock(U.eddsaGetPublic(U.decodeCrock(coinPriv)));
+ const coin = {
+ coinPub,
+ coinPriv,
+ status: U.CoinStatus.Dormant,
+ denomPubHash: crock(72, 64),
+ blindingKey: crock(73),
+ exchangeBaseUrl: "https://exchange.example/",
+ denomSig: { cipher: U.DenomKeyType.Rsa, rsa_signature: "signature" },
+ exchangeWithdrawValues: { cipher: U.DenomKeyType.Rsa },
+ coinSource: {
+ type: R.CoinSourceType.Withdraw,
+ reservePub: crock(74),
+ withdrawalGroupId: "wg",
+ coinIndex: 0,
+ hPlanchets: crock(75, 64),
+ },
+ } as R.WalletCoin;
+ const rc = crock(76, 64);
+ const melt = {
+ type: "MELT",
+ history_offset: 1,
+ amount: spent,
+ melt_fee: "TESTKUDOS:0",
+ rc,
+ h_denom_pub: coin.denomPubHash,
+ coin_sig: U.encodeCrock(
+ U.eddsaSign(
+ U.buildSigPS(U.TalerSignaturePurpose.WALLET_COIN_MELT)
+ .put(U.decodeCrock(rc))
+ .put(U.decodeCrock(coin.denomPubHash))
+ .put(new Uint8Array(32))
+ .put(U.bufferFromAmount(spent))
+ .put(U.bufferFromAmount("TESTKUDOS:0"))
+ .build(),
+ U.decodeCrock(coinPriv),
+ ),
+ ),
+ };
+ let group = {
+ recoupGroupId: "rg",
+ exchangeBaseUrl: coin.exchangeBaseUrl,
+ operationStatus: R.RecoupOperationStatus.Pending,
+ coinPubs: [coinPub],
+ recoupFinishedPerCoin: [false],
+ scheduleRefreshCoins: [],
+ timestampStarted: R.timestampPreciseToDb(U.TalerPreciseTimestamp.now()),
+ timestampFinished: undefined,
+ } as R.WalletRecoupGroup;
+ const now = U.TalerProtocolTimestamp.now();
+ const creditedAt = { t_s: (now.t_s as number) - 86400 };
+ let awaitingKeyConfirmation = true;
+ const exchangePriv = U.decodeCrock(crock(78));
+ const exchangePub = U.encodeCrock(U.eddsaGetPublic(exchangePriv));
+ const tx = {
+ listAllRefreshGroups: async () => [],
+ getCoin: async () => coin,
+ getRecoupGroup: async () => structuredClone(group),
+ upsertRecoupGroup: async (g: R.WalletRecoupGroup) => {
+ group = structuredClone(g);
+ },
+ upsertCoin: async () => {},
+ getExchange: async () =>
+ awaitingKeyConfirmation
+ ? {
+ detailsPointer: { masterPublicKey: "new" },
+ supersededKeySet: { masterPublicKey: "old" },
+ }
+ : undefined,
+ getExchangeDetails: async () => ({
+ rowId: 1,
+ protocolVersionRange: "34:0:8",
+ }),
+ getExchangeSignKeysByDetailsRowId: async () => [
+ {
+ signkeyPub: exchangePub,
+ stampStart: R.timestampProtocolToDb({
+ t_s: (now.t_s as number) - 60,
+ }),
+ stampExpire: R.timestampProtocolToDb({
+ t_s: (now.t_s as number) + 60,
+ }),
+ },
+ ],
+ getPlanchetByGroupAndIndex: async () => undefined,
+ };
+ let posts = 0;
+ let historyRequests = 0;
+ const expected = U.Amounts.stringify(
+ U.Amounts.sub("TESTKUDOS:1", spent).amount,
+ );
+ const history: unknown[] = spent === "TESTKUDOS:0" ? [] : [melt];
+ if (replay) {
+ // The authenticated history is sufficient even if old source records
+ // have already been deleted and another POST could not be constructed.
+ delete (coin.coinSource as R.WalletWithdrawCoinSource).hPlanchets;
+ history.push({
+ type: "RECOUP-WITHDRAW",
+ history_offset: history.length + 1,
+ amount: expected,
+ h_denom_pub: coin.denomPubHash,
+ reserve_pub: crock(74),
+ coin_blind: coin.blindingKey,
+ timestamp: creditedAt,
+ exchange_pub: exchangePub,
+ coin_sig: U.encodeCrock(
+ U.eddsaSign(
+ U.buildSigPS(U.TalerSignaturePurpose.WALLET_COIN_RECOUP)
+ .put(U.decodeCrock(coin.denomPubHash))
+ .put(U.decodeCrock(coin.blindingKey))
+ .build(),
+ U.decodeCrock(coinPriv),
+ ),
+ ),
+ exchange_sig: U.encodeCrock(
+ U.eddsaSign(
+ U.buildSigPS(U.TalerSignaturePurpose.EXCHANGE_CONFIRM_RECOUP)
+ .put(U.timestampRoundedToBuffer(creditedAt))
+ .put(U.bufferFromAmount(expected))
+ .put(U.decodeCrock(coinPub))
+ .put(U.decodeCrock(crock(74)))
+ .build(),
+ exchangePriv,
+ ),
+ ),
+ });
+ }
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ cancellationToken: U.CancellationToken.CONTINUE,
+ cryptoApi: {
+ signCoinHistoryRequest: nativeCrypto.signCoinHistoryRequest,
+ isValidCoinHistory: nativeCrypto.isValidCoinHistory,
+ createRecoupRequest: nativeCrypto.createRecoupRequest,
+ },
+ ws: {
+ denomInfoCache: {
+ getOrPut: async () => ({
+ value: "TESTKUDOS:1",
+ denomPubHash: coin.denomPubHash,
+ denomPub: { cipher: U.DenomKeyType.Rsa },
+ feeDeposit: "TESTKUDOS:0",
+ feeRefresh: "TESTKUDOS:0",
+ feeRefund: "TESTKUDOS:0",
+ }),
+ },
+ },
+ http: {
+ fetch: async (url: string, opts: any) => {
+ if (opts.method === "POST") posts++;
+ else historyRequests++;
+ return {
+ status: 200,
+ requestUrl: url,
+ requestMethod: opts.method,
+ headers: { get: () => undefined },
+ json: async () =>
+ opts.method === "POST"
+ ? { reserve_pub: crock(74) }
+ : {
+ balance: replay ? "TESTKUDOS:0" : expected,
+ h_denom_pub: coin.denomPubHash,
+ history,
+ },
+ };
+ },
+ },
+ } as unknown as import("./wallet.js").WalletExecutionContext;
+ await assert.rejects(
+ processRecoupForCoin(wex, "rg", 0),
+ (error) =>
+ error instanceof U.TalerError &&
+ error.errorDetail.code ===
+ U.TalerErrorCode.WALLET_EXCHANGE_KEYS_NOT_ACCEPTED,
+ );
+ assert.equal(historyRequests, 0);
+ awaitingKeyConfirmation = false;
+ await processRecoupForCoin(wex, "rg", 0);
+ assert.equal(posts, replay || spent === "TESTKUDOS:1" ? 0 : 1);
+ assert.equal(group.recoveredAmounts?.[coinPub], expected);
+ assert.deepStrictEqual(group.recoupFinishedPerCoin, [true]);
+ });
+}
+
+test("deleting recoup history does not requeue credited, rejected or reward coins", async () => {
+ const { createRecoupGroup, RecoupTransactionContext } =
+ await import("./recoup.js");
+ const coins: R.WalletCoin[] = [
+ {
+ coinPub: "credited",
+ recoupGroupId: "old-recoup",
+ coinSource: { type: R.CoinSourceType.Withdraw },
+ },
+ { coinPub: "rejected", coinSource: { type: R.CoinSourceType.Refresh } },
+ { coinPub: "reward", coinSource: { type: R.CoinSourceType.Reward } },
+ ] as R.WalletCoin[];
+ let deleted = false;
+ const tx = {
+ getRecoupGroup: async () =>
+ deleted
+ ? undefined
+ : { recoupGroupId: "old-recoup", failedCoinPubs: ["rejected"] },
+ deleteRecoupGroup: async () => {
+ deleted = true;
+ },
+ deleteTransactionMeta: async () => {},
+ getRecoupGroupsByExchange: async () => [],
+ getCoinsByPubs: async (pubs: string[]) =>
+ structuredClone(coins.filter((c) => pubs.includes(c.coinPub))),
+ upsertCoin: async (coin: R.WalletCoin) => {
+ coins[coins.findIndex((c) => c.coinPub === coin.coinPub)] = coin;
+ },
+ upsertRecoupGroup: async () =>
+ assert.fail("recoup repeated after history deletion"),
+ } as unknown as import("./db/transaction.js").WalletDbTransaction;
+ const wex = {} as import("./wallet.js").WalletExecutionContext;
+ await new RecoupTransactionContext(wex, "old-recoup").deleteTransactionInTx(
+ tx,
+ );
+ assert.ok(deleted);
+ await createRecoupGroup(
+ wex,
+ tx,
+ "https://exchange.example/",
+ coins.map((c) => c.coinPub),
+ );
+});
diff --git a/packages/taler-wallet-core/src/recoup.ts b/packages/taler-wallet-core/src/recoup.ts
@@ -27,11 +27,17 @@
import { getHttpResponseErrorDetails } from "@gnu-taler/taler-util/http";
import { addPermanentCoinFailure } from "./transaction-reasons.js";
import {
+ RecoupBatchCoinData,
+ RecoupBatchResponse,
+ LibtoolVersion,
+ HttpStatusCode,
+ throwUnexpectedResponse,
AgeRestriction,
AmountJson,
AmountLike,
AmountString,
Amounts,
+ OperationFail,
CoinStatus,
DenomKeyType,
Logger,
@@ -79,24 +85,41 @@ import {
getScopeForAllExchanges,
requireExchangeCoinUseConfirmedOrThrow,
} from "./exchanges.js";
-import { createRefreshGroup, recoverRefreshCoinNonce } from "./refresh.js";
+import {
+ createRefreshGroup,
+ recoverRefreshCoinNonce,
+ deriveRefreshSession,
+ validateAndRecomputeCoinHistoryBalance,
+ bindRefreshesToRecoup,
+ settleRefreshesForRecoup,
+} from "./refresh.js";
import {
constructTransactionIdentifier,
makeTransactionActionUnsupportedError,
} from "./transactions.js";
import {
+ EXCHANGE_COINS_LOCK,
WalletExecutionContext,
getDenomInfo,
walletExchangeClient,
} from "./wallet.js";
import {
- internalCreateWithdrawalGroup,
+ reconstructWithdrawalRecoupBatches,
+ internalPrepareCreateWithdrawalGroup,
+ internalPerformCreateWithdrawalGroup,
+ PrepareCreateWithdrawalGroupResult,
+ WithdrawTransactionContext,
reconstructWithdrawalBatchHPlanchets,
} from "./withdraw.js";
export { reconstructWithdrawalBatchHPlanchets } from "./withdraw.js";
import { WalletDbTransaction } from "./db/transaction.js";
+import {
+ requireValidRecoupBatchConfirmation,
+ requireValidExchangeCoinHistory,
+} from "./exchange-signatures.js";
+
const logger = new Logger("operations/recoup.ts");
/**
@@ -121,30 +144,6 @@ export async function putGroupAsFinished(
await ctx.updateTransactionMeta(tx);
}
-async function recoupRewardCoin(
- wex: WalletExecutionContext,
- recoupGroupId: string,
- coinIdx: number,
- coin: WalletCoin,
-): Promise<void> {
- // We can't really recoup a coin we got via tipping.
- // Thus we just put the coin to sleep.
- // FIXME: somehow report this to the user
- await wex.runWalletDbTx(async (tx) => {
- const recoupGroup = await tx.getRecoupGroup(recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.operationStatus !== RecoupOperationStatus.Pending) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
- await putGroupAsFinished(wex, tx, recoupGroup, coinIdx);
- });
-}
-
export async function markRecoupCoinPermanentlyFailed(
wex: WalletExecutionContext,
recoupGroupId: string,
@@ -167,16 +166,56 @@ export async function markRecoupCoinPermanentlyFailed(
if (!group.failedCoinPubs.includes(coinPub)) {
group.failedCoinPubs.push(coinPub);
}
+ await settleRefreshesForRecoup(wex, tx, coinPub, recoupGroupId, false);
await putGroupAsFinished(wex, tx, group, coinIdx);
});
}
+async function handleRecoupFailure(
+ wex: WalletExecutionContext,
+ recoupGroupId: string,
+ coinIndex: number,
+ coinPub: string,
+ response: OperationFail<HttpStatusCode>,
+ missingOperationCode?: TalerErrorCode,
+): Promise<void> {
+ // Only an explicit v42 rejection of this original commitment is definitive.
+ const missingOperation =
+ missingOperationCode !== undefined &&
+ response.detail?.code === missingOperationCode;
+ if (
+ response.case === HttpStatusCode.RequestTimeout ||
+ response.case === HttpStatusCode.TooManyRequests ||
+ (response.case === HttpStatusCode.NotFound && !missingOperation) ||
+ response.case === HttpStatusCode.PreconditionFailed ||
+ response.case >= 500
+ ) {
+ throwUnexpectedResponse(response);
+ }
+ logger.warn(
+ `exchange permanently rejected recoup for ${coinPub}: ${j2s(response.detail)}`,
+ );
+ await markRecoupCoinPermanentlyFailed(
+ wex,
+ recoupGroupId,
+ coinIndex,
+ coinPub,
+ response.detail ??
+ makeErrorDetail(
+ TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
+ getHttpResponseErrorDetails(response.response),
+ "exchange permanently rejected recoup",
+ ),
+ );
+}
+
async function recoupRefreshCoin(
wex: WalletExecutionContext,
recoupGroupId: string,
coinIdx: number,
coin: WalletCoin,
cs: WalletRefreshCoinSource,
+ residualAmount?: AmountString,
): Promise<void> {
let nonce = cs.nonce;
if (
@@ -228,71 +267,48 @@ async function recoupRefreshCoin(
const exchangeClient = walletExchangeClient(coin.exchangeBaseUrl, wex);
await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl);
- const recoupResp = await exchangeClient.recoupRefreshCoin(
- coin.coinPub,
- recoupRequest,
- );
+ const batchProtocol = await usesBatchRecoup(wex, coin);
+ let recoveredAmount = residualAmount ?? d.denomInfo.value;
+ if (batchProtocol) await ensureRecoupProvenance(wex, coin);
+ const recoupResp = batchProtocol
+ ? await exchangeClient.recoupRefreshBatch({
+ old_coin_pub: cs.oldCoinPub,
+ rc: cs.recoupBatch!.commitment,
+ coin_data: makeRecoupBatchCoinData(coin, recoupRequest.coin_sig),
+ })
+ : await exchangeClient.recoupRefreshCoin(coin.coinPub, recoupRequest);
if (recoupResp.case !== "ok") {
- logger.warn(
- `exchange permanently rejected recoup-refresh for ${coin.coinPub}: ${j2s(recoupResp.detail)}`,
- );
- await markRecoupCoinPermanentlyFailed(
+ return handleRecoupFailure(
wex,
recoupGroupId,
coinIdx,
coin.coinPub,
- recoupResp.detail ??
- makeErrorDetail(
- TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
- getHttpResponseErrorDetails(recoupResp.response),
- "exchange permanently rejected recoup",
- ),
+ recoupResp,
+ batchProtocol
+ ? TalerErrorCode.EXCHANGE_RECOUP_REFRESH_MELT_NOT_FOUND
+ : undefined,
);
- return;
}
+ if (batchProtocol)
+ recoveredAmount = await requireValidRecoupBatchConfirmation(
+ wex,
+ coin.exchangeBaseUrl,
+ "refresh",
+ cs.oldCoinPub,
+ cs.recoupBatch!.commitment,
+ coin.coinPub,
+ d.denomInfo.value,
+ recoupResp.body as RecoupBatchResponse,
+ );
const recoupConfirmation = recoupResp.body;
if (recoupConfirmation.old_coin_pub != cs.oldCoinPub) {
throw Error(`Coin's oldCoinPub doesn't match reserve on recoup`);
}
- await wex.runWalletDbTx(async (tx) => {
- const recoupGroup = await tx.getRecoupGroup(recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.operationStatus !== RecoupOperationStatus.Pending) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
- const oldCoin = await tx.getCoin(cs.oldCoinPub);
- const revokedCoin = await tx.getCoin(coin.coinPub);
- if (!revokedCoin) {
- logger.warn("revoked coin for recoup not found");
- return;
- }
- if (!oldCoin) {
- logger.warn("refresh old coin for recoup not found");
- return;
- }
- const oldCoinDenom = await getDenomInfo(wex, tx, oldCoin);
- const revokedCoinDenom = await getDenomInfo(wex, tx, revokedCoin);
- checkDbInvariant(
- !!oldCoinDenom,
- `no denom for coin, hash ${oldCoin.denomPubHash}`,
- );
- checkDbInvariant(
- !!revokedCoinDenom,
- `no revoked denom for coin, hash ${revokedCoin.denomPubHash}`,
- );
- revokedCoin.status = CoinStatus.Dormant;
- scheduleRecoupRefresh(recoupGroup, oldCoin.coinPub, revokedCoinDenom.value);
- await tx.upsertCoin(revokedCoin);
- await tx.upsertCoin(oldCoin);
- await putGroupAsFinished(wex, tx, recoupGroup, coinIdx);
- });
+ await wex.runWalletDbTx((tx) =>
+ recordRecoupCredit(wex, tx, recoupGroupId, coinIdx, coin, recoveredAmount),
+ );
}
export function scheduleRecoupRefresh(
@@ -325,6 +341,7 @@ export async function recoupWithdrawCoin(
coinIdx: number,
coin: WalletCoin,
cs: WalletWithdrawCoinSource,
+ residualAmount?: AmountString,
): Promise<void> {
const reservePub = cs.reservePub;
const recoupInputs = await wex.runWalletDbTx(async (tx) => {
@@ -336,7 +353,7 @@ export async function recoupWithdrawCoin(
cs.withdrawalGroupId,
cs.coinIndex,
);
- let hPlanchets = cs.hPlanchets;
+ let hPlanchets = cs.recoupBatch?.commitment ?? cs.hPlanchets;
if (!hPlanchets) {
const withdrawalGroup = await tx.getWithdrawalGroup(cs.withdrawalGroupId);
if (withdrawalGroup?.denomsSel) {
@@ -390,28 +407,39 @@ export async function recoupWithdrawCoin(
logger.trace(`requesting recoup for coin ${coin.coinPub}`);
const exchangeClient = walletExchangeClient(coin.exchangeBaseUrl, wex);
await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl);
- const recoupResp = await exchangeClient.recoupCoin(
- coin.coinPub,
- recoupRequest,
- );
+ const batchProtocol = await usesBatchRecoup(wex, coin);
+ let recoveredAmount = residualAmount ?? recoupInputs.denomInfo.value;
+ if (batchProtocol) await ensureRecoupProvenance(wex, coin);
+ const recoupResp = batchProtocol
+ ? await exchangeClient.recoupWithdrawBatch({
+ reserve_pub: reservePub,
+ planchets_h: cs.recoupBatch!.commitment,
+ coin_data: makeRecoupBatchCoinData(coin, recoupRequest.coin_sig),
+ })
+ : await exchangeClient.recoupCoin(coin.coinPub, recoupRequest);
if (recoupResp.case !== "ok") {
- logger.warn(
- `exchange permanently rejected recoup for ${coin.coinPub}: ${j2s(recoupResp.detail)}`,
- );
- await markRecoupCoinPermanentlyFailed(
+ return handleRecoupFailure(
wex,
recoupGroupId,
coinIdx,
coin.coinPub,
- recoupResp.detail ??
- makeErrorDetail(
- TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
- getHttpResponseErrorDetails(recoupResp.response),
- "exchange permanently rejected recoup",
- ),
+ recoupResp,
+ batchProtocol
+ ? TalerErrorCode.EXCHANGE_RECOUP_WITHDRAW_NOT_FOUND
+ : undefined,
);
- return;
}
+ if (batchProtocol)
+ recoveredAmount = await requireValidRecoupBatchConfirmation(
+ wex,
+ coin.exchangeBaseUrl,
+ "withdraw",
+ reservePub,
+ cs.recoupBatch!.commitment,
+ coin.coinPub,
+ recoupInputs.denomInfo.value,
+ recoupResp.body as RecoupBatchResponse,
+ );
const recoupConfirmation = recoupResp.body;
logger.trace(`got recoup confirmation ${j2s(recoupConfirmation)}`);
@@ -421,29 +449,55 @@ export async function recoupWithdrawCoin(
}
// FIXME: verify that our expectations about the amount match
- await wex.runWalletDbTx(async (tx) => {
- const recoupGroup = await tx.getRecoupGroup(recoupGroupId);
- if (!recoupGroup) {
- return;
- }
- if (recoupGroup.operationStatus !== RecoupOperationStatus.Pending) {
- return;
- }
- if (recoupGroup.recoupFinishedPerCoin[coinIdx]) {
- return;
- }
- const updatedCoin = await tx.getCoin(coin.coinPub);
- if (!updatedCoin) {
- return;
- }
- updatedCoin.status = CoinStatus.Dormant;
- recoupGroup.successfulCoinPubs ??= [];
- if (!recoupGroup.successfulCoinPubs.includes(updatedCoin.coinPub)) {
- recoupGroup.successfulCoinPubs.push(updatedCoin.coinPub);
- }
- await tx.upsertCoin(updatedCoin);
- await putGroupAsFinished(wex, tx, recoupGroup, coinIdx);
- });
+ await wex.runWalletDbTx((tx) =>
+ recordRecoupCredit(wex, tx, recoupGroupId, coinIdx, coin, recoveredAmount),
+ );
+}
+
+/** Credit, its successor work, and superseded refresh inputs share one commit. */
+export async function recordRecoupCredit(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ recoupGroupId: string,
+ coinIndex: number,
+ coin: WalletCoin,
+ amount: AmountString,
+): Promise<void> {
+ const group = await tx.getRecoupGroup(recoupGroupId);
+ if (
+ group?.operationStatus !== RecoupOperationStatus.Pending ||
+ group.recoupFinishedPerCoin[coinIndex]
+ )
+ return;
+ const current = await tx.getCoin(coin.coinPub);
+ checkDbInvariant(!!current, "recoup coin disappeared");
+ if (current.coinSource.type === CoinSourceType.Refresh) {
+ checkDbInvariant(
+ !!(await tx.getCoin(current.coinSource.oldCoinPub)),
+ "recoup parent coin disappeared",
+ );
+ scheduleRecoupRefresh(group, current.coinSource.oldCoinPub, amount);
+ } else {
+ checkDbInvariant(
+ current.coinSource.type === CoinSourceType.Withdraw,
+ "unexpected recoup source",
+ );
+ group.successfulCoinPubs ??= [];
+ if (!group.successfulCoinPubs.includes(coin.coinPub))
+ group.successfulCoinPubs.push(coin.coinPub);
+ }
+ current.recoupGroupId = recoupGroupId;
+ current.status = CoinStatus.Dormant;
+ (group.recoveredAmounts ??= {})[coin.coinPub] = amount;
+ await tx.upsertCoin(current);
+ await settleRefreshesForRecoup(
+ wex,
+ tx,
+ coin.coinPub,
+ recoupGroupId,
+ Amounts.isNonZero(amount),
+ );
+ await putGroupAsFinished(wex, tx, group, coinIndex);
}
export async function processRecoupGroup(
@@ -474,15 +528,20 @@ export async function processRecoupGroup(
logger.trace("recoup group finished");
return TaskRunResult.finished();
}
- const ps = recoupGroup.coinPubs.map(async (x, i) => {
+ const finishedCoins = recoupGroup.recoupFinishedPerCoin;
+ let firstFailure: { error: unknown } | undefined;
+ for (let i = 0; i < finishedCoins.length; i++) {
+ if (finishedCoins[i]) continue;
try {
- await processRecoupForCoin(wex, recoupGroupId, i);
- } catch (e) {
- logger.warn(`processRecoup failed: ${e}`);
- throw e;
+ await wex.ws.runSequentialized([EXCHANGE_COINS_LOCK], () =>
+ processRecoupForCoin(wex, recoupGroupId, i),
+ );
+ } catch (error) {
+ logger.warn(`processRecoup failed: ${error}`);
+ firstFailure ??= { error };
}
- });
- await Promise.all(ps);
+ }
+ if (firstFailure) throw firstFailure.error;
recoupGroup = await wex.runWalletDbTx(async (tx) => {
return tx.getRecoupGroup(recoupGroupId);
@@ -519,8 +578,13 @@ export async function processRecoupGroup(
reserveAmounts.set(
coin.coinSource.reservePub,
previous
- ? Amounts.add(previous, denom.value).amount
- : Amounts.jsonifyAmount(denom.value),
+ ? Amounts.add(
+ previous,
+ recoupGroup.recoveredAmounts?.[coinPub] ?? denom.value,
+ ).amount
+ : Amounts.jsonifyAmount(
+ recoupGroup.recoveredAmounts?.[coinPub] ?? denom.value,
+ ),
);
}
}
@@ -531,58 +595,82 @@ export async function processRecoupGroup(
}
});
+ const withdrawals: PrepareCreateWithdrawalGroupResult[] = [];
for (const [reservePub, recoveredAmount] of reserveAmounts) {
- await internalCreateWithdrawalGroup(wex, {
- amount: recoveredAmount,
- exchangeBaseUrl: recoupGroup.exchangeBaseUrl,
- reserveStatus: WithdrawalGroupStatus.PendingQueryingStatus,
- forcedWithdrawalGroupId: deterministicRecoupWithdrawalGroupId(
- recoupGroupId,
- reservePub,
- ),
- reserveKeyPair: {
- pub: reservePub,
- priv: reservePrivMap[reservePub],
- },
- wgInfo: {
- withdrawalType: WithdrawalRecordType.Recoup,
- },
- });
+ withdrawals.push(
+ await internalPrepareCreateWithdrawalGroup(wex, {
+ amount: recoveredAmount,
+ exchangeBaseUrl: recoupGroup.exchangeBaseUrl,
+ reserveStatus: WithdrawalGroupStatus.PendingQueryingStatus,
+ forcedWithdrawalGroupId: deterministicRecoupWithdrawalGroupId(
+ recoupGroupId,
+ reservePub,
+ ),
+ reserveKeyPair: {
+ pub: reservePub,
+ priv: reservePrivMap[reservePub],
+ },
+ wgInfo: {
+ withdrawalType: WithdrawalRecordType.Recoup,
+ },
+ }),
+ );
}
- const ctx = new RecoupTransactionContext(wex, recoupGroupId);
-
- await wex.runWalletDbTx(async (tx) => {
- const rg2 = await tx.getRecoupGroup(recoupGroupId);
- if (!rg2) {
- return;
- }
- if (rg2.operationStatus !== RecoupOperationStatus.Pending) {
- return;
- }
- rg2.timestampFinished = timestampPreciseToDb(TalerPreciseTimestamp.now());
- rg2.operationStatus = rg2.failedCoinPubs?.length
- ? RecoupOperationStatus.Failed
- : RecoupOperationStatus.Finished;
- if (rg2.scheduleRefreshCoins.length > 0) {
- await createRefreshGroup(
- wex,
- tx,
- Amounts.currencyOf(rg2.scheduleRefreshCoins[0].amount),
- rg2.scheduleRefreshCoins,
- RefreshReason.Recoup,
- constructTransactionIdentifier({
- tag: TransactionType.Recoup,
- recoupGroupId: rg2.recoupGroupId,
- }),
- );
- }
- await tx.upsertRecoupGroup(rg2);
- await ctx.updateTransactionMeta(tx);
- });
+ await wex.runWalletDbTx((tx) =>
+ completeRecoupGroup(wex, tx, recoupGroupId, withdrawals),
+ );
return TaskRunResult.finished();
}
+/** Install all successor work in the same transaction that completes recoup. */
+export async function completeRecoupGroup(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ recoupGroupId: string,
+ withdrawals: PrepareCreateWithdrawalGroupResult[],
+): Promise<void> {
+ const ctx = new RecoupTransactionContext(wex, recoupGroupId);
+ const rg2 = await tx.getRecoupGroup(recoupGroupId);
+ if (!rg2) {
+ return;
+ }
+ if (rg2.operationStatus !== RecoupOperationStatus.Pending) {
+ return;
+ }
+ checkDbInvariant(
+ rg2.recoupFinishedPerCoin.every(Boolean),
+ "recoup inputs are unfinished",
+ );
+ for (const withdrawal of withdrawals) {
+ await internalPerformCreateWithdrawalGroup(wex, tx, withdrawal);
+ await new WithdrawTransactionContext(
+ wex,
+ withdrawal.withdrawalGroup.withdrawalGroupId,
+ ).updateTransactionMeta(tx);
+ }
+ rg2.timestampFinished = timestampPreciseToDb(TalerPreciseTimestamp.now());
+ rg2.operationStatus = rg2.failedCoinPubs?.length
+ ? RecoupOperationStatus.Failed
+ : RecoupOperationStatus.Finished;
+ const refreshRequests = rg2.scheduleRefreshCoins;
+ if (refreshRequests.length > 0) {
+ await createRefreshGroup(
+ wex,
+ tx,
+ Amounts.currencyOf(refreshRequests[0].amount),
+ refreshRequests,
+ RefreshReason.Recoup,
+ constructTransactionIdentifier({
+ tag: TransactionType.Recoup,
+ recoupGroupId: rg2.recoupGroupId,
+ }),
+ );
+ }
+ await tx.upsertRecoupGroup(rg2);
+ await ctx.updateTransactionMeta(tx);
+}
+
export function deterministicRecoupWithdrawalGroupId(
recoupGroupId: string,
reservePub: string,
@@ -684,6 +772,13 @@ export class RecoupTransactionContext implements TransactionContext {
if (!rec) {
return { notifs };
}
+ // Retain terminal rejections even when deleting a pre-upgrade group.
+ for (const coin of await tx.getCoinsByPubs(rec.failedCoinPubs ?? [])) {
+ if (!coin.recoupGroupId) {
+ coin.recoupGroupId = rec.recoupGroupId;
+ await tx.upsertCoin(coin);
+ }
+ }
await tx.deleteRecoupGroup(this.recoupGroupId);
await this.updateTransactionMeta(tx);
return { notifs };
@@ -778,6 +873,16 @@ export async function createRecoupGroup(
exchangeBaseUrl: string,
coinPubs: string[],
): Promise<string> {
+ const existing = await tx.getRecoupGroupsByExchange(exchangeBaseUrl);
+ const coins = await tx.getCoinsByPubs(coinPubs);
+ const coinsByPub = new Map(coins.map((coin) => [coin.coinPub, coin]));
+ coinPubs = coinPubs.filter(
+ (pub) =>
+ !coinsByPub.get(pub)?.recoupGroupId &&
+ coinsByPub.get(pub)?.coinSource.type !== CoinSourceType.Reward &&
+ !existing.some((g) => g.coinPubs.includes(pub)),
+ );
+ if (!coinPubs.length) return existing[0]?.recoupGroupId ?? "";
const recoupGroupId = encodeCrock(getRandomBytes(32));
const ctx = new RecoupTransactionContext(wex, recoupGroupId);
@@ -794,8 +899,6 @@ export async function createRecoupGroup(
operationStatus: RecoupOperationStatus.Pending,
};
- const coins = await tx.getCoinsByPubs(coinPubs);
- const coinsByPub = new Map(coins.map((coin) => [coin.coinPub, coin]));
for (let coinIdx = 0; coinIdx < coinPubs.length; coinIdx++) {
const coinPub = coinPubs[coinIdx];
const coin = coinsByPub.get(coinPub);
@@ -803,24 +906,13 @@ export async function createRecoupGroup(
await putGroupAsFinished(wex, tx, recoupGroup, coinIdx);
continue;
}
- // Only coins with locally spendable value can contribute anything to a
- // recoup. In particular, a fully spent (Dormant) coin can legitimately
- // be rejected by the exchange and must not block recovery of its fresh
- // siblings forever.
- if (
- coin.status !== CoinStatus.Fresh &&
- coin.status !== CoinStatus.FreshSuspended
- ) {
- await putGroupAsFinished(wex, tx, recoupGroup, coinIdx);
- continue;
- }
await tx.upsertCoin(coin);
}
await tx.upsertRecoupGroup(recoupGroup);
await ctx.updateTransactionMeta(tx);
- wex.taskScheduler.startShepherdTask(ctx.taskId);
+ tx.scheduleOnCommit(() => wex.taskScheduler.startShepherdTask(ctx.taskId));
return recoupGroupId;
}
@@ -828,7 +920,7 @@ export async function createRecoupGroup(
/**
* Run the recoup protocol for a single coin in a recoup group.
*/
-async function processRecoupForCoin(
+export async function processRecoupForCoin(
wex: WalletExecutionContext,
recoupGroupId: string,
coinIdx: number,
@@ -854,6 +946,11 @@ async function processRecoupForCoin(
if (!coin) {
throw Error(`Coin ${coinPub} not found, can't request recoup`);
}
+ if (coin.coinSource.type === CoinSourceType.Reward) {
+ // Tipping coins have no recoup destination. Leave their refreshes alone.
+ await putGroupAsFinished(wex, tx, recoupGroup, coinIdx);
+ return;
+ }
return coin;
});
@@ -861,16 +958,254 @@ async function processRecoupForCoin(
return;
}
+ const denomination = await wex.runWalletDbTx((tx) =>
+ getDenomInfo(wex, tx, coin),
+ );
+ checkDbInvariant(
+ !!denomination,
+ "missing denomination for recoup reconciliation",
+ );
+ const historySig = await wex.cryptoApi.signCoinHistoryRequest({
+ coinPriv: coin.coinPriv,
+ coinPub: coin.coinPub,
+ startOffset: 0,
+ });
+ await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl);
+ const historyResponse = await walletExchangeClient(
+ coin.exchangeBaseUrl,
+ wex,
+ ).getCoinHistory(coin.coinPub, historySig.sig);
+ let residualAmount = denomination.value;
+ let historyItems: import("@gnu-taler/taler-util").CoinSpendHistoryItem[] = [];
+ if (historyResponse.case === "ok") {
+ const history = historyResponse.body;
+ historyItems = history.history;
+ await requireValidExchangeCoinHistory(wex, {
+ exchangeBaseUrl: coin.exchangeBaseUrl,
+ coinPub: coin.coinPub,
+ denomination,
+ response: history,
+ });
+ const residual = validateAndRecomputeCoinHistoryBalance(
+ coin.denomPubHash,
+ denomination.value,
+ history,
+ );
+ const previousRecoup = history.history.find(
+ (h) => h.type === "RECOUP-WITHDRAW" || h.type === "RECOUP-REFRESH",
+ );
+ if (previousRecoup) {
+ const source = coin.coinSource;
+ checkDbInvariant(
+ (previousRecoup.type === "RECOUP-WITHDRAW" &&
+ source.type === CoinSourceType.Withdraw &&
+ previousRecoup.reserve_pub === source.reservePub) ||
+ (previousRecoup.type === "RECOUP-REFRESH" &&
+ source.type === CoinSourceType.Refresh &&
+ previousRecoup.old_coin_pub === source.oldCoinPub),
+ "recoup history destination does not match coin source",
+ );
+ await wex.runWalletDbTx((tx) =>
+ recordRecoupCredit(
+ wex,
+ tx,
+ recoupGroupId,
+ coinIdx,
+ coin,
+ previousRecoup.amount,
+ ),
+ );
+ return;
+ }
+ residualAmount = residual;
+ } else if (
+ historyResponse.case !== HttpStatusCode.NotFound ||
+ historyResponse.detail?.code !==
+ TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN
+ ) {
+ throwUnexpectedResponse(historyResponse);
+ }
+
+ if (!(await bindRefreshesToRecoup(wex, coin, recoupGroupId, historyItems)))
+ return;
+ if (Amounts.isZero(residualAmount)) {
+ await wex.runWalletDbTx(async (tx) => {
+ const group = await tx.getRecoupGroup(recoupGroupId);
+ if (group?.operationStatus !== RecoupOperationStatus.Pending) return;
+ (group.recoveredAmounts ??= {})[coin.coinPub] = residualAmount;
+ const currentCoin = await tx.getCoin(coin.coinPub);
+ if (currentCoin) {
+ currentCoin.recoupGroupId = recoupGroupId;
+ await tx.upsertCoin(currentCoin);
+ }
+ await settleRefreshesForRecoup(
+ wex,
+ tx,
+ coin.coinPub,
+ recoupGroupId,
+ false,
+ );
+ await putGroupAsFinished(wex, tx, group, coinIdx);
+ });
+ return;
+ }
const cs = coin.coinSource;
switch (cs.type) {
- case CoinSourceType.Reward:
- return recoupRewardCoin(wex, recoupGroupId, coinIdx, coin);
case CoinSourceType.Refresh:
- return recoupRefreshCoin(wex, recoupGroupId, coinIdx, coin, cs);
+ return recoupRefreshCoin(
+ wex,
+ recoupGroupId,
+ coinIdx,
+ coin,
+ cs,
+ residualAmount,
+ );
case CoinSourceType.Withdraw:
- return recoupWithdrawCoin(wex, recoupGroupId, coinIdx, coin, cs);
+ return recoupWithdrawCoin(
+ wex,
+ recoupGroupId,
+ coinIdx,
+ coin,
+ cs,
+ residualAmount,
+ );
default:
throw Error("unknown coin source type");
}
}
+/** Recover retained source material before deleting transaction history or recouping. */
+export async function ensureRecoupProvenance(
+ wex: WalletExecutionContext,
+ coin: WalletCoin,
+): Promise<void> {
+ const source = coin.coinSource;
+ if (source.type === CoinSourceType.Reward || source.recoupBatch) return;
+ let proof: NonNullable<WalletWithdrawCoinSource["recoupBatch"]> | undefined;
+ if (source.type === CoinSourceType.Withdraw) {
+ proof = await wex.runWalletDbTx(async (tx) => {
+ const group = await tx.getWithdrawalGroup(source.withdrawalGroupId);
+ const planchets = await tx.getPlanchetsByGroup(source.withdrawalGroupId);
+ const siblings = coin.sourceTransactionId
+ ? await tx.getCoinsBySourceTransaction(coin.sourceTransactionId)
+ : await tx.getCoinsByExchange(coin.exchangeBaseUrl);
+ const members = siblings.filter(
+ (c) =>
+ c.coinPub !== coin.coinPub &&
+ c.coinSource.type === CoinSourceType.Withdraw &&
+ c.coinSource.withdrawalGroupId === source.withdrawalGroupId &&
+ c.coinSource.hPlanchets === source.hPlanchets,
+ );
+ return reconstructWithdrawalRecoupBatches(
+ [coin, ...members],
+ group,
+ planchets,
+ ).get(coin.coinPub);
+ });
+ } else {
+ const inputs = await wex.runWalletDbTx(async (tx) => {
+ const group = await tx.getRefreshGroup(source.refreshGroupId);
+ const index = group?.oldCoinPubs.indexOf(source.oldCoinPub) ?? -1;
+ const session =
+ index < 0
+ ? undefined
+ : await tx.getRefreshSession(source.refreshGroupId, index);
+ const oldCoin = await tx.getCoin(source.oldCoinPub);
+ if (!session || session.norevealIndex == null || !oldCoin) return;
+ const oldDenom = await getDenomInfo(wex, tx, oldCoin);
+ checkDbInvariant(!!oldDenom, "missing refresh input denomination");
+ const newDenoms = [];
+ for (const d of session.newDenoms) {
+ const denom = await getDenomInfo(wex, tx, {
+ exchangeMasterPub: oldCoin.exchangeMasterPub,
+ denomPubHash: d.denomPubHash,
+ });
+ checkDbInvariant(!!denom, "missing refresh output denomination");
+ newDenoms.push({
+ ...denom,
+ count: d.count,
+ value: Amounts.stringify(denom.value),
+ });
+ }
+ return { session, oldCoin, oldDenom, newDenoms };
+ });
+ if (inputs) {
+ const derived = await deriveRefreshSession(
+ wex,
+ inputs.session,
+ inputs.oldCoin,
+ inputs.oldDenom,
+ inputs.newDenoms,
+ );
+ const outputs = derived.planchets[inputs.session.norevealIndex!];
+ const index = outputs.findIndex((p) => p.coinPub === coin.coinPub);
+ if (index >= 0)
+ proof = {
+ commitment: derived.hash,
+ coinIndex: index,
+ envelopeHashes: outputs.map((p) => p.coinEvHash),
+ };
+ }
+ }
+ checkDbInvariant(
+ !!proof,
+ "original coin batch cannot be reconstructed; retain recovery material",
+ );
+ source.recoupBatch = proof;
+ await wex.runWalletDbTx(async (tx) => {
+ const current = await tx.getCoin(coin.coinPub);
+ if (current && current.coinSource.type !== CoinSourceType.Reward) {
+ current.coinSource.recoupBatch = proof;
+ if (current.coinSource.type === CoinSourceType.Withdraw)
+ current.coinSource.hPlanchets = proof.commitment;
+ await tx.upsertCoin(current);
+ }
+ });
+}
+
+export function makeRecoupBatchCoinData(
+ coin: WalletCoin,
+ signature: string,
+): RecoupBatchCoinData[] {
+ const source = coin.coinSource;
+ checkDbInvariant(
+ source.type !== CoinSourceType.Reward && !!source.recoupBatch,
+ "missing recoup batch",
+ );
+ const proof = source.recoupBatch;
+ checkDbInvariant(
+ proof.coinIndex >= 0 &&
+ proof.coinIndex < proof.envelopeHashes.length &&
+ proof.envelopeHashes[proof.coinIndex] === coin.coinEvHash,
+ "recoup batch does not contain coin",
+ );
+ return proof.envelopeHashes.map((h, i) =>
+ i !== proof.coinIndex
+ ? { type: "hash", h_coin_ev: h }
+ : {
+ type: "recoup",
+ coin_pub: coin.coinPub,
+ denom_pub_h: coin.denomPubHash,
+ denom_sig: coin.denomSig,
+ coin_blinding_secret: coin.blindingKey,
+ coin_sig: signature,
+ h_age_commitment: coin.ageCommitmentProof
+ ? AgeRestriction.hashCommitment(coin.ageCommitmentProof.commitment)
+ : undefined,
+ },
+ );
+}
+
+async function usesBatchRecoup(
+ wex: WalletExecutionContext,
+ coin: WalletCoin,
+): Promise<boolean> {
+ const details = await wex.runWalletDbTx((tx) =>
+ tx.getExchangeDetails(coin.exchangeBaseUrl),
+ );
+ checkDbInvariant(!!details, "exchange details missing for recoup");
+ return (
+ (LibtoolVersion.parseVersion(details.protocolVersionRange)?.current ?? 0) >=
+ 42
+ );
+}
diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts
@@ -527,3 +527,259 @@ test("coin history keeps refund fee waivers bound to one deposit", () => {
/refunds exceed their deposit/,
);
});
+
+test("recoup claims only existing unaccepted refreshes and never a later credit", async (t) => {
+ const { bindRefreshesToRecoup, settleRefreshesForRecoup } =
+ await import("./refresh.js");
+ const coin = {
+ coinPub: "coin",
+ exchangeBaseUrl: "https://exchange/",
+ } as WalletCoin;
+ const groups = new Map(
+ ["unaccepted", "accepted"].map((id) => [
+ id,
+ {
+ refreshGroupId: id,
+ oldCoinPubs: [coin.coinPub],
+ statusPerCoin: [RefreshCoinStatus.Pending],
+ expectedOutputPerCoin: ["TESTKUDOS:4"],
+ infoPerExchange: {
+ [coin.exchangeBaseUrl]: { outputEffective: "TESTKUDOS:4" },
+ },
+ } as WalletRefreshGroup,
+ ]),
+ );
+ const sessions = new Map(
+ [...groups.keys()].map((id) => [
+ id,
+ {
+ refreshGroupId: id,
+ coinIndex: 0,
+ sessionPublicSeed: id,
+ newDenoms: [],
+ } as unknown as WalletRefreshSession,
+ ]),
+ );
+ const U = await import("@gnu-taler/taler-util");
+ const now = Math.floor(Date.now() / 1000);
+ let refundStatus = 503;
+ const permission = {
+ h_contract_terms: "contract",
+ merchant_pub: "merchant",
+ merchant_sig: "permission",
+ rtransaction_id: 42,
+ refund_amount: "TESTKUDOS:2",
+ } as const;
+ groups.get("unaccepted")!.refundRequests = { 0: permission };
+ const tx = {
+ getExchange: async () => undefined,
+ getExchangeDetails: async () => ({ rowId: 1 }),
+ getExchangeSignKeysByDetailsRowId: async () => [
+ {
+ signkeyPub: "exchange-key",
+ stampStart: timestampProtocolToDb({ t_s: now - 60 }),
+ stampExpire: timestampProtocolToDb({ t_s: now + 60 }),
+ },
+ ],
+ listAllRefreshGroups: async () => structuredClone([...groups.values()]),
+ getRefreshGroup: async (id: string) => structuredClone(groups.get(id)),
+ upsertRefreshGroup: async (g: WalletRefreshGroup) => {
+ groups.set(g.refreshGroupId, structuredClone(g));
+ },
+ getRefreshSession: async (id: string) => structuredClone(sessions.get(id)),
+ deleteRefreshSession: async (id: string) => {
+ sessions.delete(id);
+ },
+ getCoin: async () => coin,
+ } as unknown as WalletDbTransaction;
+ const wex = {
+ cryptoApi: { isValidRefundConfirmation: async () => ({ valid: true }) },
+ cancellationToken: U.CancellationToken.CONTINUE,
+ ws: {},
+ http: {
+ fetch: async (url: string, opts: { body: unknown }) => {
+ assert.equal(new URL(url).pathname, "/coins/coin/refund");
+ assert.deepEqual(opts.body, permission);
+ return {
+ status: refundStatus,
+ requestUrl: url,
+ requestMethod: "POST",
+ headers: { get: () => "application/json" },
+ json: async () =>
+ refundStatus === 200
+ ? { exchange_pub: "exchange-key", exchange_sig: "signature" }
+ : { code: U.TalerErrorCode.GENERIC_DB_FETCH_FAILED },
+ };
+ },
+ },
+ runWalletDbTx: async (f: any) => f(tx),
+ } as unknown as WalletExecutionContext;
+ t.mock.method(
+ RefreshTransactionContext.prototype,
+ "getRecordHandle",
+ async function (this: RefreshTransactionContext) {
+ return [
+ await tx.getRefreshGroup(this.refreshGroupId),
+ { update: async (g: WalletRefreshGroup) => tx.upsertRefreshGroup(g) },
+ ] as any;
+ },
+ );
+ const history = [{ type: "MELT", refresh_seed: "accepted" }] as any;
+ assert.equal(
+ await bindRefreshesToRecoup(wex, coin, "recoup", history),
+ false,
+ );
+ assert.deepEqual(groups.get("unaccepted")!.refundRequests[0], permission);
+ refundStatus = 200;
+ assert.equal(
+ await bindRefreshesToRecoup(wex, coin, "recoup", history),
+ false,
+ );
+ assert.equal(groups.get("unaccepted")!.refundRequests[0], undefined);
+ assert.equal(groups.get("unaccepted")!.recoupGroupPerCoin, undefined);
+ // Only the following iteration, with a post-refund history, may claim the input.
+ await bindRefreshesToRecoup(wex, coin, "recoup", [
+ { type: "MELT", refresh_seed: "accepted" },
+ ] as any);
+ assert.deepStrictEqual(groups.get("unaccepted")!.recoupGroupPerCoin, {
+ 0: "recoup",
+ });
+ assert.equal(groups.get("accepted")!.recoupGroupPerCoin, undefined);
+ // Permanent failure (or a zero balance) releases the claim for retry.
+ await settleRefreshesForRecoup(wex, tx, coin.coinPub, "recoup", false);
+ assert.equal(groups.get("unaccepted")!.recoupGroupPerCoin?.[0], undefined);
+ assert.equal(
+ groups.get("unaccepted")!.statusPerCoin[0],
+ RefreshCoinStatus.Pending,
+ );
+ assert.ok(sessions.has("unaccepted"));
+ await bindRefreshesToRecoup(wex, coin, "recoup", [
+ { type: "MELT", refresh_seed: "accepted" },
+ ] as any);
+ groups.set("later-credit", {
+ ...structuredClone(groups.get("accepted")!),
+ refreshGroupId: "later-credit",
+ });
+ sessions.set("later-credit", {
+ ...sessions.get("accepted")!,
+ refreshGroupId: "later-credit",
+ });
+ // A lost recoup response is recovered from history after restart. A new
+ // refresh can exist by then, but must not acquire the earlier association.
+ await bindRefreshesToRecoup(wex, coin, "recoup", [
+ { type: "RECOUP-WITHDRAW" },
+ ] as any);
+ await settleRefreshesForRecoup(wex, tx, coin.coinPub, "recoup", true);
+ assert.equal(
+ groups.get("unaccepted")!.statusPerCoin[0],
+ RefreshCoinStatus.Finished,
+ );
+ assert.equal(
+ groups.get("unaccepted")!.expectedOutputPerCoin[0],
+ "TESTKUDOS:0",
+ );
+ assert.equal(sessions.has("unaccepted"), false);
+ for (const id of ["accepted", "later-credit"]) {
+ assert.equal(groups.get(id)!.statusPerCoin[0], RefreshCoinStatus.Pending);
+ assert.equal(groups.get(id)!.expectedOutputPerCoin[0], "TESTKUDOS:4");
+ assert.ok(sessions.has(id));
+ }
+ // Reapplying a confirmed result must not subtract the output a second time.
+ await settleRefreshesForRecoup(wex, tx, coin.coinPub, "recoup", true);
+ assert.equal(
+ groups.get("unaccepted")!.infoPerExchange![coin.exchangeBaseUrl]
+ .outputEffective,
+ "TESTKUDOS:0",
+ );
+});
+
+test("a corrected melt keeps the recouped sibling's output at zero", async (t) => {
+ const U = await import("@gnu-taler/taler-util");
+ const { handleRefreshMeltConflict } = await import("./refresh.js");
+ const denom = refreshOutputDenom(0);
+ const old = {
+ ...WalletDenomination.toDenomInfo(denom),
+ value: "TESTKUDOS:3",
+ };
+ const coin = {
+ coinPub: "pending",
+ exchangeBaseUrl: denom.exchangeBaseUrl,
+ exchangeMasterPub: denom.exchangeMasterPub,
+ denomPubHash: denom.denomPubHash,
+ maxAge: 0,
+ } as WalletCoin;
+ const group = {
+ refreshGroupId: "refresh",
+ currency: "TESTKUDOS",
+ oldCoinPubs: ["recouped", coin.coinPub],
+ inputPerCoin: ["TESTKUDOS:4", "TESTKUDOS:5"],
+ expectedOutputPerCoin: ["TESTKUDOS:0", "TESTKUDOS:4"],
+ recoupGroupPerCoin: { 0: "recoup" },
+ refundRequests: {},
+ statusPerCoin: [RefreshCoinStatus.Finished, RefreshCoinStatus.Pending],
+ infoPerExchange: {
+ [coin.exchangeBaseUrl]: { outputEffective: "TESTKUDOS:4" },
+ },
+ } as unknown as WalletRefreshGroup;
+ const tx = {
+ getRefreshSession: async () => ({ coinIndex: 1, newDenoms: [] }),
+ deleteRefreshSession: async () => {},
+ upsertRefreshSession: async () => {},
+ getCoin: async () => coin,
+ getCoinsByPubs: async (pubs: string[]) => {
+ assert.deepEqual(pubs, [coin.coinPub]);
+ return [coin];
+ },
+ getExchange: async () => undefined,
+ getDenominationFamiliesByExchange: async () => [
+ { denominationFamilySerial: 1, familyParams: denom },
+ ],
+ findDenominationByFamilyFromExpiry: async () => denom,
+ getCoinAvailability: async () => undefined,
+ upsertCoinAvailability: async () => {},
+ };
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ cancellationToken: U.CancellationToken.CONTINUE,
+ ws: {
+ denomInfoCache: { get: () => old, getOrPut: async () => old },
+ refreshCostCache: { get: () => Amounts.parseOrThrow("TESTKUDOS:1") },
+ },
+ cryptoApi: {
+ signCoinHistoryRequest: async () => ({ sig: "signature" }),
+ isValidCoinHistory: async () => ({ valid: true }),
+ },
+ http: {
+ fetch: async (url: string) => ({
+ status: 200,
+ requestUrl: url,
+ requestMethod: "GET",
+ headers: { get: () => "application/json" },
+ json: async () => ({
+ balance: "TESTKUDOS:3",
+ h_denom_pub: denom.denomPubHash,
+ history: [],
+ }),
+ }),
+ },
+ } as unknown as WalletExecutionContext;
+ const ctx = new RefreshTransactionContext(wex, "refresh");
+ t.mock.method(ctx, "getRecordHandle", async () => [
+ group,
+ { update: async () => {} },
+ ]);
+ await handleRefreshMeltConflict(
+ ctx,
+ group,
+ 1,
+ { code: TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS },
+ "TESTKUDOS:5",
+ coin,
+ );
+ assert.deepEqual(group.expectedOutputPerCoin, ["TESTKUDOS:0", "TESTKUDOS:2"]);
+ assert.equal(
+ group.infoPerExchange![coin.exchangeBaseUrl].outputEffective,
+ "TESTKUDOS:2",
+ );
+ assert.deepEqual(group.inputPerCoin, ["TESTKUDOS:4", "TESTKUDOS:3"]);
+});
diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts
@@ -14,6 +14,8 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { ensureRecoupProvenance } from "./recoup.js";
+
/**
* @fileoverview
* Implementation of the refresh transaction.
@@ -265,6 +267,7 @@ export class RefreshTransactionContext implements TransactionContext {
tx.getCoinsBySourceTransaction(this.transactionId),
);
for (const coin of sourceCoins) {
+ await ensureRecoupProvenance(this.wex, coin);
if (
coin.coinSource.type !== CoinSourceType.Refresh ||
coin.exchangeWithdrawValues.cipher !== DenomKeyType.ClauseSchnorr ||
@@ -306,8 +309,9 @@ export class RefreshTransactionContext implements TransactionContext {
)) {
if (
coin.coinSource.type === CoinSourceType.Refresh &&
- coin.exchangeWithdrawValues.cipher === DenomKeyType.ClauseSchnorr &&
- coin.coinSource.nonce == null
+ (!coin.coinSource.recoupBatch ||
+ (coin.exchangeWithdrawValues.cipher === DenomKeyType.ClauseSchnorr &&
+ coin.coinSource.nonce == null))
) {
throw makeTransactionActionUnsupportedError(
this.transactionId,
@@ -1048,6 +1052,7 @@ 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 ||
!session ||
@@ -1279,6 +1284,15 @@ async function refreshMelt(
const resp = await wex.ws.runSequentialized(
[EXCHANGE_COINS_LOCK],
async () => {
+ // Recoup can claim or finish this input while the melt waits for the lock.
+ const current = await wex.runWalletDbTx((tx) =>
+ tx.getRefreshGroup(refreshGroupId),
+ );
+ if (
+ current?.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending ||
+ current.recoupGroupPerCoin?.[coinIndex]
+ )
+ return undefined;
await requireExchangeCoinUseConfirmedOrThrow(
wex,
oldCoin.exchangeBaseUrl,
@@ -1554,7 +1568,61 @@ async function handleRefreshMeltGone(
});
}
-async function handleRefreshMeltConflict(
+/** Submit the merchant permission before consuming the coin's remaining balance. */
+async function reconcileRefreshRefund(
+ wex: WalletExecutionContext,
+ group: WalletRefreshGroup,
+ coinIndex: number,
+ coin: WalletCoin,
+): Promise<"refunded" | "refused" | "retry"> {
+ const request = group.refundRequests[coinIndex];
+ await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl);
+ const response = await walletExchangeClient(
+ coin.exchangeBaseUrl,
+ wex,
+ ).refundCoin(coin.coinPub, request);
+ if (response.case === "ok") {
+ await requireValidDirectExchangeRefundConfirmation(wex, {
+ exchangeBaseUrl: coin.exchangeBaseUrl,
+ contractTermsHash: request.h_contract_terms,
+ coinPub: coin.coinPub,
+ merchantPub: request.merchant_pub,
+ rtransactionId: request.rtransaction_id,
+ refundAmount: request.refund_amount,
+ response: response.body,
+ });
+ } else if (
+ response.case === HttpStatusCode.RequestTimeout ||
+ response.case === HttpStatusCode.TooManyRequests ||
+ response.case >= HttpStatusCode.InternalServerError ||
+ (response.case === HttpStatusCode.NotFound &&
+ response.detail?.code !==
+ TalerErrorCode.EXCHANGE_REFUND_DEPOSIT_NOT_FOUND &&
+ response.detail?.code !== TalerErrorCode.EXCHANGE_REFUND_COIN_NOT_FOUND)
+ ) {
+ logger.warn(
+ `Refund request during refresh failed: ${j2s(response.detail)}`,
+ );
+ return "retry";
+ } else {
+ logger.warn(
+ `Refund handoff during refresh refused: ${j2s(response.detail)}`,
+ );
+ }
+ 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];
+ await tx.upsertRefreshGroup(current);
+ }
+ });
+ return response.case === "ok" ? "refunded" : "refused";
+}
+
+export async function handleRefreshMeltConflict(
ctx: RefreshTransactionContext,
refreshGroup: WalletRefreshGroup,
coinIndex: number,
@@ -1570,62 +1638,14 @@ async function handleRefreshMeltConflict(
)} failed in refresh group ${ctx.refreshGroupId} due to conflict`,
);
- const refundReq = refreshGroup.refundRequests[coinIndex];
- if (refundReq != null) {
- logger.trace(`Doing deposit in refresh for coin ${coinIndex}`);
- const exchangeClient = walletExchangeClient(
- oldCoin.exchangeBaseUrl,
+ if (refreshGroup.refundRequests[coinIndex]) {
+ const result = await reconcileRefreshRefund(
ctx.wex,
+ refreshGroup,
+ coinIndex,
+ oldCoin,
);
- const refundResp = await exchangeClient.refundCoin(
- oldCoin.coinPub,
- refundReq,
- );
- if (refundResp.case === "ok") {
- await requireValidDirectExchangeRefundConfirmation(ctx.wex, {
- exchangeBaseUrl: oldCoin.exchangeBaseUrl,
- contractTermsHash: refundReq.h_contract_terms,
- coinPub: oldCoin.coinPub,
- merchantPub: refundReq.merchant_pub,
- rtransactionId: refundReq.rtransaction_id,
- refundAmount: refundReq.refund_amount,
- response: refundResp.body,
- });
- await ctx.wex.runWalletDbTx(async (tx) => {
- const rg = await tx.getRefreshGroup(refreshGroup.refreshGroupId);
- if (!rg || rg.operationStatus != RefreshOperationStatus.Pending) {
- return;
- }
- delete rg.refundRequests[coinIndex];
- await tx.upsertRefreshGroup(rg);
- });
- return;
- }
- if (
- refundResp.case === HttpStatusCode.RequestTimeout ||
- refundResp.case === HttpStatusCode.TooManyRequests ||
- refundResp.case >= HttpStatusCode.InternalServerError
- ) {
- logger.warn(
- `Refund request during refresh failed: ${j2s(refundResp.detail)}`,
- );
- return;
- }
- // The exchange refused the refund for good (it never saw the deposit,
- // or already paid it out), so the refund cannot explain the conflict
- // and would fail the same way on every retry. Drop the handoff and
- // let the coin history decide what is left to melt.
- logger.warn(
- `Refund handoff during refresh refused: ${j2s(refundResp.detail)}`,
- );
- await ctx.wex.runWalletDbTx(async (tx) => {
- const rg = await tx.getRefreshGroup(refreshGroup.refreshGroupId);
- if (!rg || rg.operationStatus != RefreshOperationStatus.Pending) {
- return;
- }
- delete rg.refundRequests[coinIndex];
- await tx.upsertRefreshGroup(rg);
- });
+ if (result !== "refused") return;
}
const historySig = await ctx.wex.cryptoApi.signCoinHistoryRequest({
@@ -1720,16 +1740,22 @@ async function handleRefreshMeltConflict(
ctx.wex,
tx,
rg.currency,
- rg.oldCoinPubs.map((coinPub, i) => ({
- coinPub,
- amount: rg.inputPerCoin[i],
- })),
+ [{ coinPub: oldCoin.coinPub, amount: correctedBalance }],
);
- rg.expectedOutputPerCoin = correctedOutput.outputPerCoin.map((x) =>
- Amounts.stringify(x),
+ const previousOutput = rg.expectedOutputPerCoin[coinIndex];
+ rg.expectedOutputPerCoin[coinIndex] = Amounts.stringify(
+ correctedOutput.outputPerCoin[0],
);
- rg.infoPerExchange = correctedOutput.perExchangeInfo;
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],
+ ).amount,
+ );
+ }
// The new session was computed from the corrected input amount,
// so that amount must be stored as well.
await h.update(rg, "melt-conflict-retry");
@@ -2152,6 +2178,11 @@ async function refreshReveal(
coinSource: {
type: CoinSourceType.Refresh,
refreshGroupId,
+ recoupBatch: {
+ commitment: derived.hash,
+ coinIndex: newCoinIndex,
+ envelopeHashes: planchets[norevealIndex].map((p) => p.coinEvHash),
+ },
oldCoinPub: refreshGroup.oldCoinPubs[coinIndex],
nonce:
pc.coinEv.cipher === DenomKeyType.ClauseSchnorr
@@ -2410,6 +2441,176 @@ export async function processRefreshGroup(
return TaskRunResult.backoff();
}
+/**
+ * Bind only currently pending, unaccepted melts before submitting recoup.
+ * The caller holds EXCHANGE_COINS_LOCK, so no melt can reach the exchange
+ * between examining its history and committing these associations. Return false
+ * when a refund needs retrying or the caller must refresh the coin history.
+ */
+export async function bindRefreshesToRecoup(
+ wex: WalletExecutionContext,
+ coin: WalletCoin,
+ recoupGroupId: string,
+ history: import("@gnu-taler/taler-util").CoinSpendHistoryItem[],
+): Promise<boolean> {
+ // A replay must use the associations persisted before its first POST.
+ // It must not capture refreshes created after the original recoup.
+ if (
+ history.some(
+ (h) => h.type === "RECOUP-WITHDRAW" || h.type === "RECOUP-REFRESH",
+ )
+ )
+ return true;
+ const candidates = await wex.runWalletDbTx(async (tx) => {
+ const result: {
+ group: WalletRefreshGroup;
+ index: number;
+ session?: WalletRefreshSession;
+ }[] = [];
+ for (const group of await tx.listAllRefreshGroups()) {
+ const index = group.oldCoinPubs.indexOf(coin.coinPub);
+ if (
+ index < 0 ||
+ ![
+ RefreshCoinStatus.Pending,
+ RefreshCoinStatus.PendingRedenominate,
+ ].includes(group.statusPerCoin[index])
+ )
+ continue;
+ const session = await tx.getRefreshSession(group.refreshGroupId, index);
+ result.push({ group, index, session });
+ }
+ return result;
+ });
+ const unaccepted: typeof candidates = [];
+ for (const candidate of candidates) {
+ if (candidate.group.refundRequests?.[candidate.index]) {
+ const result = await reconcileRefreshRefund(
+ wex,
+ candidate.group,
+ candidate.index,
+ coin,
+ );
+ // A granted refund changes the residual. Read a fresh history next time.
+ if (result !== "refused") return false;
+ }
+ const { session } = candidate;
+ if (session?.norevealIndex != null) continue;
+ if (session?.sessionPublicSeed) {
+ if (
+ history.some(
+ (h) =>
+ h.type === "MELT" && h.refresh_seed === session.sessionPublicSeed,
+ )
+ )
+ continue;
+ // Older histories identify accepted melts by commitment, without a seed.
+ if (history.some((h) => h.type === "MELT" && !h.refresh_seed)) {
+ const inputs = await wex.runWalletDbTx(async (tx) => {
+ const oldDenom = await getDenomInfo(wex, tx, coin);
+ checkDbInvariant(!!oldDenom, "missing recoup input denomination");
+ const newDenoms = [];
+ for (const d of session.newDenoms) {
+ const denom = await getDenomInfo(wex, tx, {
+ exchangeMasterPub: coin.exchangeMasterPub,
+ denomPubHash: d.denomPubHash,
+ });
+ checkDbInvariant(!!denom, "missing refresh output denomination");
+ newDenoms.push({
+ ...denom,
+ count: d.count,
+ value: Amounts.stringify(denom.value),
+ });
+ }
+ return { oldDenom, newDenoms };
+ });
+ const derived = await deriveRefreshSession(
+ wex,
+ session,
+ coin,
+ inputs.oldDenom,
+ inputs.newDenoms,
+ );
+ if (history.some((h) => h.type === "MELT" && h.rc === derived.hash))
+ continue;
+ }
+ }
+ unaccepted.push(candidate);
+ }
+ await wex.runWalletDbTx(async (tx) => {
+ for (const { group, index } of unaccepted) {
+ const current = await tx.getRefreshGroup(group.refreshGroupId);
+ const rs = await tx.getRefreshSession(group.refreshGroupId, index);
+ if (
+ !current ||
+ (current.recoupGroupPerCoin?.[index] !== undefined &&
+ current.recoupGroupPerCoin[index] !== recoupGroupId) ||
+ rs?.norevealIndex != null ||
+ ![
+ RefreshCoinStatus.Pending,
+ RefreshCoinStatus.PendingRedenominate,
+ ].includes(current.statusPerCoin[index])
+ )
+ continue;
+ (current.recoupGroupPerCoin ??= {})[index] = recoupGroupId;
+ await tx.upsertRefreshGroup(current);
+ }
+ });
+ return true;
+}
+
+/** Commit the affected refresh states with the recoup result, never its successors. */
+export async function settleRefreshesForRecoup(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ coinPub: string,
+ recoupGroupId: string,
+ recovered: boolean,
+): Promise<void> {
+ for (const group of await tx.listAllRefreshGroups()) {
+ const index = group.oldCoinPubs.indexOf(coinPub);
+ if (index < 0 || group.recoupGroupPerCoin?.[index] !== recoupGroupId)
+ continue;
+ if (
+ ![
+ RefreshCoinStatus.Pending,
+ RefreshCoinStatus.PendingRedenominate,
+ ].includes(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]) {
+ // 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];
+ } else {
+ const session = await tx.getRefreshSession(group.refreshGroupId, index);
+ checkDbInvariant(
+ session?.norevealIndex == null,
+ "recoup cannot supersede an accepted melt",
+ );
+ if (session) {
+ 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 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");
+ }
+}
+
async function processRefreshSession(
wex: WalletExecutionContext,
refreshGroupId: string,
@@ -2421,6 +2622,8 @@ 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])
+ return { refreshGroup: rg, refreshSession: undefined };
if (
rg &&
@@ -2829,10 +3032,7 @@ export async function createRefreshGroup(
logger.trace(`created refresh group ${refreshGroupId}`);
- // Shepherd the task.
- // If the current transaction fails to commit the refresh
- // group to the DB, the shepherd will give up.
- wex.taskScheduler.startShepherdTask(ctx.taskId);
+ tx.scheduleOnCommit(() => wex.taskScheduler.startShepherdTask(ctx.taskId));
tx.notify({
type: NotificationType.TransactionStateTransition,
@@ -2898,6 +3098,7 @@ async function redenominateRefresh(
for (let i = 0; i < refreshGroup.oldCoinPubs.length; i++) {
if (
+ !refreshGroup.recoupGroupPerCoin?.[i] &&
Amounts.isZero(refreshGroup.expectedOutputPerCoin[i]) &&
Amounts.isNonZero(outInfo.outputPerCoin[i]) &&
refreshGroup.statusPerCoin[i] === RefreshCoinStatus.Finished
diff --git a/packages/taler-wallet-core/src/testing-recover-coins.ts b/packages/taler-wallet-core/src/testing-recover-coins.ts
@@ -391,6 +391,11 @@ export async function recoverCoinMelt(
status: CoinStatus.Dormant,
coinSource: {
type: CoinSourceType.Refresh,
+ recoupBatch: {
+ commitment: derived.hash,
+ coinIndex: i,
+ envelopeHashes: derived.planchets[index].map((p) => p.coinEvHash),
+ },
refreshGroupId,
oldCoinPub: oldCoin.coinPub,
nonce:
diff --git a/packages/taler-wallet-core/src/withdraw.ts b/packages/taler-wallet-core/src/withdraw.ts
@@ -648,33 +648,25 @@ export class WithdrawTransactionContext implements TransactionContext {
const sourceCoins = await tx.getCoinsBySourceTransaction(
this.transactionId,
);
- const numCoins = rec.denomsSel?.selectedDenoms.reduce(
- (n, x) => n + x.count,
- 0,
+ const proofs = reconstructWithdrawalRecoupBatches(
+ sourceCoins,
+ rec,
+ planchets,
);
for (const coin of sourceCoins) {
- if (
- coin.coinSource.type !== CoinSourceType.Withdraw ||
- coin.coinSource.hPlanchets != null
- ) {
+ const source = coin.coinSource;
+ if (source.type !== CoinSourceType.Withdraw || source.recoupBatch)
continue;
- }
- const hPlanchets =
- numCoins == null
- ? undefined
- : reconstructWithdrawalBatchHPlanchets(
- planchets,
- coin.coinSource.coinIndex,
- numCoins,
- );
- if (!hPlanchets) {
+ const proof = proofs.get(coin.coinPub);
+ if (!proof) {
throw makeTransactionActionUnsupportedError(
this.transactionId,
"delete",
- "withdrawal source material is still needed for recoup",
+ "withdrawal batch material is still needed for recoup",
);
}
- coin.coinSource.hPlanchets = hPlanchets;
+ source.recoupBatch = proof;
+ source.hPlanchets = proof.commitment;
await tx.upsertCoin(coin);
}
for (const p of planchets) {
@@ -1845,6 +1837,14 @@ export function reconstructWithdrawalBatchHPlanchets(
coinIndex: number,
numCoins: number,
): string | undefined {
+ return legacyWithdrawalCommitments(planchets, numCoins).get(coinIndex);
+}
+
+function legacyWithdrawalCommitments(
+ planchets: WalletPlanchet[],
+ numCoins: number,
+) {
+ const result = new Map<number, string>();
const byIndex = new Map(planchets.map((x) => [x.coinIdx, x]));
const maxBatchSize = 64;
for (let start = 0; start < numCoins; ) {
@@ -1861,26 +1861,22 @@ export function reconstructWithdrawalBatchHPlanchets(
}
}
const end = Math.min(start + batchSize, numCoins);
- if (coinIndex >= start && coinIndex < end) {
- const batch = planchets
- .filter(
- (x) =>
- x.coinIdx >= start &&
- x.coinIdx < end &&
- x.planchetStatus !== PlanchetStatus.AbortedReplaced,
- )
- .sort((a, b) => a.coinIdx - b.coinIdx);
- if (!batch.some((x) => x.coinIdx === coinIndex)) {
- return undefined;
- }
- return hashWithdrawalPlanchets(
- batch.map((x) => x.coinEv),
- batch.map((x) => x.denomPubHash),
+ const batch: WalletPlanchet[] = [];
+ for (let i = start; i < end; i++) {
+ const p = byIndex.get(i);
+ if (p && p.planchetStatus !== PlanchetStatus.AbortedReplaced)
+ batch.push(p);
+ }
+ if (batch.length) {
+ const commitment = hashWithdrawalPlanchets(
+ batch.map((p) => p.coinEv),
+ batch.map((p) => p.denomPubHash),
);
+ for (const p of batch) result.set(p.coinIdx, commitment);
}
start = end;
}
- return undefined;
+ return result;
}
export function requireWithdrawalBatchCardinality(
@@ -3395,6 +3391,79 @@ function findWithdrawalBatches(
return matches;
}
+/** Rebuild one ordered envelope list per legacy withdrawal commitment. */
+export function reconstructWithdrawalRecoupBatches(
+ coins: WalletCoin[],
+ group: WalletWithdrawalGroup | undefined,
+ planchets: WalletPlanchet[],
+) {
+ const proofs = new Map<
+ string,
+ NonNullable<WalletWithdrawCoinSource["recoupBatch"]>
+ >();
+ const members = new Map<
+ string,
+ {
+ coinPub: string;
+ index: number;
+ envelopeHash: string;
+ needsProof: boolean;
+ }[]
+ >();
+ let inferred: Map<number, string> | undefined;
+ for (const coin of coins) {
+ const source = coin.coinSource;
+ if (source.type !== CoinSourceType.Withdraw) continue;
+ let commitment = source.hPlanchets ?? source.recoupBatch?.commitment;
+ if (
+ !commitment &&
+ group?.denomsSel &&
+ !group.denomsSel.selectedDenoms.some((d) => d.skip)
+ ) {
+ inferred ??= legacyWithdrawalCommitments(
+ planchets,
+ group.denomsSel.selectedDenoms.reduce((n, d) => n + d.count, 0),
+ );
+ commitment = inferred.get(source.coinIndex);
+ }
+ if (!commitment) continue;
+ const batch = members.get(commitment) ?? [];
+ batch.push({
+ coinPub: coin.coinPub,
+ index: source.coinIndex,
+ envelopeHash: coin.coinEvHash,
+ needsProof: !source.recoupBatch,
+ });
+ members.set(commitment, batch);
+ }
+ let originals: Map<string, WalletPlanchet[]> | undefined;
+ for (const [commitment, batch] of members) {
+ if (!batch.some((c) => c.needsProof)) continue;
+ batch.sort((a, b) => a.index - b.index);
+ let coinPubs = batch.map((c) => c.coinPub);
+ let envelopeHashes = batch.map((c) => c.envelopeHash);
+ const hc = createHashContext();
+ for (const h of envelopeHashes) hc.update(decodeCrock(h));
+ if (encodeCrock(hc.finish()) !== commitment) {
+ // The surviving coins alone do not account for this batch. Try the
+ // original planchets if the withdrawal history is still available.
+ originals ??= findWithdrawalBatches(planchets, new Set(members.keys()));
+ const original = originals.get(commitment);
+ if (!original) continue;
+ coinPubs = original.map((p) => p.coinPub);
+ envelopeHashes = original.map((p) =>
+ encodeCrock(hashCoinEv(p.coinEv, p.denomPubHash)),
+ );
+ }
+ for (const c of batch) {
+ const coinIndex = coinPubs.indexOf(c.coinPub);
+ if (coinIndex >= 0 && envelopeHashes[coinIndex] === c.envelopeHash)
+ proofs.set(c.coinPub, { commitment, coinIndex, envelopeHashes });
+ }
+ }
+ return proofs;
+}
+
/** Upgrade old worklists without guessing a possibly already debited request. */
export async function restoreWithdrawalBatches(
wex: WalletExecutionContext,