taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit eecab0595f5e8fb5ea54cdeecc6686b07d71aca0
parent 1fd9c5be927d7bd527cb7727877ebcc72b33d3cc
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 19:57:37 +0100

wallet withdrawal: replace CS keys rejected during preparation

Reselect the unissued value after a permanent denomination error.
Replay outstanding batches first and keep the reserve pending until
an affordable replacement is available.

Diffstat:
Mpackages/taler-wallet-core/src/db/records.ts | 4+++-
Mpackages/taler-wallet-core/src/testing-recover-coins.test.ts | 231++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/withdraw.ts | 185++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
3 files changed, 365 insertions(+), 55 deletions(-)

diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -798,8 +798,10 @@ export interface WalletWithdrawalGroup { * Denominations selected for withdrawal. */ denomsSel?: DenomSelectionState & { - /** Legacy replacements must be reselected after replaying a recovered debit. */ + /** Replay outstanding batches before replacing the remaining selection. */ requiresReselection?: boolean; + /** Denominations the exchange permanently rejected during preparation. */ + rejectedPrepareDenoms?: string[]; }; abortReason?: TalerErrorDetail; diff --git a/packages/taler-wallet-core/src/testing-recover-coins.test.ts b/packages/taler-wallet-core/src/testing-recover-coins.test.ts @@ -26,6 +26,7 @@ import { AmountString, Amounts, BlindedDenominationSignature, + Cache, CancellationToken, CoinEnvelope, CoinHistoryResponse, @@ -38,11 +39,13 @@ import { DenomKeyType, deriveCsNonce, deriveCsRefreshBlindingSeed, + Duration, eddsaGetPublic, encodeCrock, ExchangeWithdrawValue, getRandomBytes, hash, + hashDenomPub, stringToBytes, NotificationType, RefreshReason, @@ -57,6 +60,7 @@ import { HttpRequestLibrary, HttpResponse } from "@gnu-taler/taler-util/http"; import { WalletExecutionContext } from "./wallet.js"; import { testingRecoverCoins } from "./testing-recover-coins.js"; import { processRefreshGroup } from "./refresh.js"; +import { processWithdrawalGroup } from "./withdraw.js"; import { CoinSourceType, DenominationVerificationStatus, @@ -69,11 +73,14 @@ import { WalletDenomination, WalletExchangeDetails, WalletExchangeEntry, + WalletWithdrawalGroup, + WithdrawalGroupStatus, + WithdrawalRecordType, } from "./db/records.js"; import { WalletDbHandle } from "./db/handle.js"; import { runnerFactories } from "./db/testing/runners.js"; import { handleCancelProgressToken } from "./progress.js"; -import { nativeCryptoR } from "./crypto/cryptoImplementation.js"; +import { nativeCrypto, nativeCryptoR } from "./crypto/cryptoImplementation.js"; const url = "https://exchange.test/"; const a = (value: string): AmountString => `TESTKUDOS:${value}` as AmountString; @@ -674,7 +681,229 @@ async function localRefresh(f: Awaited<ReturnType<typeof fixture>>) { }; } +/** A funded reserve and a signing exchange, with control over key rotation. */ +async function localWithdrawal( + f: Awaited<ReturnType<typeof fixture>>, + sibling = false, +) { + const id = "cs-withdrawal"; + const reservePriv = k("withdrawal reserve"); + const cs = signer.csDenomPub(); + const rsa = signer.rsaDenomPub(); + const csHash = encodeCrock(hashDenomPub(cs)); + const rsaHash = encodeCrock(hashDenomPub(rsa)); + async function offer(key: DenominationPubKey, value = "1") { + const d = denom(value); + d.denomPub = key; + d.denomPubHash = encodeCrock(hashDenomPub(key)); + // The refused key would otherwise be chosen again as the first family member. + if (d.denomPubHash === csHash) + d.stampExpireWithdraw = stamp(d.stampExpireWithdraw - 1000000); + await f.db.runReadWriteTx(async (tx) => { + const params = { + exchangeBaseUrl: url, + exchangeMasterPub: master, + value: d.value, + ...d.fees, + }; + const family = await tx.getDenominationFamilyByParams(params); + d.denominationFamilySerial = + family?.denominationFamilySerial ?? + (await tx.upsertDenominationFamily({ familyParams: params })); + await tx.upsertDenomination(d); + }); + } + await offer(cs); + if (sibling) await offer(rsa); + const amount = sibling ? a("2") : a("1"); + const group: WalletWithdrawalGroup = { + withdrawalGroupId: id, + wgInfo: { withdrawalType: WithdrawalRecordType.BankManual }, + secretSeed: k("withdrawal seed"), + reservePriv, + reservePub: encodeCrock(eddsaGetPublic(decodeCrock(reservePriv))), + exchangeBaseUrl: url, + timestampStart: timestampPreciseToDb({ t_s: 1 }), + status: WithdrawalGroupStatus.PendingReady, + instructedAmount: amount, + reserveBalanceAmount: amount, + rawWithdrawalAmount: amount, + effectiveWithdrawalAmount: amount, + denomsSel: { + selectedDenoms: [{ denomPubHash: sibling ? rsaHash : csHash, count: 1 }], + totalCoinValue: a("1"), + totalWithdrawCost: a("1"), + hasDenomWithAgeRestriction: false, + }, + batches: [], + }; + await f.db.runReadWriteTx((tx) => tx.upsertWithdrawalGroup(group)); + let updates = 0; + let nextKey: DenominationPubKey | undefined; + async function exchangeReady() { + await f.db.runReadWriteTx(async (tx) => { + const exchange = (await tx.getExchange(url))!; + exchange.updateStatus = ExchangeEntryDbUpdateStatus.Ready; + exchange.nextUpdateStamp = timestampPreciseToDb({ t_s: 4000000000 }); + await tx.upsertExchange(exchange); + }); + } + await exchangeReady(); + Object.assign(f.wex.ws, { + exchangeCache: new Cache(5, Duration.fromSpec({ minutes: 5 })), + addFdr() {}, + notifyInternal() {}, + addNotificationListener: () => () => {}, + }); + Object.assign(f.wex, { + cryptoApi: nativeCrypto, + taskScheduler: { + ensureRunning() {}, + startShepherdTask() {}, + async resetTask() { + updates++; + if (nextKey) { + await offer(nextKey); + nextKey = undefined; + } + await exchangeReady(); + }, + }, + }); + // The exchange debits each distinct signed batch once even when its response + // is lost. Keep its requests so the test can compare the complete replay. + const charges = new Set<string>(); + let loseResponse = sibling; + f.replies.set("withdraw", (body) => { + charges.add(JSON.stringify(body)); + if (loseResponse) { + loseResponse = false; + throw Error("lost withdrawal response"); + } + return { status: 200, body: { ev_sigs: body.coin_evs.map(signer.sign) } }; + }); + const run = () => processWithdrawalGroup(f.wex, id); + const read = async () => + (await f.db.runReadWriteTx((tx) => tx.getWithdrawalGroup(id)))!; + if (sibling) { + await run(); + const submitted = await read(); + assert.equal(submitted.batches?.[0].state, "submitted"); + // Resume a selection with both a submitted batch and a still unprepared slot. + submitted.denomsSel!.selectedDenoms.push({ + denomPubHash: csHash, + count: 1, + }); + submitted.denomsSel!.totalCoinValue = + submitted.denomsSel!.totalWithdrawCost = amount; + await f.db.runReadWriteTx((tx) => tx.upsertWithdrawalGroup(submitted)); + } + return { + run, + read, + offer, + rsa, + rsaHash, + csHash, + charges, + publishOnUpdate: (key: DenominationPubKey) => { + nextKey = key; + }, + updates: () => updates, + }; +} + for (const makeDb of runnerFactories) { + for (const [status, code] of [ + [410, TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED], + [410, TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED], + [404, TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN], + ] as const) { + test(`${makeDb.name}: funded withdrawal replaces a CS preparation rejected with ${code}`, async (t) => { + const { f, reopen } = await persistentFixture(t, makeDb); + const sibling = + code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED; + const w = await localWithdrawal(f, sibling); + f.replies.set("blinding-prepare", () => ({ status, body: { code } })); + await w.run(); + const pending = await w.read(); + assert.equal(pending.status, WithdrawalGroupStatus.PendingRedenominate); + assert.deepEqual(pending.denomsSel?.rejectedPrepareDenoms, [w.csHash]); + assert.equal(pending.denomsSel?.requiresReselection, true); + await reopen(); + if (code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED) { + await w.offer( + { + cipher: DenomKeyType.ClauseSchnorr, + age_mask: 0, + cs_public_key: signer.rPubs[0], + }, + "3", + ); + await assert.rejects(w.run(), /no affordable replacement/); + assert.equal( + (await w.read()).status, + WithdrawalGroupStatus.PendingRedenominate, + ); + assert.equal(w.charges.size, 0); + } + w.publishOnUpdate(w.rsa); + for ( + let i = 0; + i < 4 && (await w.read()).status !== WithdrawalGroupStatus.Done; + i++ + ) + await w.run(); + assert.equal((await w.read()).status, WithdrawalGroupStatus.Done); + assert.ok(w.updates() >= 1); + const posts = f.requests.filter((r) => r.path === "withdraw"); + if (sibling) assert.deepEqual(posts[0], posts[1]); + assert.equal(posts.length, sibling ? 3 : 1); + assert.equal(w.charges.size, sibling ? 2 : 1); + assert.equal( + f.requests.filter((r) => r.path === "blinding-prepare").length, + 1, + ); + const coins = ( + await f.db.runReadWriteTx((tx) => tx.listAllCoins()) + ).filter((c) => c.denomPubHash === w.rsaHash); + assert.equal(coins.length, sibling ? 2 : 1); + assert.ok(coins.every((c) => c.status === CoinStatus.Fresh && c.visible)); + }); + } + + test(`${makeDb.name}: temporary CS withdrawal preparation errors retry the original planchet`, async (t) => { + const f = await fixture(await makeDb()); + t.after(f.close); + const w = await localWithdrawal(f); + for (const [status, code] of [ + [412, TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_VALIDITY_IN_FUTURE], + [410, TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_VALIDITY_IN_FUTURE], + [500, TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN], + ]) { + f.replies.set("blinding-prepare", () => ({ status, body: { code } })); + await assert.rejects(w.run()); + assert.equal((await w.read()).status, WithdrawalGroupStatus.PendingReady); + } + f.fail("blinding-prepare"); + await assert.rejects(w.run()); + f.fail(); + f.replies.delete("blinding-prepare"); + assert.equal((await w.read()).denomsSel?.rejectedPrepareDenoms, undefined); + f.blindingPrepare(() => ({ cipher: "CS", r_pubs: [signer.rPubs] })); + await w.run(); + assert.equal((await w.read()).status, WithdrawalGroupStatus.Done); + const preparations = f.requests.filter( + (r) => r.path === "blinding-prepare", + ); + assert.equal(preparations.length, 5); + assert.ok( + preparations.every((r) => r.body.seed === preparations[0].body.seed), + ); + assert.equal(w.charges.size, 1); + assert.equal(w.updates(), 0); + }); + for (const interrupted of ["melt", "reveal-melt"]) { test(`${makeDb.name}: resume CS refresh after losing the ${interrupted} response`, async (t) => { const { f, reopen } = await persistentFixture(t, makeDb); diff --git a/packages/taler-wallet-core/src/withdraw.ts b/packages/taler-wallet-core/src/withdraw.ts @@ -164,11 +164,13 @@ import { } from "./db/records.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { + sameSelectedDenoms, selectForcedWithdrawalDenominations, selectWithdrawalDenominations, } from "./denomSelection.js"; import { isCandidateWithdrawableDenomRec, + isDenominationUnavailable, isWithdrawableDenom, validateDenoms, } from "./denominations.js"; @@ -1209,6 +1211,8 @@ async function processWithdrawalGroupRedenominate( return wex.runWalletDbTx(async (tx) => { const [rec, h] = await ctx.getRecordHandle(tx); if (rec?.status === WithdrawalGroupStatus.PendingRedenominate) { + checkDbInvariant(!!rec.denomsSel, "missing withdrawal selection"); + rec.denomsSel.requiresReselection = true; rec.status = WithdrawalGroupStatus.PendingReady; await h.update(rec, "replay-ambiguous-batches"); } @@ -1616,7 +1620,11 @@ export async function getWithdrawableDenomsTx( tx: WalletDbTransaction, exchangeBaseUrl: string, currency: string, - options: { maxAmount?: AmountLike; ageMask?: number } = {}, + options: { + maxAmount?: AmountLike; + ageMask?: number; + excludeDenoms?: readonly string[]; + } = {}, ): Promise<WalletDenomination[]> { const { maxAmount, ageMask } = options; const dbNow = timestampProtocolToDb(TalerProtocolTimestamp.now()); @@ -1664,6 +1672,7 @@ export async function getWithdrawableDenomsTx( fpSerial, dbNow, (d) => + !options.excludeDenoms?.includes(d.denomPubHash) && (ageMask === undefined || d.denomPub.age_mask === ageMask) && isCandidateWithdrawableDenomRec(d), ); @@ -1698,6 +1707,21 @@ export async function getWithdrawableDenomsTx( return relevantDenoms; } +/** Find the active denomination at an absolute planchet index, accounting for retired slots. */ +function withdrawalDenomAtIndex( + selection: DenomSelectionState, + index: number, +): string | undefined { + for (const item of selection.selectedDenoms) { + if (index < item.count) + return index < item.count - (item.skip ?? 0) + ? item.denomPubHash + : undefined; + index -= item.count; + } + return undefined; +} + /** * Generate a planchet for a coin index in a withdrawal group. * Does not actually withdraw the coin yet. @@ -1709,7 +1733,7 @@ async function processPlanchetGenerate( wex: WalletExecutionContext, withdrawalGroup: WalletWithdrawalGroup, coinIdx: number, -): Promise<{ badDenom?: boolean }> { +): Promise<{ denomPubHash: string; rejectedByExchange: boolean } | undefined> { checkDbInvariant( withdrawalGroup.denomsSel !== undefined, "can't process uninitialized exchange", @@ -1719,36 +1743,20 @@ async function processPlanchetGenerate( "can't get funding uri from uninitialized wg", ); const exchangeBaseUrl = withdrawalGroup.exchangeBaseUrl; - let planchet = await wex.runWalletDbTx(async (tx) => { + const planchet = await wex.runWalletDbTx(async (tx) => { return tx.getPlanchetByGroupAndIndex( withdrawalGroup.withdrawalGroupId, coinIdx, ); }); if (planchet) { - return {}; - } - let ci = 0; - let isSkipped = false; - let maybeDenomPubHash: string | undefined; - for (let di = 0; di < withdrawalGroup.denomsSel.selectedDenoms.length; di++) { - const d = withdrawalGroup.denomsSel.selectedDenoms[di]; - if (coinIdx >= ci && coinIdx < ci + d.count) { - maybeDenomPubHash = d.denomPubHash; - if (coinIdx >= ci + d.count - (d.skip ?? 0)) { - isSkipped = true; - } - break; - } - ci += d.count; - } - if (isSkipped) { - return {}; - } - if (!maybeDenomPubHash) { - throw Error("invariant violated"); + return; } - const denomPubHash = maybeDenomPubHash; + const denomPubHash = withdrawalDenomAtIndex( + withdrawalGroup.denomsSel, + coinIdx, + ); + if (!denomPubHash) return; const denom = await wex.runWalletDbTx(async (tx) => { return getDenomInfo(wex, tx, { @@ -1758,7 +1766,7 @@ async function processPlanchetGenerate( }); if (!denom) { // We handle this gracefully, to fix previous bugs that made it into production. - return { badDenom: true }; + return { denomPubHash, rejectedByExchange: false }; } let exchangeWithdrawValues; let csNonce: string | undefined; @@ -1768,16 +1776,17 @@ async function processPlanchetGenerate( coinIdx, ); const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex); - const prep = succeedOrThrow( - await exchangeClient.postBlindingPrepare({ - body: { - cipher: DenomKeyType.ClauseSchnorr, - operation: "withdraw", - seed: encodeCrock(blindingSeed), - nks: [{ coin_offset: 0, denom_pub_hash: denomPubHash }], - }, - }), - ); + const response = await exchangeClient.postBlindingPrepare({ + body: { + cipher: DenomKeyType.ClauseSchnorr, + operation: "withdraw", + seed: encodeCrock(blindingSeed), + nks: [{ coin_offset: 0, denom_pub_hash: denomPubHash }], + }, + }); + if (response.case !== "ok" && isDenominationUnavailable(response)) + return { denomPubHash, rejectedByExchange: true }; + const prep = succeedOrThrow(response); checkProtocolInvariant( prep.r_pubs.length === 1, "exchange returned wrong number of Clause-Schnorr R-pairs", @@ -1822,13 +1831,22 @@ async function processPlanchetGenerate( coinIdx, ); if (p) { - planchet = p; return; } + const current = await tx.getWithdrawalGroup( + withdrawalGroup.withdrawalGroupId, + ); + if ( + !current?.denomsSel || + (current.status !== WithdrawalGroupStatus.PendingReady && + current.status !== WithdrawalGroupStatus.PendingKyc) || + current.denomsSel.requiresReselection || + withdrawalDenomAtIndex(current.denomsSel, coinIdx) !== denomPubHash + ) + return; await tx.upsertPlanchet(newPlanchet); - planchet = newPlanchet; }); - return {}; + return undefined; } interface WithdrawalRequestBatchArgs { @@ -2589,6 +2607,7 @@ export async function updateWithdrawalDenomsForCurrency( export async function updateWithdrawalDenomsForExchange( wex: WalletExecutionContext, exchangeBaseUrl: string, + excludeDenoms?: readonly string[], ): Promise<void> { logger.trace( `updating denominations used for withdrawal for ${exchangeBaseUrl}`, @@ -2621,7 +2640,9 @@ export async function updateWithdrawalDenomsForExchange( const dv = await tx.findDenominationByFamilyFromExpiry( fpSerial, dbNow, - isCandidateWithdrawableDenomRec, + (d) => + !excludeDenoms?.includes(d.denomPubHash) && + isCandidateWithdrawableDenomRec(d), ); if ( dv && @@ -3169,7 +3190,12 @@ export async function redenominateWithdrawal( exchangeBaseUrl: string, withdrawalGroupId: string, ): Promise<TaskRunResult> { - await updateWithdrawalDenomsForExchange(wex, exchangeBaseUrl); + const excluded = await wex.runWalletDbTx( + async (tx) => + (await tx.getWithdrawalGroup(withdrawalGroupId))?.denomsSel + ?.rejectedPrepareDenoms, + ); + await updateWithdrawalDenomsForExchange(wex, exchangeBaseUrl, excluded); logger.trace(`redenominating withdrawal group ${withdrawalGroupId}`); const ctx = new WithdrawTransactionContext(wex, withdrawalGroupId); @@ -3208,6 +3234,7 @@ export async function redenominateWithdrawal( tx, exchangeBaseUrl, currency, + { excludeDenoms: wg.denomsSel.rejectedPrepareDenoms }, ); const oldSel = wg.denomsSel; @@ -3233,6 +3260,8 @@ export async function redenominateWithdrawal( denominations.map((denom) => [denomRefKey(denom), denom]), ); const planchets = await tx.getPlanchetsByGroup(withdrawalGroupId); + if (withdrawalBatchesNeedReplay(wg.batches ?? [], planchets)) + return TaskRunResult.backoff(); const planchetsByIndex = new Map( planchets.map((planchet) => [planchet.coinIdx, planchet]), ); @@ -3252,7 +3281,10 @@ export async function redenominateWithdrawal( // must be replaced with fresh planchets. Reusing only some members // would keep them assigned to the rejected request forever. // Submitted batches have been replayed before entering this function. - denomOkay = wg.batches === undefined && isWithdrawableDenom(denom); + denomOkay = + wg.batches === undefined && + !oldSel.rejectedPrepareDenoms?.includes(denom.denomPubHash) && + isWithdrawableDenom(denom); const numCoins = sel.count - (sel.skip ?? 0); const denomValue = Amount.from(denom.value).mult(numCoins); @@ -3329,19 +3361,23 @@ export async function redenominateWithdrawal( coinIndex += sel.count; } - if (!remaining.isZero() && candidates.length === 0) { + const newSel = selectWithdrawalDenominations( + remaining.toJson(), + candidates, + ); + if ( + !remaining.isZero() && + (candidates.length === 0 || + (oldSel.rejectedPrepareDenoms?.length && + newSel.selectedDenoms.length === 0)) + ) { throw TalerError.fromDetail( TalerErrorCode.WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT, { exchangeBaseUrl }, - "no withdrawal denominations available during re-denomination", + "no affordable replacement withdrawal denomination is available", ); } - const newSel = selectWithdrawalDenominations( - remaining.toJson(), - candidates, - ); - if (logger.shouldLogTrace()) { logger.trace(`new denom sel: ${j2s(newSel)}`); } @@ -3358,6 +3394,8 @@ export async function redenominateWithdrawal( prevHasDenomWithAgeRestriction || newSel.hasDenomWithAgeRestriction, }; wg.denomsSel = mergedSel; + if (oldSel.rejectedPrepareDenoms) + wg.denomsSel.rejectedPrepareDenoms = oldSel.rejectedPrepareDenoms; if (logger.shouldLogTrace()) { logger.trace(`merged denom sel: ${j2s(mergedSel)}`); } @@ -3820,7 +3858,7 @@ async function processWithdrawalGroupPendingReady( // large withdrawal groups don't make the wallet unresponsive. for (let i = 0; !replayOnly && i < numTotalCoins; i++) { const res = await processPlanchetGenerate(wex, withdrawalGroup, i); - if (res.badDenom) { + if (res) { logger.warn( `redenomination required for withdrawal ${withdrawalGroupId}`, ); @@ -3828,7 +3866,7 @@ async function processWithdrawalGroupPendingReady( target: ctx.transactionId, event: FlightRecordEvent.WithdrawalRedenominate, }); - return startRedenomination(ctx, exchangeBaseUrl); + return startRedenomination(ctx, exchangeBaseUrl, { coinIdx: i, ...res }); } } @@ -3852,7 +3890,17 @@ async function processWithdrawalGroupPendingReady( ? await wex.runWalletDbTx(async (tx) => { const wg = await tx.getWithdrawalGroup(withdrawalGroupId); checkDbInvariant(!!wg, "withdrawal disappeared"); - if (replayOnly) return wg.batches ?? []; + if ( + (wg.status !== WithdrawalGroupStatus.PendingReady && + wg.status !== WithdrawalGroupStatus.PendingKyc) || + !sameSelectedDenoms( + wg.denomsSel?.selectedDenoms, + withdrawalGroup.denomsSel?.selectedDenoms, + ) + ) + return undefined; + if (replayOnly || wg.denomsSel?.requiresReselection) + return wg.batches ?? []; // A stored signature can prove acceptance only for its original // membership. Never include a paid legacy output in a fresh batch. const planchets = await tx.getPlanchetsByGroup(withdrawalGroupId); @@ -3882,6 +3930,7 @@ async function processWithdrawalGroupPendingReady( }), ); + if (!batches) return TaskRunResult.backoff(); for (const batch of batches) { if (batch.state === "rejected" || batch.state === "unresolved") continue; const args = { @@ -3977,7 +4026,12 @@ async function processWithdrawalGroupPendingReady( if ( (wg.timestampFinish === undefined || wg.status !== WithdrawalGroupStatus.Done) && - numActive === 0 + numActive === 0 && + !wg.denomsSel?.requiresReselection && + sameSelectedDenoms( + wg.denomsSel?.selectedDenoms, + withdrawalGroup.denomsSel?.selectedDenoms, + ) ) { wg.timestampFinish = timestampPreciseToDb(TalerPreciseTimestamp.now()); wg.status = WithdrawalGroupStatus.Done; @@ -4050,6 +4104,11 @@ export function withdrawalNeedsRedenomination( async function startRedenomination( ctx: WithdrawTransactionContext, exchangeBaseUrl: string, + unprepared?: { + coinIdx: number; + denomPubHash: string; + rejectedByExchange: boolean; + }, ): Promise<TaskRunResult> { // Exchange is broken. Mark exchange as unavailable and re-fetch // exchange entry. @@ -4067,6 +4126,26 @@ async function startRedenomination( default: return TaskRunResult.backoff(); } + if (unprepared) { + const sel = rec.denomsSel; + if ( + !sel || + withdrawalDenomAtIndex(sel, unprepared.coinIdx) !== + unprepared.denomPubHash || + (await tx.getPlanchetByGroupAndIndex( + rec.withdrawalGroupId, + unprepared.coinIdx, + )) + ) + return TaskRunResult.backoff(); + if (unprepared.rejectedByExchange) { + const rejected = (sel.rejectedPrepareDenoms ??= []); + if (!rejected.includes(unprepared.denomPubHash)) + rejected.push(unprepared.denomPubHash); + } + } + checkDbInvariant(!!rec.denomsSel, "missing withdrawal selection"); + rec.denomsSel.requiresReselection = true; rec.status = WithdrawalGroupStatus.PendingRedenominate; await h.update(rec, "start-redenomination"); return TaskRunResult.progress();