taler-typescript-core

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

commit 1cdd07d48a9c3df2ccd4acba73a9551af2855a7b
parent 890ca977b9fe4728f96e6c4e4d059baa0c48c57f
Author: Florian Dold <dold@taler.net>
Date:   Fri, 27 Nov 2026 18:12:45 +0100

wallet-core: refresh the remainder of each settled payment melt

A refresh session can only issue a bounded batch of coins. Record the
gross melt and reserve the remainder alongside the issued coins.
Reconstruct older melts from their retained refresh sessions.

Issue: https://bugs.taler.net/n/12291

Diffstat:
Mpackages/taler-wallet-core/src/db/records.ts | 4++--
Mpackages/taler-wallet-core/src/pay-merchant.ts | 31+++++++++++++++++++------------
Mpackages/taler-wallet-core/src/refresh.test.ts | 327++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/refresh.ts | 174++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
4 files changed, 519 insertions(+), 17 deletions(-)

diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -1213,8 +1213,8 @@ export interface WalletRefundGroup { amountRaw: AmountString; /** - * Estimated effective amount, based on - * refund fees and refresh costs. + * Estimated output after refund fees and refresh costs. For deferred + * abort refunds, this accumulates the coins actually issued on reveal. */ amountEffective: AmountString; } diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -6499,18 +6499,22 @@ export async function storeRefunds( amount: Amounts.stringify(amount), }), ); - const outInfo = await calculateRefreshOutput( - wex, - tx, - currency, - newlyRefundedCoins, - ); - refundGroup.amountEffective = Amounts.stringify( - Amounts.add( - refundGroup.amountEffective, - Amounts.sumOrZero(currency, outInfo.outputPerCoin).amount, - ).amount, - ); + const isAbortRefund = + refundGroup.refundReason === RefundReason.AbortRefund; + if (!isAbortRefund) { + const outInfo = await calculateRefreshOutput( + wex, + tx, + currency, + newlyRefundedCoins, + ); + refundGroup.amountEffective = Amounts.stringify( + Amounts.add( + refundGroup.amountEffective, + Amounts.sumOrZero(currency, outInfo.outputPerCoin).amount, + ).amount, + ); + } const refreshResult = await createRefreshGroup( wex, tx, @@ -6520,6 +6524,9 @@ export async function storeRefunds( // Refunds are pseudo-transactions, so their recovery refresh is // associated with the payment transaction. ctx.transactionId, + isAbortRefund + ? { refundGroupId: refundGroup.refundGroupId } + : undefined, ); refundGroup.refreshGroupId = refreshResult.refreshGroupId; } diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts @@ -13,12 +13,16 @@ You should have received a copy of the GNU General Public License along with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ +import { assessMerchantAbortRecovery } from "./refund-accounting.js"; +import { DeriveRefreshSessionRequestV2 } from "./crypto/cryptoTypes.js"; import { validateAndRecomputeCoinHistoryBalance } from "./coin-history.js"; -import { spendCoins } from "./common.js"; +import { spendCoins, TaskRunResultType } from "./common.js"; import { AbsoluteTime, Amounts, CoinStatus, + Cache, + Duration, DenominationInfo, DenomKeyType, encodeCrock, @@ -29,10 +33,14 @@ import { TransactionIdStr, TransactionType, } from "@gnu-taler/taler-util"; +import { dummyHttpResponse } from "@gnu-taler/taler-util/http"; import assert from "node:assert"; import { test } from "node:test"; import { classifyRecoveryRefresh, + createRefreshGroup, + processRefreshGroup, + restorePaymentRecoveryMelts, computeRefreshTransactionActions, getTotalRefreshCostInternal, getTotalRefreshCosts, @@ -40,6 +48,8 @@ import { requireValidNorevealIndex, } from "./refresh.js"; import { + RefundGroupStatus, + RefundReason, DenominationVerificationStatus, RefreshCoinStatus, RefreshOperationStatus, @@ -50,7 +60,15 @@ import { WalletRefreshGroup, WalletRefreshSession, timestampProtocolToDb, + timestampPreciseToDb, } from "./db/records.js"; +import { + makeCoin, + makeDenomination, + makeExchange, + makeExchangeDetails, + makeSignKey, +} from "./db/testing/conformance-cases.js"; import { runnerFactories } from "./db/testing/runners.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { WalletExecutionContext } from "./wallet.js"; @@ -253,6 +271,313 @@ for (const makeRunner of runnerFactories) { }); } +for (const { makeRunner, reason } of runnerFactories.flatMap((makeRunner) => + [RefreshReason.AbortPay, RefreshReason.Refund].map((reason) => ({ + makeRunner, + reason, + })), +)) { + test(`${makeRunner.name}: ${reason} retries missing keys and collects a capped melt in batches`, async (t) => { + t.mock.timers.enable({ apis: ["Date"], now: 2_000_000 }); + const runner = await makeRunner(); + const coin = makeCoin("old"); + let batch: WalletCoin[] = []; + const melts: string[] = []; + const url = coin.exchangeBaseUrl; + const paths: string[] = []; + const wex = { + ws: { + networkAvailable: true, + denomInfoCache: new Cache(10, Duration.fromSpec({ minutes: 1 })), + exchangeCache: new Map([ + [url, { exchangeBaseUrl: url, protocolVersionRange: "27:0:0" }], + ]), + runSequentialized: (_locks: string[], f: () => Promise<unknown>) => f(), + }, + cryptoApi: { + deriveRefreshSessionV2: async ( + request: DeriveRefreshSessionRequestV2, + ) => { + const [denom] = request.newCoinDenoms; + batch = Array.from({ length: denom.count }, (_, i) => + makeCoin(`${request.sessionPublicSeed}-${i}`), + ); + return { + planchets: [0, 1, 2].map(() => + batch.map((coin) => ({ + ...coin, + coinEv: { + cipher: DenomKeyType.Rsa, + rsa_blinded_planchet: "planchet", + }, + })), + ), + signatures: ["a", "b", "c"], + hash: coin.coinEvHash, + meltValueWithFee: Amounts.mult(denom.value, denom.count).amount, + confirmSig: encodeCrock(new Uint8Array(64)), + }; + }, + isValidMeltConfirmation: async () => ({ valid: true }), + unblindDenominationSignature: async () => batch[0].denomSig, + verifyDenominationSignature: async () => ({ valid: true }), + }, + http: { + async fetch( + requestUrl: string, + options: { body: { value_with_fee: string } }, + ) { + const path = new URL(requestUrl).pathname; + paths.push(path); + if (path === "/melt") melts.push(options.body.value_with_fee); + const reply = + path === "/melt" + ? { + noreveal_index: 0, + exchange_pub: coin.exchangeMasterPub, + exchange_sig: encodeCrock(new Uint8Array(64)), + } + : { + ev_sigs: batch.map(() => ({ + cipher: DenomKeyType.Rsa, + blinded_rsa_signature: "sig", + })), + }; + return { + ...dummyHttpResponse, + requestUrl, + status: 200, + json: async () => reply, + }; + }, + }, + cancellationToken: { isCancelled: false }, + taskScheduler: { startShepherdTask() {} }, + runWalletDbTx: runner.runReadWriteTx.bind(runner), + } as unknown as WalletExecutionContext; + try { + const old = makeDenomination(url, coin.denomPubHash, { + isOffered: false, + }); + old.value = "TESTKUDOS:100"; + old.fees.feeRefresh = old.fees.feeWithdraw = "TESTKUDOS:0"; + const other = { + ...makeDenomination(url, "other-mask"), + fees: old.fees, + }; + other.denomPub = { ...other.denomPub, age_mask: 257 }; + const { refreshGroupId } = await runner.runReadWriteTx(async (tx) => { + const rowId = await tx.upsertExchangeDetails( + makeExchangeDetails(url, coin.exchangeMasterPub), + ); + await tx.upsertExchangeSignKey({ + ...makeSignKey(rowId, coin.exchangeMasterPub), + stampExpire: old.stampExpireDeposit, + }); + await tx.upsertExchange({ + ...makeExchange(url), + detailsPointer: { + masterPublicKey: coin.exchangeMasterPub, + currency: old.currency, + updateClock: timestampPreciseToDb({ t_s: 1 }), + }, + }); + const serial = await tx.upsertDenominationFamily({ + familyParams: { + exchangeBaseUrl: url, + exchangeMasterPub: coin.exchangeMasterPub, + value: old.value, + ...old.fees, + }, + }); + await tx.upsertDenomination({ + ...old, + denominationFamilySerial: serial, + }); + await tx.upsertDenomination({ + ...other, + denominationFamilySerial: serial, + }); + await tx.upsertCoin({ ...coin, status: CoinStatus.Dormant }); + if (reason === RefreshReason.Refund) { + await tx.upsertRefundGroup({ + refundGroupId: "signed", + proposalId: "refused", + refundReason: RefundReason.AbortRefund, + amountRaw: old.value, + amountEffective: "TESTKUDOS:0", + status: RefundGroupStatus.Done, + timestampCreated: timestampPreciseToDb({ t_s: 1 }), + }); + } + const result = await createRefreshGroup( + wex, + tx, + old.currency, + [{ coinPub: coin.coinPub, amount: old.value }], + reason, + "txn:payment:refused", + reason === RefreshReason.Refund + ? { refundGroupId: "signed" } + : undefined, + ); + if (reason === RefreshReason.Refund) { + const refund = (await tx.getRefundGroup("signed"))!; + refund.refreshGroupId = result.refreshGroupId; + await tx.upsertRefundGroup(refund); + } + return result; + }); + const verifyPending = async () => { + assert.equal( + (await processRefreshGroup(wex, refreshGroupId)).type, + TaskRunResultType.Error, + ); + await runner.runReadWriteTx(async (tx) => { + const group = await tx.getRefreshGroup(refreshGroupId); + assert.equal(group?.operationStatus, RefreshOperationStatus.Pending); + assert.equal(group?.statusPerCoin[0], RefreshCoinStatus.Pending); + assert.equal( + await tx.getRefreshSession(refreshGroupId, 0), + undefined, + ); + }); + }; + await verifyPending(); + const bigger = { + ...makeDenomination(url, "larger"), + value: "TESTKUDOS:200" as const, + fees: old.fees, + }; + await runner.runReadWriteTx(async (tx) => { + bigger.denominationFamilySerial = await tx.upsertDenominationFamily({ + familyParams: { + exchangeBaseUrl: url, + exchangeMasterPub: coin.exchangeMasterPub, + value: bigger.value, + ...bigger.fees, + }, + }); + await tx.upsertDenomination(bigger); + }); + await verifyPending(); + await runner.runReadWriteTx(async (tx) => { + const d = makeDenomination(url, "replacement-one"); + d.fees = old.fees; + d.denominationFamilySerial = await tx.upsertDenominationFamily({ + familyParams: { + exchangeBaseUrl: url, + exchangeMasterPub: coin.exchangeMasterPub, + value: d.value, + ...d.fees, + }, + }); + await tx.upsertDenomination(d); + }); + assert.deepEqual(paths, []); + const result = await processRefreshGroup(wex, refreshGroupId); + assert.equal( + result.type, + TaskRunResultType.Progress, + JSON.stringify(result), + ); + assert.deepEqual(paths, ["/melt", "/reveal-melt"]); + const readRecovery = () => + runner.runReadWriteTx(async (tx) => { + const original = (await tx.getRefreshGroup(refreshGroupId))!; + const related = await tx.getRefreshGroupsByOriginatingTransaction( + "txn:payment:refused", + ); + const { outcome: evidence } = assessMerchantAbortRecovery( + { + coinPubs: [coin.coinPub], + coinContributions: [old.value], + }, + [original, ...related], + [], + new Map([[coin.coinPub, { value: old.value, ...old.fees }]]), + ); + const history = await tx.getCoinHistory(coin.coinPub); + const allocations = history!.history + .filter((h) => h.type === "refresh") + .map((h) => h.amount); + return { original, related, evidence, allocations }; + }); + const first = await readRecovery(); + assert.deepEqual(melts, ["TESTKUDOS:64"]); + assert.equal( + first.original.paymentRecovery?.settledPerCoin[0].melted, + melts[0], + ); + assert.equal(first.evidence, "pending"); + assert.deepEqual(first.original.inputPerCoin, ["TESTKUDOS:64"]); + assert.deepEqual(first.allocations, ["TESTKUDOS:64", "TESTKUDOS:36"]); + const [remaining] = first.related.filter( + (g) => g.refreshGroupId !== refreshGroupId, + ); + assert.deepEqual(remaining.inputPerCoin, ["TESTKUDOS:36"]); + await processRefreshGroup(wex, remaining.refreshGroupId); + await processRefreshGroup(wex, refreshGroupId); + await processRefreshGroup(wex, remaining.refreshGroupId); + const complete = await readRecovery(); + assert.deepEqual(melts, ["TESTKUDOS:64", "TESTKUDOS:36"]); + assert.equal(complete.evidence, "recovered"); + assert.equal(complete.related.length, 2); + await runner.runReadWriteTx(async (tx) => { + if (reason === RefreshReason.Refund) { + const refund = (await tx.getRefundGroup("signed"))!; + assert.equal(refund.amountEffective, old.value); + assert.equal(refund.transactionAmounts?.final, old.value); + } + for (const group of complete.related) { + const fresh = await tx.getCoinsBySourceTransaction( + new RefreshTransactionContext(wex, group.refreshGroupId) + .transactionId, + ); + assert.equal( + fresh.length, + group.refreshGroupId === refreshGroupId ? 64 : 36, + ); + assert.ok(fresh.every((c) => c.status === CoinStatus.Fresh)); + } + }); + if (reason === RefreshReason.AbortPay) { + // Older groups stored a full budget with the retained session, and + // never reserved the excess. Restore once from the actual outputs. + await runner.runReadWriteTx(async (tx) => { + const group = (await tx.getRefreshGroup(remaining.refreshGroupId))!; + delete group.paymentRecovery; + group.inputPerCoin[0] = "TESTKUDOS:40"; + await tx.upsertRefreshGroup(group); + const restore = async () => + restorePaymentRecoveryMelts( + wex, + tx, + (await tx.getRefreshGroup(group.refreshGroupId))!, + new Map([[coin.coinPub, coin]]), + "txn:payment:refused" as TransactionIdStr, + ); + assert.equal(await restore(), true); + assert.equal(await restore(), false); + const groups = await tx.getRefreshGroupsByOriginatingTransaction( + "txn:payment:refused", + ); + assert.equal(groups.length, 3); + const pending = groups.filter( + (g) => g.statusPerCoin[0] === RefreshCoinStatus.Pending, + ); + assert.deepEqual( + pending.map((g) => g.inputPerCoin), + [["TESTKUDOS:4"]], + ); + }); + } + } finally { + await runner.close(); + } + }); +} + test("melt noreveal index must be an integer inside kappa", () => { assert.doesNotThrow(() => requireValidNorevealIndex(0, 3)); assert.doesNotThrow(() => requireValidNorevealIndex(2, 3)); diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -690,6 +690,12 @@ async function initRefreshSession( availableAmount, )} too small`, ); + if (refreshGroup.paymentRecovery) { + refreshGroup.paymentRecovery.settledPerCoin[coinIndex] = { + melted: Amounts.stringify(Amounts.zeroOfCurrency(currency)), + dust: input.amount, + }; + } input.update({ status: RefreshCoinStatus.Finished, expectedOutput: Amounts.stringify(Amounts.zeroOfCurrency(currency)), @@ -716,6 +722,9 @@ async function initRefreshSession( await tx.upsertCoinAvailability(car); } + // A dust input can become refreshable after redenomination. + if (refreshGroup.paymentRecovery) + delete refreshGroup.paymentRecovery.settledPerCoin[coinIndex]; const newSession: WalletRefreshSession = { ...(refreshGroup.reason === RefreshReason.Scheduled ? { autoRefreshMeltStarted: false } @@ -2037,6 +2046,11 @@ export async function handleRefreshMeltConflict( rg.originatingTransactionId, ); if (Amounts.isZero(correctedBalance)) { + if (isPaymentRecovery(rg)) { + const recovery = (rg.paymentRecovery ??= { settledPerCoin: {} }); + recovery.settledPerCoin[coinIndex] = { melted: correctedBalance }; + await settleRecoveryAllocation(tx, rg, input, correctedBalance); + } const refreshSession = await tx.getRefreshSession( ctx.refreshGroupId, coinIndex, @@ -2089,15 +2103,18 @@ export async function handleRefreshMeltConflict( } await destroyRefreshSession(tx, rg, refreshSession); await tx.deleteRefreshSession(ctx.refreshGroupId, coinIndex); + const retryAmount = isPaymentRecovery(rg) + ? Amounts.stringify(Amounts.min(input.amount, correctedBalance)) + : correctedBalance; const correctedOutput = await calculateRefreshOutput( ctx.wex, tx, rg.currency, - [{ coinPub: oldCoin.coinPub, amount: correctedBalance }], + [{ coinPub: oldCoin.coinPub, amount: retryAmount }], ); const previousOutput = input.expectedOutput; input.update({ - amount: correctedBalance, + amount: retryAmount, expectedOutput: Amounts.stringify(correctedOutput.outputPerCoin[0]), }); await initRefreshSession(ctx.wex, tx, rg, coinIndex); @@ -2234,6 +2251,150 @@ async function handleRefreshMeltNotFound( }); } +async function settleRecoveryAllocation( + tx: WalletDbTransaction, + group: WalletRefreshGroup, + input: RefreshInput, + melted: AmountLike, +): Promise<void> { + input.update({ amount: Amounts.stringify(melted) }); + const history = await tx.getCoinHistory(input.coinPub); + const id = constructTransactionIdentifier({ + tag: TransactionType.Refresh, + refreshGroupId: group.refreshGroupId, + }); + const allocation = history?.history.find( + (h) => h.type === "refresh" && h.transactionId === id, + ); + if ( + history && + allocation?.type === "refresh" && + Amounts.cmp(allocation.amount, melted) !== 0 + ) { + allocation.amount = Amounts.stringify(melted); + await tx.upsertCoinHistory(history); + } +} + +/** Settle the signed melt and reserve any remainder in the same transaction as + * the issued coins. A fresh group gives the next batch its own session seed + * and keeps the original session available for recoup. */ +async function settlePaymentRecoveryMelt( + wex: WalletExecutionContext, + tx: WalletDbTransaction, + group: WalletRefreshGroup, + input: RefreshInput, + melted: AmountLike, +): Promise<void> { + const recovery = (group.paymentRecovery ??= { settledPerCoin: {} }); + if (recovery.settledPerCoin[input.index]) return; + const remainder = Amounts.sub(input.amount, melted); + checkDbInvariant(!remainder.saturated, "invalid recovery melt value"); + recovery.settledPerCoin[input.index] = { melted: Amounts.stringify(melted) }; + const refund = + recovery.refundGroupId && (await tx.getRefundGroup(recovery.refundGroupId)); + if (refund) { + refund.amountEffective = Amounts.stringify( + Amounts.add(refund.amountEffective, input.expectedOutput).amount, + ); + await tx.upsertRefundGroup(refund); + } + await settleRecoveryAllocation(tx, group, input, melted); + if (Amounts.isZero(remainder.amount)) return; + const next = await createRefreshGroup( + wex, + tx, + group.currency, + [ + { + coinPub: input.coinPub, + amount: Amounts.stringify(remainder.amount), + }, + ], + group.reason, + group.originatingTransactionId, + { + remainder: true, + refundGroupId: recovery.refundGroupId, + }, + ); + if (refund) { + // Group creation may have refreshed the materialized transaction amounts. + const current = await tx.getRefundGroup(refund.refundGroupId); + if (current) { + const amounts = (current.transactionAmounts ??= {}); + (amounts.unsettledRefreshIds ??= []).push(next.refreshGroupId); + await tx.upsertRefundGroup(current); + } + } +} + +/** Older finished sessions only stored an input budget. Reconstruct the signed + * melt from its output denominations and fees before using it as evidence. */ +export async function restorePaymentRecoveryMelts( + wex: WalletExecutionContext, + tx: WalletDbTransaction, + group: WalletRefreshGroup, + selectedCoins: ReadonlyMap<string, WalletCoin>, + paymentId: TransactionIdStr, +): Promise<boolean> { + let changed = false; + for (const input of RefreshInput.all(group)) { + const coin = selectedCoins.get(input.coinPub); + if ( + !coin || + !input.amount || + !input.expectedOutput || + input.status !== RefreshCoinStatus.Finished || + group.paymentRecovery?.settledPerCoin[input.index] || + input.recoupGroupId + ) + continue; + group.originatingTransactionId ??= paymentId; + if (Amounts.isZero(input.expectedOutput)) { + if ( + group.reason === RefreshReason.PayMerchant && + Amounts.isNonZero(input.amount) + ) { + // The old wallet could have seen missing keys instead of genuine dust. + // Re-evaluate the change before using it to settle this payment. + await settlePaymentRecoveryMelt( + wex, + tx, + group, + input, + Amounts.zeroOfCurrency(group.currency), + ); + changed = true; + } + continue; + } + const session = await tx.getRefreshSession( + group.refreshGroupId, + input.index, + ); + if (session?.norevealIndex === undefined) continue; + const oldDenom = await getDenomInfo(wex, tx, coin); + checkDbInvariant(!!oldDenom, "missing payment denomination"); + let gross = Amounts.parseOrThrow(oldDenom.feeRefresh); + for (const { denomPubHash, count } of session.newDenoms) { + const d = await getDenomInfo(wex, tx, { + exchangeMasterPub: coin.exchangeMasterPub, + denomPubHash, + }); + checkDbInvariant(!!d, "missing refresh output denomination"); + gross = Amounts.add( + gross, + Amounts.mult(Amounts.add(d.value, d.feeWithdraw).amount, count).amount, + ).amount; + } + await settlePaymentRecoveryMelt(wex, tx, group, input, gross); + changed = true; + } + if (changed) await tx.upsertRefreshGroup(group); + return changed; +} + async function refreshReveal( wex: WalletExecutionContext, refreshGroupId: string, @@ -2485,6 +2646,15 @@ async function refreshReveal( status: RefreshCoinStatus.Finished, expectedOutput: rs.amountRefreshOutput, }); + if (isPaymentRecovery(rg)) { + await settlePaymentRecoveryMelt( + wex, + tx, + rg, + input, + derived.meltValueWithFee, + ); + } const existingCoins = await tx.getCoinsByPubs( coins.map((coin) => coin.coinPub), );