taler-typescript-core

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

commit 340231965e15267e551da79503f0ce7b8e173350
parent 034c94bf06a4c478184efaafd7a79b88719e92a8
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 19:51:55 +0100

wallet-core: recover scheduled refreshes after an interrupted melt

Use the saved melt confirmation to resume the reveal. If a retry is
rejected and there's no saved confirmation, check the coin history
before giving up on the original melt.

Diffstat:
Mpackages/taler-wallet-core/src/autoRefreshLifecycle.test.ts | 259++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/db/records.ts | 4+++-
Mpackages/taler-wallet-core/src/refresh.ts | 323+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
3 files changed, 453 insertions(+), 133 deletions(-)

diff --git a/packages/taler-wallet-core/src/autoRefreshLifecycle.test.ts b/packages/taler-wallet-core/src/autoRefreshLifecycle.test.ts @@ -33,8 +33,10 @@ import { RefreshCoinStatus, timestampProtocolToDb, WalletCoin, + WalletCoinAvailability, WalletDenomination, WalletExchangeEntry, + WalletRefreshMeltConfirmation, WalletRefreshGroup, WalletRefreshSession, } from "./db/records.js"; @@ -177,23 +179,61 @@ function meltFixture() { const headers = new HeadersImpl(); headers.set("content-type", "application/json"); const replies = new Map<string, { status: number; body: unknown }>(); - const controls = { blocked: false }; + const controls = { blocked: false, validHistory: true }; const exchangeBaseUrl = old.exchangeBaseUrl; session.sessionPublicSeed = "seed"; session.amountRefreshOutput = output.value; rg.expectedOutputPerCoin = [output.value]; rg.refundRequests = {}; let storedSession: WalletRefreshSession | undefined = session; + const freshCoins = new Map<string, WalletCoin>(); + const availability: WalletCoinAvailability = { + ...output, + maxAge: 0, + freshCoinCount: 0, + hasFreshCoins: 0, + visibleCoinCount: 0, + pendingRefreshOutputCount: 1, + }; + const availabilities = new Map([[output.denomPubHash, availability]]); + const denominations = new Map([ + [old.denomPubHash, old], + [output.denomPubHash, output], + ]); Object.assign(tx, { getExchangeBaseUrlFixup: async () => undefined, getExchangeDetailsByPointer: async () => ({ wireInfo: { accounts: [] } }), getConfig: async () => ({ value: controls.blocked }), getDenomination: async (ref: WalletDenomination) => - ref.denomPubHash === old.denomPubHash ? old : output, + denominations.get(ref.denomPubHash), + getDenominationsByMasterPub: async () => [...denominations.values()], getRefreshSession: async () => structuredClone(storedSession), upsertRefreshSession: async (next: WalletRefreshSession) => { storedSession = Object.assign(storedSession ?? {}, next); }, + deleteRefreshSession: async () => { + storedSession = undefined; + }, + getCoinAvailability: async (ref: WalletCoinAvailability) => + availabilities.get(ref.denomPubHash), + upsertCoinAvailability: async (row: WalletCoinAvailability) => + availabilities.set(row.denomPubHash, row), + getCoinAvailabilitiesByRefs: async (refs: WalletCoinAvailability[]) => + refs.flatMap((ref) => availabilities.get(ref.denomPubHash) ?? []), + getCoinsByPubs: async (pubs: string[]) => + [...freshCoins.values()].filter((c) => pubs.includes(c.coinPub)), + getCoinsBySourceTransaction: async () => [...freshCoins.values()], + upsertCoin: async (c: WalletCoin) => freshCoins.set(c.coinPub, c), + getRefreshMeltConfirmation: async () => undefined, + upsertRefreshMeltConfirmation: async () => {}, + getExchangeDetails: async () => ({ rowId: 1 }), + getExchangeSignKeysByDetailsRowId: async () => [ + { + signkeyPub: "online", + stampStart: output.stampStart, + stampExpire: output.stampExpireDeposit, + }, + ], upsertTransactionMeta: async () => {}, }); Object.assign(wex.ws, { @@ -221,6 +261,14 @@ function meltFixture() { meltValueWithFee: Amounts.parseOrThrow(old.value), confirmSig: "signed", }), + signCoinHistoryRequest: async () => ({ sig: "history-signature" }), + isValidCoinHistory: async () => ({ valid: controls.validHistory }), + isValidMeltConfirmation: async () => ({ valid: true }), + unblindDenominationSignature: async () => ({ + cipher: DenomKeyType.Rsa, + rsa_signature: "sig", + }), + verifyDenominationSignature: async () => ({ valid: true }), }, http: { fetch: async (url: string) => { @@ -242,10 +290,18 @@ function meltFixture() { status: 410, body: { code: TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED }, }); + replies.set("/reveal-melt", { + status: 200, + body: { + ev_sigs: [{ cipher: DenomKeyType.Rsa, blinded_rsa_signature: "sig" }], + }, + }); return { ...f, controls, replies, + denominations, + freshCoins, requests, rc, run: () => processRefreshGroup(wex, rg.refreshGroupId), @@ -280,6 +336,205 @@ test("a legacy unseeded scheduled refresh can replace denominations after its fi assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.PendingRedenominate); }); +test("a scheduled melt interrupted after commit can finish when the exchange has never seen the coin", async () => { + const { + session, + rg, + tx, + wex, + requests, + replies, + denominations, + old, + output, + freshCoins, + run, + } = meltFixture(); + const transact = wex.runWalletDbTx; + wex.runWalletDbTx = async (work) => { + const result = await work(tx); + if (session.autoRefreshMeltStarted) + throw Error("simulated shutdown after commit"); + return result; + }; + await assert.rejects(run(), /simulated shutdown/); + assert.equal(session.autoRefreshMeltStarted, true); + assert.deepEqual(requests, []); + wex.runWalletDbTx = transact; + const replacement = { ...output, denomPubHash: "replacement" }; + output.stampExpireWithdraw = old.stampExpireWithdraw; + denominations.set(replacement.denomPubHash, replacement); + replies.set("/coins/coin/history", { + status: 404, + body: { code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN }, + }); + await run(); + assert.deepEqual(requests, ["/melt", "/coins/coin/history"]); + assert.equal(session.autoRefreshMeltStarted, false); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.PendingRedenominate); + replies.set("/melt", { + status: 200, + body: { noreveal_index: 1, exchange_pub: "online", exchange_sig: "signed" }, + }); + await run(); + assert.deepEqual(requests, [ + "/melt", + "/coins/coin/history", + "/melt", + "/reveal-melt", + ]); + assert.equal(rg.operationStatus, RefreshOperationStatus.Finished); + assert.deepEqual( + [...freshCoins.values()].map((c) => c.denomPubHash), + [replacement.denomPubHash], + ); +}); + +function spentCoinHistory(denom: WalletDenomination, rc: string) { + return { + status: 200, + body: { + balance: "TEST:0", + h_denom_pub: denom.denomPubHash, + history: [ + { + type: "MELT", + rc, + amount: denom.value, + melt_fee: "TEST:0", + history_offset: 0, + h_denom_pub: denom.denomPubHash, + coin_sig: "signed", + noreveal_index: 2, + }, + ], + }, + }; +} + +test("a seeded legacy retry retains a reported melt until the exchange signs the reveal index", async () => { + const { session, rg, old, rc, replies, requests, freshCoins, run } = + meltFixture(); + delete session.autoRefreshMeltStarted; + const path = "/coins/coin/history"; + replies.set(path, spentCoinHistory(old, rc.toLowerCase())); + await run(); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.Pending); + assert.equal(session.norevealIndex, undefined); + assert.equal(session.sessionPublicSeed, "seed"); + assert.deepEqual(requests, ["/melt", path]); + // The exchange later omits the same debit. + replies.set(path, { + status: 200, + body: { balance: old.value, h_denom_pub: old.denomPubHash, history: [] }, + }); + await run(); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.Pending); + replies.set("/melt", { + status: 200, + body: { noreveal_index: 1, exchange_pub: "online", exchange_sig: "signed" }, + }); + await run(); + assert.equal(session.norevealIndex, 1); + assert.equal(rg.operationStatus, RefreshOperationStatus.Finished); + assert.equal(freshCoins.size, 1); +}); + +test("a scheduled retry fails for insufficient funds only when verified history shows the coin was spent", async () => { + const { session, rg, old, replies, controls, run } = meltFixture(); + session.autoRefreshMeltStarted = true; + replies.set("/melt", { + status: 409, + body: { code: TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS }, + }); + const path = "/coins/coin/history"; + replies.set(path, { + status: 404, + body: { code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN }, + }); + await run(); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.Pending); + replies.set(path, { + status: 200, + body: { balance: old.value, h_denom_pub: old.denomPubHash, history: [] }, + }); + await run(); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.Pending); + replies.set( + path, + spentCoinHistory(old, encodeCrock(new Uint8Array(64).fill(11))), + ); + controls.validHistory = false; + await run(); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.Pending); + controls.validHistory = true; + await run(); + assert.equal(rg.operationStatus, RefreshOperationStatus.Failed); + assert.equal(rg.expectedOutputPerCoin[0], "TEST:0"); +}); + +test("a scheduled retry settles an unknown coin only when its history also returns coin unknown", async () => { + const { session, rg, old, replies, run } = meltFixture(); + session.autoRefreshMeltStarted = true; + const missing = { + status: 404, + body: { code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN }, + }; + replies.set("/melt", missing); + const path = "/coins/coin/history"; + replies.set(path, { + status: 200, + body: { balance: old.value, h_denom_pub: old.denomPubHash, history: [] }, + }); + await run(); + assert.equal(rg.statusPerCoin[0], RefreshCoinStatus.Pending); + replies.set(path, missing); + await run(); + assert.equal(rg.operationStatus, RefreshOperationStatus.Failed); + assert.equal( + session.lastError?.code, + TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN, + ); +}); + +test("a scheduled refresh resumes reveal after the confirmed index could not be saved to the session", async () => { + const { session, rg, tx, old, rc, requests, replies, freshCoins, run } = + meltFixture(); + let pin: WalletRefreshMeltConfirmation | undefined; + tx.getRefreshMeltConfirmation = async (key) => { + assert.deepEqual(key, { + exchangeBaseUrl: old.exchangeBaseUrl, + refreshCommitment: rc, + }); + return pin; + }; + tx.upsertRefreshMeltConfirmation = async (record) => { + pin = record; + }; + const saveSession = tx.upsertRefreshSession; + tx.upsertRefreshSession = async (next) => { + if (next.norevealIndex !== undefined) + throw Error("interrupted session write"); + await saveSession(next); + }; + replies.set("/melt", { + status: 200, + body: { noreveal_index: 2, exchange_pub: "online", exchange_sig: "signed" }, + }); + await run(); + assert.equal(pin?.norevealIndex, 2); + assert.equal(session.norevealIndex, undefined); + assert.deepEqual(requests, ["/melt"]); + tx.upsertRefreshSession = saveSession; + await run(); + assert.deepEqual(requests, ["/melt", "/reveal-melt"]); + assert.equal(rg.operationStatus, RefreshOperationStatus.Finished); + assert.deepEqual( + [...freshCoins.keys()], + [encodeCrock(new Uint8Array(32).fill(2))], + ); +}); + test("pending and failed renewals retain risks; successful groups yield one dismissible notice", async () => { const { tx, wex, rg, ex } = fixture(); const getResponse = async () => { diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -412,6 +412,8 @@ export interface WalletRefreshGroup { dismissed?: boolean; recoveryInputs?: Record<string, AmountString>; recovery?: import("@gnu-taler/taler-util").CashRenewalNotice; + /** Commitments seen in verified coin history, indexed by input coin. */ + reportedMeltCommitments?: Record<number, HashCodeString>; }; transactionAmounts?: WalletTransactionAmounts; operationStatus: RefreshOperationStatus; @@ -472,7 +474,7 @@ export interface WalletRefreshGroup { export interface WalletRefreshSession { /** Original CS seed when recovering a refresh made by another wallet. */ blindingSeed?: string; - /** Once set, the melt may have reached the exchange; never change outputs. */ + /** The melt may have reached the exchange. Reconcile a rejection before changing outputs. */ autoRefreshMeltStarted?: boolean; refreshGroupId: string; diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -47,6 +47,7 @@ import { BlindedDenominationSignature, checkDbInvariant, checkLogicInvariant, + CoinHistoryResponse, CoinRefreshRequest, CoinStatus, DenominationInfo, @@ -75,6 +76,7 @@ import { Logger, makeErrorDetail, NotificationType, + OperationFail, RefreshPlanchetInfo, RefreshReason, succeedOrThrow, @@ -1391,135 +1393,194 @@ async function refreshMelt( const exchangeClient = walletExchangeClient(oldCoin.exchangeBaseUrl, wex, { timeout: getRefreshRequestTimeout(refreshGroup), }); - const submission = await wex.ws.runSequentialized( - [EXCHANGE_COINS_LOCK], - async () => { - await requireExchangeCoinUseConfirmedOrThrow( - wex, - oldCoin.exchangeBaseUrl, + // Keep recoup and other melt submissions from acting on this input between + // reading its history and applying a rejection to the session. + return wex.ws.runSequentialized([EXCHANGE_COINS_LOCK], async () => { + await requireExchangeCoinUseConfirmedOrThrow(wex, oldCoin.exchangeBaseUrl); + const submission = await wex.runWalletDbTx(async (tx) => { + // Recoup can claim or finish this input while the melt waits for the lock. + const rg = await tx.getRefreshGroup(refreshGroupId); + if ( + rg?.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending || + rg.recoupGroupPerCoin?.[coinIndex] + ) + return; + if ((await tx.getConfig(ConfigRecordKey.RefreshBlocked))?.value) + throw new RefreshBlockedError(); + const history = await tx.getCoinHistory(oldCoin.coinPub); + const allocation = history?.history.find( + (h) => h.type === "refresh" && h.transactionId === ctx.transactionId, ); - const attempt = await wex.runWalletDbTx(async (tx) => { - // Recoup can claim or finish this input while the melt waits for the lock. - const rg = await tx.getRefreshGroup(refreshGroupId); - if ( - rg?.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending || - rg.recoupGroupPerCoin?.[coinIndex] - ) - return; - if ((await tx.getConfig(ConfigRecordKey.RefreshBlocked))?.value) - throw new RefreshBlockedError(); - const history = await tx.getCoinHistory(oldCoin.coinPub); - const allocation = history?.history.find( - (h) => h.type === "refresh" && h.transactionId === ctx.transactionId, - ); - const attempt = - rg.reason === RefreshReason.Scheduled - ? await authorizeScheduledMelt( - wex, - tx, - rg, - coinIndex, - refreshSession, - !!allocation, - ) - : "ordinary"; - if (!attempt) return; - // Keep authorizations with the coin even after a session is replaced or deleted. - if ( - history && - allocation?.type === "refresh" && - allocation.meltSignatures && - !allocation.meltSignatures.includes(derived.confirmSig) - ) { - allocation.meltSignatures.push(derived.confirmSig); - await tx.upsertCoinHistory(history); - } - return attempt; - }); + const attempt = + rg.reason === RefreshReason.Scheduled + ? await authorizeScheduledMelt( + wex, + tx, + rg, + coinIndex, + refreshSession, + !!allocation, + ) + : "ordinary"; if (!attempt) return; + // Keep authorizations with the coin even after a session is replaced or deleted. + if ( + history && + allocation?.type === "refresh" && + allocation.meltSignatures && + !allocation.meltSignatures.includes(derived.confirmSig) + ) { + allocation.meltSignatures.push(derived.confirmSig); + await tx.upsertCoinHistory(history); + } + const pin = + attempt === "retry" + ? await tx.getRefreshMeltConfirmation({ + exchangeBaseUrl: oldCoin.exchangeBaseUrl, + refreshCommitment: derived.hash, + }) + : undefined; return { attempt, - resp: await exchangeClient.postMelt({ body: meltReqBody }), + pin, + reportedMelt: + rg.autoRefresh?.reportedMeltCommitments?.[coinIndex] === derived.hash, }; - }, - ); - - if (!submission) return false; - const { attempt, resp } = submission; - if (attempt === "retry" && resp.case !== "ok") { - // A previous attempt may have succeeded. An error on a later retry does - // not establish that its outputs can safely be discarded or replaced. - throwUnexpectedRequestError(resp.response, resp.detail!); - } - switch (resp.case) { - case HttpStatusCode.NotFound: - await handleRefreshMeltNotFound( - ctx, - coinIndex, - resp.response, - resp.detail!, - ); - return false; - case HttpStatusCode.Gone: - await handleRefreshMeltGone( - ctx, - coinIndex, - resp.detail!, - attempt === "first", - ); - return false; - case HttpStatusCode.Conflict: - await handleRefreshMeltConflict( - ctx, - refreshGroup, - coinIndex, - resp.detail!, - derived.meltValueWithFee, - oldCoin, - ); - return false; - case "ok": - break; - default: - throwUnexpectedRequestError(resp.response, resp.detail!); - } + }); + if (!submission) return false; + // A crash may have interrupted the session update after the signed + // exchange confirmation was verified and its no-reveal index pinned. + if (submission.pin) return saveMeltIndex(submission.pin.norevealIndex); + + const resp = await exchangeClient.postMelt({ body: meltReqBody }); + const verifiedHistory = + submission.attempt === "retry" && resp.case !== "ok" + ? await reconcileRejectedRetry(resp, submission.reportedMelt) + : undefined; + switch (resp.case) { + case HttpStatusCode.NotFound: + await handleRefreshMeltNotFound( + ctx, + coinIndex, + resp.response, + resp.detail!, + ); + return false; + case HttpStatusCode.Gone: + await handleRefreshMeltGone(ctx, coinIndex, resp.detail!); + return false; + case HttpStatusCode.Conflict: + await handleRefreshMeltConflict( + ctx, + refreshGroup, + coinIndex, + resp.detail!, + derived.meltValueWithFee, + oldCoin, + verifiedHistory, + ); + return false; + case "ok": + break; + default: + throwUnexpectedRequestError(resp.response, resp.detail!); + } - const meltResponse = resp.body; - const norevealIndex = meltResponse.noreveal_index; - requireValidNorevealIndex(norevealIndex, derived.planchets.length); + const meltResponse = resp.body; + await requireValidMeltConfirmation( + wex, + oldCoin.exchangeBaseUrl, + derived.hash, + meltResponse, + ); - await requireValidMeltConfirmation( - wex, - oldCoin.exchangeBaseUrl, - derived.hash, - meltResponse, - ); + return saveMeltIndex(meltResponse.noreveal_index); + }); - refreshSession.norevealIndex = norevealIndex; + // A rejection describes this submission. Check whether an earlier one + // reached the exchange before replacing or failing its commitment. + async function reconcileRejectedRetry( + resp: OperationFail<HttpStatusCode>, + reportedMelt: boolean, + ): Promise<CoinHistoryResponse | undefined> { + const code = resp.detail?.code; + const canReconcile = + (resp.case === HttpStatusCode.Gone && + (code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED || + code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED)) || + (resp.case === HttpStatusCode.Conflict && + code === TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS) || + (resp.case === HttpStatusCode.NotFound && + (code === TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN || + code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN)); + if (reportedMelt || !canReconcile) + throwUnexpectedRequestError(resp.response, resp.detail!); - return await wex.runWalletDbTx(async (tx) => { - const rg = await tx.getRefreshGroup(refreshGroupId); - if (!rg) { - return false; - } - if (rg.timestampFinished) { - return false; - } - if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) { - return false; + const history = await readVerifiedCoinHistory(wex, oldCoin, oldDenom); + if (history.case !== "ok") { + // A missing coin cannot substantiate an insufficient-funds conflict. + if (resp.case === HttpStatusCode.Conflict) + throwUnexpectedRequestError(resp.response, resp.detail!); + return undefined; } - const rs = await tx.getRefreshSession(refreshGroupId, coinIndex); - if (!rs) { - return false; + if ( + history.body.history.some( + (h) => + h.type === "MELT" && encodeCrock(decodeCrock(h.rc)) === derived.hash, + ) + ) { + // History authenticates the commitment, but only the signed melt + // confirmation authenticates the index needed for reveal. Keep the + // commitment even if the exchange later omits this debit. + await wex.runWalletDbTx(async (tx) => { + const rg = await tx.getRefreshGroup(refreshGroupId); + const rs = await tx.getRefreshSession(refreshGroupId, coinIndex); + if ( + rg?.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending || + rs?.sessionPublicSeed !== refreshSession.sessionPublicSeed + ) + return; + const state = (rg.autoRefresh ??= {}); + (state.reportedMeltCommitments ??= {})[coinIndex] = derived.hash; + await tx.upsertRefreshGroup(rg); + }); + throwUnexpectedRequestError(resp.response, resp.detail!); } - if (rs.norevealIndex !== undefined) { + if ( + code === TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN || + (resp.case === HttpStatusCode.Conflict && + Amounts.cmp(history.body.balance, derived.meltValueWithFee) >= 0) + ) + throwUnexpectedRequestError(resp.response, resp.detail!); + return history.body; + } + + async function saveMeltIndex(norevealIndex: number): Promise<boolean> { + requireValidNorevealIndex(norevealIndex, derived.planchets.length); + return await wex.runWalletDbTx(async (tx) => { + const rg = await tx.getRefreshGroup(refreshGroupId); + if (!rg) { + return false; + } + if (rg.timestampFinished) { + return false; + } + if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) { + return false; + } + const rs = await tx.getRefreshSession(refreshGroupId, coinIndex); + if (!rs || rs.sessionPublicSeed !== refreshSession.sessionPublicSeed) { + return false; + } + if (rs.norevealIndex !== undefined) { + return true; + } + rs.norevealIndex = norevealIndex; + await tx.upsertRefreshSession(rs); + await wakePurseResiduals(wex, tx, rg, [rg.oldCoinPubs[coinIndex]]); return true; - } - rs.norevealIndex = norevealIndex; - await tx.upsertRefreshSession(rs); - await wakePurseResiduals(wex, tx, rg, [rg.oldCoinPubs[coinIndex]]); - return true; - }); + }); + } } export function requireValidNorevealIndex(index: number, kappa: number): void { @@ -1561,7 +1622,6 @@ async function handleRefreshMeltGone( ctx: RefreshTransactionContext, coinIndex: number, errDetails: TalerErrorDetail, - firstAutoMeltAttempt: boolean, ): Promise<void> { // const expiredMsg = codecForDenominationExpiredMessage().decode(errDetails); @@ -1594,9 +1654,8 @@ async function handleRefreshMeltGone( throw Error("db invariant failed: missing refresh session in database"); } refreshSession.lastError = errDetails; - // This first attempt was definitively rejected; no ambiguous earlier - // request needs this commitment. Allow selection of replacement keys. - if (firstAutoMeltAttempt) refreshSession.autoRefreshMeltStarted = false; + if (rg.reason === RefreshReason.Scheduled) + refreshSession.autoRefreshMeltStarted = false; await tx.upsertRefreshSession(refreshSession); await h.update(rg, "melt-gone"); }); @@ -1663,6 +1722,7 @@ export async function handleRefreshMeltConflict( errDetails: TalerErrorDetail, meltValueWithFee: AmountLike, oldCoin: WalletCoin, + verifiedHistory?: CoinHistoryResponse, ): Promise<void> { // Just log for better diagnostics here, error status // will be handled later. @@ -1682,14 +1742,17 @@ export async function handleRefreshMeltConflict( if (result !== "refused") return; } - const denomination = await ctx.wex.runWalletDbTx(async (tx) => { - const denom = await getDenomInfo(ctx.wex, tx, oldCoin); - checkDbInvariant(!!denom, "missing denomination for history recovery"); - return denom; - }); - const history = succeedOrThrow( - await readVerifiedCoinHistory(ctx.wex, oldCoin, denomination), - ); + if (!verifiedHistory) { + const denomination = await ctx.wex.runWalletDbTx(async (tx) => { + const denom = await getDenomInfo(ctx.wex, tx, oldCoin); + checkDbInvariant(!!denom, "missing denomination for history recovery"); + return denom; + }); + verifiedHistory = succeedOrThrow( + await readVerifiedCoinHistory(ctx.wex, oldCoin, denomination), + ); + } + const history = verifiedHistory; const correctedBalance = history.balance; await ctx.wex.runWalletDbTx(async (tx) => { @@ -2887,12 +2950,12 @@ async function applyRefreshToOldCoins( } histEntry.history.push({ type: "refresh", - meltSignatures: [], transactionId: constructTransactionIdentifier({ tag: TransactionType.Refresh, refreshGroupId, }), amount: Amounts.stringify(request.amount), + meltSignatures: [], }); historiesByPub.set(coin.coinPub, histEntry); changedHistories.set(coin.coinPub, histEntry);