commit 1fd9c5be927d7bd527cb7727877ebcc72b33d3cc
parent 2b5703c041203f264f3f3b949f12f5269e0f70dd
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 19:57:12 +0100
wallet refresh: recover missing CS R-pairs from coin history
For older sessions, verify that the reconstructed commitment matches
the original melt before revealing. Interactive recovery can also use
pairs retained by the wallet when exchange history omits them.
Issue: https://bugs.taler.net/n/12286
Diffstat:
4 files changed, 263 insertions(+), 5 deletions(-)
diff --git a/packages/taler-wallet-core/src/denominations.ts b/packages/taler-wallet-core/src/denominations.ts
@@ -29,7 +29,10 @@ import {
Duration,
FeeDescription,
FeeDescriptionPair,
+ HttpStatusCode,
Logger,
+ OperationFail,
+ TalerErrorCode,
TalerProtocolTimestamp,
TimePoint,
} from "@gnu-taler/taler-util";
@@ -46,6 +49,20 @@ import { WalletExecutionContext } from "./wallet.js";
*/
const logger = new Logger("denominations.ts");
+/** A blinding preparation failed because the selected denomination is unusable. */
+export function isDenominationUnavailable(
+ resp: OperationFail<HttpStatusCode>,
+): boolean {
+ const code = resp.detail?.code;
+ return (
+ (resp.case === HttpStatusCode.NotFound &&
+ code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN) ||
+ (resp.case === HttpStatusCode.Gone &&
+ (code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED ||
+ code === TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED))
+ );
+}
+
/**
* Given a list of denominations with the same value and same period of time:
* return the one that will be used.
diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts
@@ -21,6 +21,7 @@ import {
RefreshBlockedError,
} from "./user-attention.js";
import { ensureRecoupProvenance } from "./recoup.js";
+import { isDenominationUnavailable } from "./denominations.js";
/**
* @fileoverview
@@ -886,6 +887,53 @@ export async function requireValidMeltConfirmation(
});
}
+/** Recover the original values when an older wallet omitted them and the key has expired. */
+async function readHistoricalRefreshRPubs(
+ wex: WalletExecutionContext,
+ session: WalletRefreshSession,
+ oldCoin: WalletCoin,
+ oldDenom: DenominationInfo,
+ blindingSeed: string,
+ nks: BlindingInputParameter[],
+ error: TalerErrorDetail | undefined,
+) {
+ const history = await readVerifiedCoinHistory(wex, oldCoin, oldDenom);
+ const entries = history.case === "ok" ? history.body.history : [];
+ const melt = entries.find(
+ (h) =>
+ h.type === "MELT" &&
+ h.refresh_seed === session.sessionPublicSeed &&
+ h.blinding_seed === blindingSeed,
+ );
+ const reveal =
+ melt?.type === "MELT"
+ ? entries.find((h) => h.type === "REVEAL" && h.rc === melt.rc)
+ : undefined;
+ if (reveal?.type !== "REVEAL" || !reveal.cs_r_values) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_TRANSACTION_RECOVERY_FAILED,
+ {
+ transactionId: constructTransactionIdentifier({
+ tag: TransactionType.Refresh,
+ refreshGroupId: session.refreshGroupId,
+ }),
+ innerError: error,
+ },
+ "Cannot recover the original CS R-pairs from blinding preparation or coin history",
+ );
+ }
+ const values = reveal.cs_r_values;
+ const csRPubs = nks.map(({ coin_offset }) => {
+ const pair = values[coin_offset];
+ checkProtocolInvariant(
+ !!pair,
+ "Missing CS R-pair at committed output offset",
+ );
+ return pair;
+ });
+ return { csRPubs, historicalCommitment: reveal.rc };
+}
+
/**
* Re-derive everything about a refresh session from the stored seed, using the
* refresh protocol the session melted with.
@@ -916,6 +964,7 @@ export async function deriveRefreshSession(
}
let blindingSeed: string | undefined;
let csRPubs = refreshSession.csRPubs;
+ let historicalCommitment: string | undefined;
let exchangeWithdrawValues: (ExchangeWithdrawValue | undefined)[] | undefined;
if (nks.length > 0) {
blindingSeed =
@@ -939,7 +988,19 @@ export async function deriveRefreshSession(
nks,
},
});
- csRPubs = succeedOrThrow(prep).r_pubs;
+ if (prep.case !== "ok" && isDenominationUnavailable(prep)) {
+ ({ csRPubs, historicalCommitment } = await readHistoricalRefreshRPubs(
+ wex,
+ refreshSession,
+ oldCoin,
+ oldDenom,
+ blindingSeed,
+ nks,
+ prep.detail,
+ ));
+ } else {
+ csRPubs = succeedOrThrow(prep).r_pubs;
+ }
}
checkProtocolInvariant(
csRPubs.length === nks.length,
@@ -982,6 +1043,39 @@ export async function deriveRefreshSession(
protocolVersion === REFRESH_PROTOCOL_V45,
})),
};
+ checkProtocolInvariant(
+ historicalCommitment === undefined || derived.hash === historicalCommitment,
+ "Historical CS R-pairs do not reproduce the original melt commitment",
+ );
+ // A legacy session can have a confirmed index but no R-pairs. Authenticate
+ // the reconstructed commitment before using fresh exchange data for reveal.
+ if (
+ csRPubs &&
+ !refreshSession.csRPubs &&
+ refreshSession.norevealIndex !== undefined
+ ) {
+ const pin = await wex.runWalletDbTx((tx) =>
+ tx.getRefreshMeltConfirmation({
+ exchangeBaseUrl: oldCoin.exchangeBaseUrl,
+ refreshCommitment: derived.hash,
+ }),
+ );
+ if (pin) {
+ checkProtocolInvariant(
+ pin.norevealIndex === refreshSession.norevealIndex,
+ "Stored melt confirmations disagree about the no-reveal index",
+ );
+ } else if (!historicalCommitment) {
+ const history = await readVerifiedCoinHistory(wex, oldCoin, oldDenom);
+ checkProtocolInvariant(
+ history.case === "ok" &&
+ history.body.history.some(
+ (h) => h.type === "MELT" && h.rc === derived.hash,
+ ),
+ "CS R-pairs do not reproduce a confirmed melt commitment",
+ );
+ }
+ }
return { ...derived, csRPubs, blindingSeed };
}
@@ -2153,6 +2247,8 @@ async function refreshReveal(
derived,
);
if (!current) return false;
+ // Backfill sessions made by a wallet that only saved the seed.
+ await saveRefreshRPubs(tx, current, derived);
return true;
});
if (!ready) return;
diff --git a/packages/taler-wallet-core/src/testing-recover-coins.test.ts b/packages/taler-wallet-core/src/testing-recover-coins.test.ts
@@ -714,6 +714,72 @@ for (const makeDb of runnerFactories) {
});
}
+ test(`${makeDb.name}: backfill a confirmed CS session from matching history after expiry`, async () => {
+ const f = await fixture(await makeDb());
+ try {
+ const m = await localRefresh(f);
+ const session = (await m.session())!;
+ session.norevealIndex = m.melt.noreveal_index;
+ await f.db.runReadWriteTx((tx) => tx.upsertRefreshSession(session));
+ f.blindingPrepare();
+ m.history(m.melt);
+ const missing = await m.run();
+ assert.match(JSON.stringify(missing), /original CS R-pairs/);
+ m.history(m.melt, {
+ ...m.reveal,
+ cs_r_values: [null, [signer.rPubs[1], signer.rPubs[0]], null],
+ });
+ assert.match(JSON.stringify(await m.run()), /original melt commitment/);
+ assert.ok(
+ !f.requests.some((r) => r.path === "melt" || r.path === "reveal-melt"),
+ );
+ assert.equal((await m.session())?.csRPubs, undefined);
+ m.history(m.melt, m.reveal);
+ await m.run();
+ assert.deepEqual((await m.session())?.csRPubs, [signer.rPubs]);
+ assert.equal((await m.session())?.norevealIndex, m.melt.noreveal_index);
+ assert.equal(f.requests.at(-1)?.body.rc, m.melt.rc);
+ assert.equal(
+ (await f.db.runReadWriteTx((tx) => tx.getRefreshGroup(m.id)))
+ ?.operationStatus,
+ RefreshOperationStatus.Finished,
+ );
+ } finally {
+ await f.close();
+ }
+ });
+
+ test(`${makeDb.name}: a confirmed legacy refresh backfills preparation only for the pinned commitment`, async (t) => {
+ const f = await fixture(await makeDb());
+ t.after(f.close);
+ const m = await localRefresh(f);
+ await f.db.runReadWriteTx(async (tx) => {
+ await tx.upsertRefreshSession({
+ ...(await tx.getRefreshSession(m.id, 0))!,
+ norevealIndex: m.melt.noreveal_index,
+ });
+ await tx.upsertRefreshMeltConfirmation({
+ exchangeBaseUrl: url,
+ refreshCommitment: m.melt.rc,
+ norevealIndex: m.melt.noreveal_index!,
+ });
+ });
+ f.blindingPrepare(() => ({
+ cipher: "CS",
+ r_pubs: [[signer.rPubs[1], signer.rPubs[0]]],
+ }));
+ assert.match(JSON.stringify(await m.run()), /confirmed melt commitment/);
+ assert.equal((await m.session())?.csRPubs, undefined);
+ f.blindingPrepare(() => ({ cipher: "CS", r_pubs: [signer.rPubs] }));
+ f.requests.length = 0;
+ await m.run();
+ assert.deepEqual(
+ f.requests.map((r) => r.path),
+ ["blinding-prepare", "reveal-melt"],
+ );
+ assert.deepEqual((await m.session())?.csRPubs, [signer.rPubs]);
+ });
+
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);
@@ -747,6 +813,32 @@ for (const makeDb of runnerFactories) {
assert.equal((await m.session())?.norevealIndex, m.melt.noreveal_index);
});
+ for (const revealed of [false, true]) {
+ test(`${makeDb.name}: interactive recovery uses saved CS R-pairs with ${revealed ? "REVEAL" : "MELT"} history`, async (t) => {
+ const f = await fixture(await makeDb());
+ t.after(f.close);
+ const m = await localRefresh(f);
+ f.fail("reveal-melt");
+ await m.run();
+ f.fail();
+ f.blindingPrepare();
+ f.requests.length = 0;
+ m.history(
+ m.melt,
+ ...(revealed ? [{ ...m.reveal, cs_r_values: undefined }] : []),
+ );
+ const result = await f.run(false);
+ assert.equal(result.complete, true, JSON.stringify(result));
+ assert.equal(result.recoveredAmount, a("5"));
+ assert.deepEqual(
+ f.requests
+ .filter((r) => !r.path.startsWith("coins/"))
+ .map((r) => r.path),
+ revealed ? [] : ["melt", "reveal-melt"],
+ );
+ });
+ }
+
test(`${makeDb.name}: stale blinding preparation cannot authorize a replaced refresh`, async () => {
const f = await fixture(await makeDb());
try {
diff --git a/packages/taler-wallet-core/src/testing-recover-coins.ts b/packages/taler-wallet-core/src/testing-recover-coins.ts
@@ -33,6 +33,8 @@ import {
CoinStatus,
DenominationPubKey,
DenomKeyType,
+ decodeCrock,
+ deriveCsRefreshBlindingSeed,
encodeCrock,
ExchangeWithdrawValue,
getRandomBytes,
@@ -179,16 +181,18 @@ async function revealedExchangeWithdrawValues(
wex: WalletExecutionContext,
oldCoin: WalletCoin,
newDenoms: { denomPub: DenominationPubKey; denomPubHash: string }[],
- blindingSeed: string | undefined,
+ session: WalletRefreshSession,
revealEntry: CoinRevealTransaction,
): Promise<(ExchangeWithdrawValue | undefined)[] | undefined> {
const nks: BlindingInputParameter[] = [];
const values: (ExchangeWithdrawValue | undefined)[] = newDenoms.map(
() => undefined,
);
+ let csIndex = 0;
newDenoms.forEach((d, i) => {
if (d.denomPub.cipher !== DenomKeyType.ClauseSchnorr) return;
- const r = revealEntry.cs_r_values?.[i];
+ const r = session.csRPubs?.[csIndex] ?? revealEntry.cs_r_values?.[i];
+ csIndex++;
if (r) {
values[i] = {
cipher: DenomKeyType.ClauseSchnorr,
@@ -211,7 +215,7 @@ async function revealedExchangeWithdrawValues(
body: {
cipher: DenomKeyType.ClauseSchnorr,
operation: "melt",
- seed: blindingSeed!,
+ seed: session.blindingSeed!,
nks,
},
});
@@ -328,6 +332,41 @@ export async function recoverCoinMelt(
count: 1,
})),
};
+ if (melt.blinding_seed) {
+ // Recovery builds its own group. Reuse the original session's values when
+ // the exchange only reports a MELT or omits R-pairs from its REVEAL.
+ session.csRPubs = await wex.runWalletDbTx(async (tx) => {
+ for (const group of await tx.listAllRefreshGroups()) {
+ const index = group.oldCoinPubs.indexOf(oldCoin.coinPub);
+ if (index < 0) continue;
+ const local = await tx.getRefreshSession(group.refreshGroupId, index);
+ if (
+ !local?.csRPubs ||
+ !local.sessionPublicSeed ||
+ local.sessionPublicSeed !== melt.refresh_seed
+ )
+ continue;
+ const seed =
+ local.blindingSeed ??
+ encodeCrock(
+ deriveCsRefreshBlindingSeed(
+ decodeCrock(local.sessionPublicSeed),
+ decodeCrock(oldCoin.coinPriv),
+ ),
+ );
+ const hashes = local.newDenoms.flatMap((d) =>
+ Array<string>(d.count).fill(d.denomPubHash),
+ );
+ if (
+ seed === melt.blinding_seed &&
+ hashes.length === newDenoms.length &&
+ hashes.every((h, i) => h === newDenoms[i].denomPubHash)
+ )
+ return local.csRPubs;
+ }
+ return undefined;
+ });
+ }
phase("derive");
let planchets: RefreshPlanchetInfo[];
let evSigs: BlindedDenominationSignature[];
@@ -349,7 +388,7 @@ export async function recoverCoinMelt(
wex,
oldCoin,
newDenoms,
- melt.blinding_seed,
+ session,
revealEntry,
);
planchets = (
@@ -363,11 +402,19 @@ export async function recoverCoinMelt(
exchangeWithdrawValues,
})
).planchets;
+ if (exchangeWithdrawValues) {
+ session.csRPubs = exchangeWithdrawValues.flatMap((v) =>
+ v?.cipher === DenomKeyType.ClauseSchnorr
+ ? [[v.r_pub_0, v.r_pub_1] as [string, string]]
+ : [],
+ );
+ }
evSigs = revealEntry.ev_sigs;
// The coins do not follow from the refresh seed, so the session cannot
// be re-derived; the refresh group is finished and never re-derives it.
session.norevealIndex = melt.noreveal_index;
} else {
+ session.csRPubs ??= revealEntry?.cs_r_values?.filter((r) => r !== null);
({ planchets, evSigs } = await replayCoinMelt(
wex,
oldCoin,
@@ -415,6 +462,7 @@ async function replayCoinMelt(
newDenoms,
waitForRefreshAllowed,
);
+ session.csRPubs ??= candidate.csRPubs;
if (
candidate.hash === melt.rc &&
Amounts.cmp(candidate.meltValueWithFee, melt.amount) === 0
@@ -709,6 +757,11 @@ async function runCoinRecovery(
};
const issue = (coinPub: string, e: unknown, rc?: string) => {
checkCancelled(wex);
+ if (
+ e instanceof TalerError &&
+ e.errorDetail.code === TalerErrorCode.WALLET_TRANSACTION_RECOVERY_FAILED
+ )
+ e = new RecoveryError("missing-recovery-data", e.message);
result.issues.push({
coinPub,
refreshCommitment: rc,