taler-typescript-core

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

commit 2b5703c041203f264f3f3b949f12f5269e0f70dd
parent 920f4f0aedfa9640ee401a6e17e8eb272ceb32a0
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 19:56:50 +0100

wallet refresh: save CS R-pairs before submitting a melt

Persist the pairs with the authorization for the same seed and ordered
outputs. A restarted wallet can reproduce the original commitment and
reveal its coins after the denomination stops signing.

Co-authored-by: Özgür Kesim <oec@codeblau.de>
Issue: https://bugs.taler.net/n/12286

Diffstat:
Mpackages/taler-wallet-core/src/denomSelection.ts | 19+++++++++++++++++++
Mpackages/taler-wallet-core/src/refresh.ts | 205++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
Mpackages/taler-wallet-core/src/testing-recover-coins.test.ts | 256++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
3 files changed, 392 insertions(+), 88 deletions(-)

diff --git a/packages/taler-wallet-core/src/denomSelection.ts b/packages/taler-wallet-core/src/denomSelection.ts @@ -28,6 +28,7 @@ import { AmountJson, Amounts, DenominationInfo, + DenomSelItem, DenomSelectionState, ForcedDenomSel, Logger, @@ -41,6 +42,24 @@ import { isWithdrawableDenom } from "./denominations.js"; const logger = new Logger("denomSelection.ts"); +/** Check that the same denominations still occupy the same planchet slots. */ +export function sameSelectedDenoms( + a: readonly DenomSelItem[] | undefined, + b: readonly DenomSelItem[] | undefined, +): boolean { + return ( + !!a && + !!b && + a.length === b.length && + a.every( + (item, i) => + item.denomPubHash === b[i].denomPubHash && + item.count === b[i].count && + (item.skip ?? 0) === (b[i].skip ?? 0), + ) + ); +} + /** * Exception to signal that a denomination that is intended * to be used has not been verified yet. diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -46,8 +46,10 @@ import { Amounts, assertUnreachable, BlindedDenominationSignature, + BlindingInputParameter, checkDbInvariant, checkLogicInvariant, + checkProtocolInvariant, CoinHistoryResponse, CoinRefreshRequest, CoinStatus, @@ -126,7 +128,10 @@ import { WalletRefreshGroup, WalletRefreshSession, } from "./db/records.js"; -import { selectWithdrawalDenominations } from "./denomSelection.js"; +import { + sameSelectedDenoms, + selectWithdrawalDenominations, +} from "./denomSelection.js"; import { fetchFreshExchange, getLegacyScopesForTransaction, @@ -786,6 +791,7 @@ interface DerivedRefreshCommon { hash: string; meltValueWithFee: AmountJson; blindingSeed?: string; + csRPubs?: [string, string][]; } type DerivedRefresh = @@ -896,7 +902,7 @@ export async function deriveRefreshSession( beforeBlindingRequest = checkRefreshAllowed, ): Promise<DerivedRefresh> { checkLogicInvariant(refreshSession.sessionPublicSeed != null); - const nks: { coin_offset: number; denom_pub_hash: string }[] = []; + const nks: BlindingInputParameter[] = []; let coinOffset = 0; for (const newDenom of newCoinDenoms) { for (let i = 0; i < newDenom.count; i++, coinOffset++) { @@ -909,6 +915,7 @@ export async function deriveRefreshSession( } } let blindingSeed: string | undefined; + let csRPubs = refreshSession.csRPubs; let exchangeWithdrawValues: (ExchangeWithdrawValue | undefined)[] | undefined; if (nks.length > 0) { blindingSeed = @@ -919,9 +926,9 @@ export async function deriveRefreshSession( decodeCrock(oldCoin.coinPriv), ), ); - await beforeBlindingRequest(wex); - const prep = succeedOrThrow( - await walletExchangeClient( + if (!csRPubs) { + await beforeBlindingRequest(wex); + const prep = await walletExchangeClient( oldCoin.exchangeBaseUrl, wex, ).postBlindingPrepare({ @@ -931,17 +938,19 @@ export async function deriveRefreshSession( seed: blindingSeed, nks, }, - }), - ); - if (prep.r_pubs.length !== nks.length) { - throw Error("exchange returned wrong number of Clause-Schnorr R-pairs"); + }); + csRPubs = succeedOrThrow(prep).r_pubs; } + checkProtocolInvariant( + csRPubs.length === nks.length, + "Wrong number of Clause-Schnorr R-pairs for refresh", + ); exchangeWithdrawValues = new Array(coinOffset); for (let i = 0; i < nks.length; i++) { exchangeWithdrawValues[nks[i].coin_offset] = { cipher: DenomKeyType.ClauseSchnorr, - r_pub_0: prep.r_pubs[i][0], - r_pub_1: prep.r_pubs[i][1], + r_pub_0: csRPubs[i][0], + r_pub_1: csRPubs[i][1], }; } } @@ -959,40 +968,21 @@ export async function deriveRefreshSession( exchangeWithdrawValues, }; const protocolVersion = refreshProtocolVersionOf(refreshSession); - switch (protocolVersion) { - case REFRESH_PROTOCOL_V32: - case REFRESH_PROTOCOL_V45: { - const derived = await wex.cryptoApi.deriveRefreshSessionV3({ - ...req, - includeTransferPubsInCommitment: - protocolVersion === REFRESH_PROTOCOL_V45, - }); - return { - protocolVersion, - confirmSig: derived.confirmSig, - planchets: derived.planchets, - hash: derived.hash, - meltValueWithFee: derived.meltValueWithFee, - batchSeeds: derived.batchSeeds, - transferPubs: derived.transferPubs, - blindingSeed, - }; - } - case REFRESH_PROTOCOL_V27: { - const derived = await wex.cryptoApi.deriveRefreshSessionV2(req); - return { - protocolVersion, - confirmSig: derived.confirmSig, - planchets: derived.planchets, - hash: derived.hash, - meltValueWithFee: derived.meltValueWithFee, - signatures: derived.signatures, - blindingSeed, - }; - } - default: - assertUnreachable(protocolVersion); - } + const derived: DerivedRefresh = + protocolVersion === REFRESH_PROTOCOL_V27 + ? { + protocolVersion, + ...(await wex.cryptoApi.deriveRefreshSessionV2(req)), + } + : { + protocolVersion, + ...(await wex.cryptoApi.deriveRefreshSessionV3({ + ...req, + includeTransferPubsInCommitment: + protocolVersion === REFRESH_PROTOCOL_V45, + })), + }; + return { ...derived, csRPubs, blindingSeed }; } /** @@ -1144,21 +1134,50 @@ export async function prepareAutoRefreshSession( return true; } +/** Discard work if the session changed while crypto or HTTP was in flight. */ +async function getPreparedRefreshSession( + tx: WalletDbTransaction, + snapshot: WalletRefreshSession, + derived: DerivedRefresh, +) { + const current = await tx.getRefreshSession( + snapshot.refreshGroupId, + snapshot.coinIndex, + ); + if ( + !current || + current.sessionPublicSeed !== snapshot.sessionPublicSeed || + current.blindingSeed !== snapshot.blindingSeed || + current.refreshProtocolVersion !== snapshot.refreshProtocolVersion || + current.norevealIndex !== snapshot.norevealIndex || + !sameSelectedDenoms(current.newDenoms, snapshot.newDenoms) || + (current.csRPubs && + JSON.stringify(current.csRPubs) !== JSON.stringify(derived.csRPubs)) + ) + return; + return current; +} + +async function saveRefreshRPubs( + tx: WalletDbTransaction, + current: WalletRefreshSession, + derived: DerivedRefresh, +) { + if (derived.csRPubs && !current.csRPubs) { + current.csRPubs = derived.csRPubs; + await tx.upsertRefreshSession(current); + } +} + /** Check current eligibility and mark the first scheduled melt in the submission transaction. */ async function authorizeScheduledMelt( wex: WalletExecutionContext, tx: WalletDbTransaction, rg: WalletRefreshGroup, coinIndex: number, - refreshSession: WalletRefreshSession, + session: WalletRefreshSession, hasAllocation: boolean, ): Promise<"first" | "retry" | undefined> { - const session = await tx.getRefreshSession(rg.refreshGroupId, coinIndex); - if ( - !session || - session.sessionPublicSeed !== refreshSession.sessionPublicSeed - ) - return; // Seeded sessions from older wallets may already have been submitted. if (session.autoRefreshMeltStarted ?? !!session.sessionPublicSeed) return "retry"; @@ -1333,7 +1352,13 @@ async function refreshMelt( refreshGroupId, coinIndex, ); - if (!refreshSession) { + if ( + !refreshSession || + !sameSelectedDenoms( + refreshSession.newDenoms, + d.refreshSession.newDenoms, + ) + ) { return undefined; } if (refreshSession.sessionPublicSeed != null) { @@ -1348,7 +1373,7 @@ async function refreshMelt( return refreshSession; }); if (!updatedSession) { - throw Error("Could not update refresh session (concurrent deletion?)."); + return false; } d.refreshSession = updatedSession; } @@ -1415,10 +1440,20 @@ async function refreshMelt( const rg = await tx.getRefreshGroup(refreshGroupId); if (!rg) return; const input = new RefreshInput(rg, coinIndex); - if (input.status !== RefreshCoinStatus.Pending || input.recoupGroupId) + if ( + input.status !== RefreshCoinStatus.Pending || + input.coinPub !== oldCoin.coinPub || + input.recoupGroupId + ) return; if ((await tx.getConfig(ConfigRecordKey.RefreshBlocked))?.value) throw new RefreshBlockedError(); + const current = await getPreparedRefreshSession( + tx, + refreshSession, + derived, + ); + if (!current) return; const history = await tx.getCoinHistory(oldCoin.coinPub); const allocation = history?.history.find( (h) => h.type === "refresh" && h.transactionId === ctx.transactionId, @@ -1430,11 +1465,12 @@ async function refreshMelt( tx, rg, coinIndex, - refreshSession, + current, !!allocation, ) : "ordinary"; if (!attempt) return; + await saveRefreshRPubs(tx, current, derived); // Keep authorizations with the coin even after a session is replaced or deleted. if ( history && @@ -1445,15 +1481,18 @@ async function refreshMelt( allocation.meltSignatures.push(derived.confirmSig); await tx.upsertCoinHistory(history); } - const pin = - attempt === "retry" - ? await tx.getRefreshMeltConfirmation({ - exchangeBaseUrl: oldCoin.exchangeBaseUrl, - refreshCommitment: derived.hash, - }) - : undefined; + // A seeded CS session can predate persistence of the R-pairs. Its melt + // may already have reached the exchange, even on the first upgraded run. + const checkPreviousMelt = + attempt === "retry" || derived.csRPubs !== undefined; + const pin = checkPreviousMelt + ? await tx.getRefreshMeltConfirmation({ + exchangeBaseUrl: oldCoin.exchangeBaseUrl, + refreshCommitment: derived.hash, + }) + : undefined; return { - attempt, + checkPreviousMelt, pin, reportedMelt: input.reportedMeltCommitment === derived.hash, }; @@ -1465,7 +1504,7 @@ async function refreshMelt( const resp = await exchangeClient.postMelt({ body: meltReqBody }); const verifiedHistory = - submission.attempt === "retry" && resp.case !== "ok" + submission.checkPreviousMelt && resp.case !== "ok" ? await reconcileRejectedRetry(resp, submission.reportedMelt) : undefined; switch (resp.case) { @@ -1545,12 +1584,12 @@ async function refreshMelt( // 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) return; const input = new RefreshInput(rg, coinIndex); if ( input.status !== RefreshCoinStatus.Pending || - rs?.sessionPublicSeed !== refreshSession.sessionPublicSeed + input.coinPub !== oldCoin.coinPub || + !(await getPreparedRefreshSession(tx, refreshSession, derived)) ) return; input.update({ reportedMeltCommitment: derived.hash }); @@ -1581,13 +1620,10 @@ async function refreshMelt( if (input.status !== RefreshCoinStatus.Pending) { return false; } - const rs = await tx.getRefreshSession(refreshGroupId, coinIndex); - if (!rs || rs.sessionPublicSeed !== refreshSession.sessionPublicSeed) { + const rs = await getPreparedRefreshSession(tx, refreshSession, derived); + if (!rs || input.coinPub !== oldCoin.coinPub) { return false; } - if (rs.norevealIndex !== undefined) { - return true; - } rs.norevealIndex = norevealIndex; await tx.upsertRefreshSession(rs); await wakePurseResiduals(wex, tx, rg, [input.coinPub]); @@ -2085,6 +2121,7 @@ async function refreshReveal( newCoinDenoms, ); // Everything but the candidate batch the exchange told us to keep secret. + requireValidNorevealIndex(norevealIndex, derived.planchets.length); const disclosed = (_: unknown, i: number): boolean => i !== norevealIndex; const req: ExchangeRefreshRevealRequestV2 = { rc: derived.hash, @@ -2100,10 +2137,30 @@ async function refreshReveal( [exchangeCoinLock(oldCoin.exchangeBaseUrl)], async () => { await checkRefreshAllowed(wex); + const ready = await wex.runWalletDbTx(async (tx) => { + const group = await tx.getRefreshGroup(refreshGroupId); + if (!group) return false; + const input = new RefreshInput(group, coinIndex); + if ( + input.status !== RefreshCoinStatus.Pending || + input.coinPub !== oldCoin.coinPub || + input.recoupGroupId + ) + return false; + const current = await getPreparedRefreshSession( + tx, + refreshSession, + derived, + ); + if (!current) return false; + return true; + }); + if (!ready) return; return exchangeClient.postRevealMelt({ body: req }); }, ); + if (!resp) return; switch (resp.case) { case "ok": break; @@ -2205,8 +2262,8 @@ async function refreshReveal( if (input.status !== RefreshCoinStatus.Pending) { return; } - const rs = await tx.getRefreshSession(refreshGroupId, coinIndex); - if (!rs) { + const rs = await getPreparedRefreshSession(tx, refreshSession, derived); + if (!rs || input.coinPub !== oldCoin.coinPub) { return; } // Once issued, retain the actual session output for final accounting. diff --git a/packages/taler-wallet-core/src/testing-recover-coins.test.ts b/packages/taler-wallet-core/src/testing-recover-coins.test.ts @@ -18,7 +18,10 @@ import { setRefreshBlocked } from "./user-attention.js"; import { openPromise } from "@gnu-taler/taler-util"; import assert from "node:assert/strict"; import { generateKeyPairSync } from "node:crypto"; -import { test } from "node:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test, type TestContext } from "node:test"; import { AmountString, Amounts, @@ -34,6 +37,7 @@ import { DenominationPubKey, DenomKeyType, deriveCsNonce, + deriveCsRefreshBlindingSeed, eddsaGetPublic, encodeCrock, ExchangeWithdrawValue, @@ -41,6 +45,7 @@ import { hash, stringToBytes, NotificationType, + RefreshReason, SetTimeoutTimerAPI, TimerGroup, WalletNotification, @@ -51,11 +56,15 @@ import { 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 { CoinSourceType, DenominationVerificationStatus, ExchangeEntryDbRecordStatus, ExchangeEntryDbUpdateStatus, + RefreshCoinStatus, + RefreshOperationStatus, + timestampPreciseToDb, WalletCoin, WalletDenomination, WalletExchangeDetails, @@ -185,6 +194,10 @@ async function fixture(db: WalletDbHandle) { >(); const events: WalletNotification[] = []; const requests: { path: string; body: any }[] = []; + const replies = new Map< + string, + (body: any) => { status: number; body: unknown } + >(); let failPath: string | undefined; let badHistory = false; let badSignature = false; @@ -230,7 +243,12 @@ async function fixture(db: WalletDbHandle) { if (path === failPath) throw Error("network failure"); let response: unknown; let status = 200; - if (path.startsWith("coins/")) { + const reply = replies.get(path); + if (reply) { + const result = reply(body); + status = result.status; + response = result.body; + } else if (path.startsWith("coins/")) { response = histories.get(path.split("/")[1]); if (!response) { status = 404; @@ -313,6 +331,8 @@ async function fixture(db: WalletDbHandle) { cancellationToken: cts.token, runWalletDbTx: db.runReadWriteTx.bind(db), ws: { + networkAvailable: true, + denomInfoCache: { getOrPut: (_key: string, get: () => unknown) => get() }, progressMap: new Map(), timerGroup, notify: (n: WalletNotification) => events.push(n), @@ -333,7 +353,15 @@ async function fixture(db: WalletDbHandle) { }, } as unknown as WalletExecutionContext; return { - db, + get db() { + return db; + }, + reopen: async (open: () => Promise<WalletDbHandle>) => { + await db.close(); + db = await open(); + wex.runWalletDbTx = db.runReadWriteTx.bind(db); + }, + replies, root, melt, histories, @@ -371,6 +399,23 @@ async function fixture(db: WalletDbHandle) { }; } +async function persistentFixture( + t: TestContext, + makeDb: (filename: string) => Promise<WalletDbHandle>, +) { + const dir = mkdtempSync(join(tmpdir(), "wallet-cs-")); + const open = () => makeDb(join(dir, "wallet.db")); + const f = await fixture(await open()); + t.after(async () => { + try { + await f.close(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + return { f, reopen: () => f.reopen(open) }; +} + function bigIntFromBytes(b: Uint8Array, littleEndian = false): bigint { const bytes = littleEndian ? [...b].reverse() : [...b]; return bytes.reduce((acc, x) => (acc << 8n) | BigInt(x), 0n); @@ -461,11 +506,11 @@ const signer = (() => { }; })(); -/** - * A melt of the root coin by another holder of its private key, with batch - * seeds that do not follow from the refresh seed in its history entry. - */ -async function foreignMelt(f: Awaited<ReturnType<typeof fixture>>) { +/** Sign a mixed batch; a foreign holder may choose its own batch seeds. */ +async function signedMelt( + f: Awaited<ReturnType<typeof fixture>>, + holder: "wallet" | "foreign", +) { const outputs = [ { ...denom("2"), denomPubHash: h("rsa"), denomPub: signer.rsaDenomPub() }, { ...denom("1"), denomPubHash: h("cs"), denomPub: signer.csDenomPub() }, @@ -479,11 +524,21 @@ async function foreignMelt(f: Awaited<ReturnType<typeof fixture>>) { r_pub_0: signer.rPubs[0], r_pub_1: signer.rPubs[1], }; - const blindingSeed = encodeCrock(getRandomBytes(32)); + const seed = h("refresh seed in the melt request"); + const blindingSeed = + holder === "foreign" + ? encodeCrock(getRandomBytes(32)) + : encodeCrock( + deriveCsRefreshBlindingSeed( + decodeCrock(seed), + decodeCrock(f.root.coinPriv), + ), + ); const session = await nativeCryptoR.deriveRefreshSessionV3(nativeCryptoR, { includeTransferPubsInCommitment: true, kappa: 3, - sessionPublicSeed: h("seed of the other holder"), + sessionPublicSeed: + holder === "foreign" ? h("seed of the other holder") : seed, meltCoinPub: f.root.coinPub, meltCoinPriv: f.root.coinPriv, meltCoinDenomPubHash: f.root.denomPubHash, @@ -507,7 +562,7 @@ async function foreignMelt(f: Awaited<ReturnType<typeof fixture>>) { melt_fee: a("1"), rc: session.hash, h_denom_pub: f.root.denomPubHash, - refresh_seed: h("refresh seed in the melt request"), + refresh_seed: seed, blinding_seed: blindingSeed, denoms_h: order.map((d) => d.denomPubHash), noreveal_index: noreveal, @@ -544,13 +599,186 @@ async function foreignMelt(f: Awaited<ReturnType<typeof fixture>>) { return { melt, reveal, + outputs, history, blindingSeed, planchets: session.planchets[noreveal], }; } +async function localRefresh(f: Awaited<ReturnType<typeof fixture>>) { + const signed = await signedMelt(f, "wallet"); + const { melt, reveal, outputs } = signed; + const id = "local-refresh"; + await f.db.runReadWriteTx(async (tx) => { + await tx.upsertCoin({ ...f.root, status: CoinStatus.Dormant }); + await tx.upsertRefreshGroup({ + refreshGroupId: id, + currency: "TESTKUDOS", + reason: RefreshReason.Manual, + operationStatus: RefreshOperationStatus.Pending, + statusPerCoin: [RefreshCoinStatus.Pending], + oldCoinPubs: [f.root.coinPub], + inputPerCoin: [a("6")], + expectedOutputPerCoin: [a("5")], + timestampCreated: timestampPreciseToDb({ t_s: 1 }), + timestampFinished: undefined, + refundRequests: {}, + }); + await tx.upsertRefreshSession({ + refreshGroupId: id, + coinIndex: 0, + amountRefreshOutput: a("5"), + refreshProtocolVersion: 45, + sessionPublicSeed: melt.refresh_seed, + norevealIndex: undefined, + newDenoms: melt.denoms_h!.map((denomPubHash) => ({ + denomPubHash, + count: 1, + })), + }); + for (const d of outputs) { + await tx.upsertCoinAvailability({ + ...d, + maxAge: 0, + freshCoinCount: 0, + visibleCoinCount: 0, + hasFreshCoins: 0, + pendingRefreshOutputCount: melt.denoms_h!.filter( + (h) => h === d.denomPubHash, + ).length, + }); + } + }); + f.blindingPrepare((body) => { + assert.deepEqual(body.nks, [{ coin_offset: 1, denom_pub_hash: h("cs") }]); + return { cipher: "CS", r_pubs: [signer.rPubs] }; + }); + f.replies.set("melt", () => ({ + status: 200, + body: { + noreveal_index: melt.noreveal_index, + exchange_pub: k("exchange"), + exchange_sig: sig, + }, + })); + f.replies.set("reveal-melt", () => ({ + status: 200, + body: { ev_sigs: reveal.ev_sigs }, + })); + return { + ...signed, + id, + run: () => processRefreshGroup(f.wex, id), + session: () => f.db.runReadWriteTx((tx) => tx.getRefreshSession(id, 0)), + }; +} + for (const makeDb of runnerFactories) { + 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); + const m = await localRefresh(f); + f.onRequest(async (path) => { + if (path === "melt") + assert.deepEqual((await m.session())?.csRPubs, [signer.rPubs]); + }); + f.fail(interrupted); + await m.run(); + const firstRequest = f.requests.find((r) => r.path === "melt")!; + assert.equal( + (await m.session())?.norevealIndex, + interrupted === "melt" ? undefined : m.melt.noreveal_index, + ); + await reopen(); + f.fail(); + f.blindingPrepare(); + f.requests.length = 0; + await m.run(); + assert.deepEqual( + f.requests.map((r) => r.path), + interrupted === "melt" ? ["melt", "reveal-melt"] : ["reveal-melt"], + ); + if (interrupted === "melt") assert.deepEqual(f.requests[0], firstRequest); + assert.equal(f.requests.at(-1)!.body.rc, m.melt.rc); + const coins = await f.db.runReadWriteTx((tx) => + tx.getCoinsByPubs(m.planchets.map((p) => p.coinPub)), + ); + assert.equal(coins.length, 3); + assert.ok(coins.every((c) => c.status === CoinStatus.Fresh && c.visible)); + assert.equal( + (await f.db.runReadWriteTx((tx) => tx.getRefreshGroup(m.id))) + ?.operationStatus, + RefreshOperationStatus.Finished, + ); + }); + } + + test(`${makeDb.name}: a reported CS melt waits for an authenticated no-reveal index`, async (t) => { + const f = await fixture(await makeDb()); + t.after(f.close); + const m = await localRefresh(f); + f.fail("melt"); + await m.run(); + f.fail(); + m.history(m.melt); + f.replies.set("melt", () => ({ + status: 410, + body: { code: TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED }, + })); + await m.run(); + assert.equal((await m.session())?.norevealIndex, undefined); + assert.deepEqual((await m.session())?.csRPubs, [signer.rPubs]); + assert.ok(!f.requests.some((r) => r.path === "reveal-melt")); + // A signed melt response can be pinned before the worker saves the index. + await f.db.runReadWriteTx((tx) => + tx.upsertRefreshMeltConfirmation({ + exchangeBaseUrl: url, + refreshCommitment: m.melt.rc, + norevealIndex: m.melt.noreveal_index!, + }), + ); + f.requests.length = 0; + await m.run(); + assert.deepEqual( + f.requests.map((r) => r.path), + ["reveal-melt"], + ); + assert.equal((await m.session())?.norevealIndex, m.melt.noreveal_index); + }); + + test(`${makeDb.name}: stale blinding preparation cannot authorize a replaced refresh`, async () => { + const f = await fixture(await makeDb()); + try { + const m = await localRefresh(f); + for (const change of ["order", "seed"]) { + f.onRequest(async (path) => { + if (path !== "blinding-prepare") return; + await f.db.runReadWriteTx(async (tx) => { + const session = (await tx.getRefreshSession(m.id, 0))!; + if (change === "seed") + session.sessionPublicSeed = h("next session"); + else + [session.newDenoms[0], session.newDenoms[1]] = [ + session.newDenoms[1], + session.newDenoms[0], + ]; + await tx.upsertRefreshSession(session); + }); + }); + f.blindingPrepare(() => ({ cipher: "CS", r_pubs: [signer.rPubs] })); + await m.run(); + } + assert.deepEqual( + f.requests.map((r) => r.path), + ["blinding-prepare", "blinding-prepare"], + ); + assert.equal((await m.session())?.csRPubs, undefined); + } finally { + await f.close(); + } + }); + test(`${makeDb.name}: recursive recovery, duplicate denominations and idempotent retry`, async () => { const f = await fixture(await makeDb()); try { @@ -849,7 +1077,7 @@ for (const makeDb of runnerFactories) { test(`${makeDb.name}: a REVEAL entry recovers a melt with seeds of another holder`, async () => { const f = await fixture(await makeDb()); try { - const m = await foreignMelt(f); + const m = await signedMelt(f, "foreign"); f.blindingPrepare((body) => ({ cipher: DenomKeyType.ClauseSchnorr, r_pubs: body.nks.map(() => signer.rPubs), @@ -899,7 +1127,7 @@ for (const makeDb of runnerFactories) { test(`${makeDb.name}: a REVEAL entry without R-values asks the exchange for them`, async () => { const f = await fixture(await makeDb()); try { - const m = await foreignMelt(f); + const m = await signedMelt(f, "foreign"); delete m.reveal.cs_r_values; m.history(m.melt, m.reveal); const unavailable = await f.run(); @@ -932,7 +1160,7 @@ for (const makeDb of runnerFactories) { test(`${makeDb.name}: a REVEAL entry must fit the melt and carry valid signatures`, async () => { const f = await fixture(await makeDb()); try { - const m = await foreignMelt(f); + const m = await signedMelt(f, "foreign"); const [s0, s1, s2] = m.reveal.ev_sigs; for (const reveal of [ { ...m.reveal, ev_sigs: [s2, s1, s0] },