taler-typescript-core

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

commit 92dade61e41ebafa3f1f5ba933ccf43742142dba
parent 2454eedb44a07a07c4b3a2a3d9147a807e675602
Author: Florian Dold <dold@taler.net>
Date:   Sun, 22 Nov 2026 21:35:33 +0100

wallet-core: match purse refunds to the original coin deposits

Recompute the coin balance from signed history for purse recovery,
refresh and recoup. Exchanges can encode a purse refund with a waived
fee or with the denomination fee deducted from the signed amount.
Both restore the original deposit exactly once.

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-exchange-purse.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mpackages/taler-harness/src/integrationtests/testrunner.ts | 6+++++-
Apackages/taler-wallet-core/src/coin-history.ts | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/crypto/cryptoImplementation.test.ts | 47++++++++++++++++++++++++++++++++++++-----------
Mpackages/taler-wallet-core/src/crypto/cryptoImplementation.ts | 5++++-
Mpackages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts | 9++++++++-
Mpackages/taler-wallet-core/src/purse-deposit-reconciliation.ts | 51+++++++++------------------------------------------
Mpackages/taler-wallet-core/src/recoup.ts | 92+++++++++++++++++++++++++------------------------------------------------------
Mpackages/taler-wallet-core/src/refresh.test.ts | 71+++++++++++++++++++++++++++++++++++++++++++++--------------------------
Mpackages/taler-wallet-core/src/refresh.ts | 223++-----------------------------------------------------------------------------
Mpackages/taler-wallet-core/src/testing-check-coins.ts | 2+-
Mpackages/taler-wallet-core/src/testing-recover-coins.ts | 2+-
12 files changed, 490 insertions(+), 369 deletions(-)

diff --git a/packages/taler-harness/src/integrationtests/test-exchange-purse.ts b/packages/taler-harness/src/integrationtests/test-exchange-purse.ts @@ -20,7 +20,9 @@ import { AbsoluteTime, AmountString, + Amounts, ContractTermsUtil, + codecForCoinHistoryResponse, Duration, encodeCrock, getRandomBytes, @@ -42,6 +44,7 @@ import { topupReserveWithBank, withdrawCoin, } from "@gnu-taler/taler-wallet-core/dbless"; +import { makeLargeCoinTestConfig } from "../harness/denomStructures.js"; import { createSimpleTestkudosEnvironmentV3 } from "../harness/environments.js"; import { harnessLongpollQueue, @@ -52,10 +55,17 @@ import { /** * Test the exchange's purse API. */ -export async function runExchangePurseTest(t: GlobalTestState) { +async function testExchangePurse(t: GlobalTestState, expire: boolean) { // Set up test environment - const { bank, exchange } = await createSimpleTestkudosEnvironmentV3(t); + const { bank, exchange } = await createSimpleTestkudosEnvironmentV3(t, [ + { + ...makeLargeCoinTestConfig()[0], + value: "TESTKUDOS:8", + feeDeposit: "TESTKUDOS:0.1", + feeRefund: "TESTKUDOS:0.02", + }, + ]); const http = harnessHttpLib; const cryptoDisp = new CryptoDispatcher( @@ -136,7 +146,6 @@ export async function runExchangePurseTest(t: GlobalTestState) { ), }; - await cryptoApi.createEddsaKeypair({}); const pursePair = await cryptoApi.createEddsaKeypair({}); const mergePair = await cryptoApi.createEddsaKeypair({}); const contractPair = await cryptoApi.createEddsaKeypair({}); @@ -223,6 +232,59 @@ export async function runExchangePurseTest(t: GlobalTestState) { console.log(j2s(statusRespBody)); t.assertTrue(statusRespBody.merge_timestamp === undefined); + if (expire) { + await exchange.stop(); + exchange.setTimetravel( + Duration.toMilliseconds(Duration.fromSpec({ minutes: 2 })), + ); + await exchange.start(); + await exchange.runExpireOnce(); + } else { + const { sig } = await cryptoApi.signDeletePurse({ + pursePriv: pursePair.priv, + }); + const res = await http.fetch( + new URL(`purses/${pursePub}`, exchange.baseUrl).href, + { + method: "DELETE", + headers: { "Taler-Purse-Signature": sig }, + }, + ); + t.assertDeepEqual(res.status, HttpStatusCode.NoContent); + } + const { sig } = await cryptoApi.signCoinHistoryRequest({ + ...coin, + startOffset: 0, + }); + const res = await http.fetch( + new URL(`coins/${coin.coinPub}/history`, exchange.baseUrl).href, + { + headers: { "Taler-Coin-History-Signature": sig }, + }, + ); + t.assertDeepEqual(res.status, HttpStatusCode.Ok); + const { balance, history } = codecForCoinHistoryResponse().decode( + await res.json(), + ); + t.assertAmountEquals(balance, d1.value); + t.assertDeepEqual(history.length, 2); + const refund = history.find((entry) => entry.type === "PURSE-REFUND"); + t.assertTrue(!!refund); + t.assertTrue( + Amounts.isZero(refund.refund_fee) || + Amounts.cmp(refund.refund_fee, d1.feeRefund) === 0, + ); + t.assertAmountEquals( + Amounts.add(refund.amount, refund.refund_fee).amount, + amount, + ); + const checked = await cryptoApi.isValidCoinHistory({ + ...d1, + coinPub: coin.coinPub, + denomPubHash: coin.denomPubHash, + history, + }); + t.assertTrue(checked.valid); } catch (e) { if (e instanceof TalerError) { console.log(e); @@ -234,4 +296,10 @@ export async function runExchangePurseTest(t: GlobalTestState) { } } -runExchangePurseTest.suites = ["wallet"]; +export function runExchangePurseTest(t: GlobalTestState) { + return testExchangePurse(t, false); +} +export function runExchangePurseExpiryTest(t: GlobalTestState) { + return testExchangePurse(t, true); +} +runExchangePurseTest.suites = runExchangePurseExpiryTest.suites = ["wallet"]; diff --git a/packages/taler-harness/src/integrationtests/testrunner.ts b/packages/taler-harness/src/integrationtests/testrunner.ts @@ -75,7 +75,10 @@ import { runExchangeManagementTest } from "./test-exchange-management.js"; import { runExchangeCurrencyChangeTest } from "./test-exchange-currency-change.js"; import { runExchangeMasterPubChangeTest } from "./test-exchange-master-pub-change.js"; import { runExchangeMerchantKycAuthTest } from "./test-exchange-merchant-kyc-auth.js"; -import { runExchangePurseTest } from "./test-exchange-purse.js"; +import { + runExchangePurseTest, + runExchangePurseExpiryTest, +} from "./test-exchange-purse.js"; import { runExchangeTimetravelTest } from "./test-exchange-timetravel.js"; import { runFeeRegressionTest } from "./test-fee-regression.js"; import { runForcedSelectionTest } from "./test-forced-selection.js"; @@ -367,6 +370,7 @@ const allTests: TestMainFunction[] = [ runCoinselLegacy2024Test, runKycChallengerTest, runExchangePurseTest, + runExchangePurseExpiryTest, runExchangeDepositTest, runExchangeEphemeralTest, runMerchantExchangeConfusionTest, diff --git a/packages/taler-wallet-core/src/coin-history.ts b/packages/taler-wallet-core/src/coin-history.ts @@ -0,0 +1,275 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + 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 { + AmountString, + Amounts, + assertUnreachable, + CoinHistoryResponse, + DenominationInfo, + HttpStatusCode, + TalerError, + TalerErrorCode, + throwUnexpectedResponse, +} from "@gnu-taler/taler-util"; +import { WalletCoin } from "./db/records.js"; +import { requireValidExchangeCoinHistory } from "./exchange-signatures.js"; +import { requireExchangeCoinUseConfirmedOrThrow } from "./exchanges.js"; +import { WalletExecutionContext, walletExchangeClient } from "./wallet.js"; + +/** A coin-unknown reply is the only recoverable absence of history. */ +export async function readVerifiedCoinHistory( + wex: WalletExecutionContext, + coin: WalletCoin, + denomination: DenominationInfo, +) { + const signature = await wex.cryptoApi.signCoinHistoryRequest({ + coinPriv: coin.coinPriv, + coinPub: coin.coinPub, + startOffset: 0, + }); + await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl); + const response = await walletExchangeClient( + coin.exchangeBaseUrl, + wex, + ).getCoinHistory(coin.coinPub, signature.sig); + if (response.case !== "ok") { + if ( + response.case === HttpStatusCode.NotFound && + response.detail?.code === TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN + ) { + return response; + } + throwUnexpectedResponse(response); + } + await requireValidExchangeCoinHistory(wex, { + exchangeBaseUrl: coin.exchangeBaseUrl, + coinPub: coin.coinPub, + denomination, + response: response.body, + }); + const balance = validateAndRecomputeCoinHistoryBalance( + coin.denomPubHash, + denomination.value, + response.body, + ); + return { ...response, body: { ...response.body, balance } }; +} + +/** + * Recompute a coin balance from the typed history instead of trusting the + * unauthenticated top-level aggregate. + */ +export function validateAndRecomputeCoinHistoryBalance( + denomPubHash: string, + denomValue: AmountString, + response: CoinHistoryResponse, +): AmountString { + if (response.h_denom_pub !== denomPubHash) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "coin history denomination does not match the requested coin", + ); + } + let balance = Amounts.parseOrThrow(denomValue); + let previousOffset = -1; + const deposits = new Map< + string, + { + amount: AmountString; + fee: AmountString; + refunded: AmountString; + } + >(); + const purseDeposits = new Map<string, AmountString>(); + const refundedPurses = new Set<string>(); + // Refunds and subsequent spends depend on the order of the ledger entries. + const ordered = [...response.history].sort( + (a, b) => a.history_offset - b.history_offset, + ); + for (const item of ordered) { + if ( + !Number.isSafeInteger(item.history_offset) || + item.history_offset <= previousOffset + ) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "coin history contains an invalid or duplicate offset", + ); + } + previousOffset = item.history_offset; + let amount: AmountString; + let addsValue = false; + switch (item.type) { + case "DEPOSIT": + deposits.set(`${item.merchant_pub}:${item.h_contract_terms}`, { + amount: item.amount, + fee: item.deposit_fee, + refunded: Amounts.stringify( + Amounts.zeroOfCurrency(Amounts.currencyOf(denomValue)), + ), + }); + amount = item.amount; + break; + case "PURSE-DEPOSIT": + if (purseDeposits.has(item.purse_pub)) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "coin history contains duplicate deposits for the purse", + ); + } + purseDeposits.set(item.purse_pub, item.amount); + if (item.refunded) refundedPurses.add(item.purse_pub); + amount = item.amount; + break; + case "RECOUP-WITHDRAW": + case "RECOUP-REFRESH": + case "MELT": + amount = item.amount; + break; + case "REVEAL": + // The preceding MELT already accounts for these fresh signatures. + continue; + case "RESERVE-OPEN-DEPOSIT": + amount = item.coin_contribution; + break; + case "REFUND": { + const deposit = deposits.get( + `${item.merchant_pub}:${item.h_contract_terms}`, + ); + if (!deposit) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "coin history refund has no matching deposit", + ); + } + // History reports the net refund. The exchange also returns the + // deposit fee once gross cumulative refunds cover this deposit. + const grossRefund = Amounts.add(item.amount, item.refund_fee); + const totalRefund = Amounts.add(deposit.refunded, grossRefund.amount); + if ( + grossRefund.saturated || + totalRefund.saturated || + Amounts.cmp(totalRefund.amount, deposit.amount) > 0 + ) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "coin history refunds exceed their deposit", + ); + } + amount = item.amount; + if ( + Amounts.cmp(deposit.refunded, deposit.amount) < 0 && + Amounts.cmp(totalRefund.amount, deposit.amount) === 0 + ) { + const withWaivedFee = Amounts.add(amount, deposit.fee); + if (withWaivedFee.saturated) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "refunded deposit fee overflows the coin balance", + ); + } + amount = Amounts.stringify(withWaivedFee.amount); + } + deposit.refunded = Amounts.stringify(totalRefund.amount); + addsValue = true; + break; + } + case "PURSE-REFUND": { + const deposit = purseDeposits.get(item.purse_pub); + // Legacy exchanges signed the amount net of the denomination refund fee. + const gross = Amounts.add(item.amount, item.refund_fee); + if ( + !deposit || + !refundedPurses.delete(item.purse_pub) || + gross.saturated || + Amounts.cmp(gross.amount, deposit) !== 0 + ) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "purse refund does not match its original deposit", + ); + } + amount = deposit; + addsValue = true; + break; + } + case "RECOUP-REFRESH-RECEIVER": + amount = item.amount; + addsValue = true; + break; + default: + assertUnreachable(item); + } + if ( + "h_denom_pub" in item && + item.h_denom_pub !== undefined && + item.h_denom_pub !== denomPubHash + ) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + `coin history ${item.type} entry has a different denomination`, + ); + } + if ( + !Amounts.isSameCurrency( + Amounts.currencyOf(amount), + Amounts.currencyOf(denomValue), + ) + ) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + `coin history ${item.type} entry has a different currency`, + ); + } + const result = addsValue + ? Amounts.add(balance, amount) + : Amounts.sub(balance, amount); + if (result.saturated) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + `coin history ${item.type} entry violates value conservation`, + ); + } + balance = result.amount; + } + if (refundedPurses.size) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "missing purse refund in coin history", + ); + } + const recomputed = Amounts.stringify(balance); + if (Amounts.cmp(recomputed, response.balance) !== 0) { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + `coin history balance ${response.balance} does not match recomputed ${recomputed}`, + ); + } + return recomputed; +} diff --git a/packages/taler-wallet-core/src/crypto/cryptoImplementation.test.ts b/packages/taler-wallet-core/src/crypto/cryptoImplementation.test.ts @@ -422,14 +422,19 @@ test("coin history verifies purse deposit and refund evidence", async () => { .put(decodeCrock(pursePub)) .put(hash(stringToBytes(exchangeBaseUrl + "\0"))) .build(); - const refundPreimage = buildSigPS( - TalerSignaturePurpose.EXCHANGE_CONFIRM_PURSE_REFUND, - ) - .put(decodeCrock(pursePub)) - .put(decodeCrock(coinPub)) - .put(bufferFromAmount(Amounts.parseOrThrow(refundAmount))) - .put(bufferFromAmount(Amounts.parseOrThrow(refundFee))) - .build(); + const signRefund = (amount: AmountString, fee: AmountString) => { + const preimage = buildSigPS( + TalerSignaturePurpose.EXCHANGE_CONFIRM_PURSE_REFUND, + ) + .put(decodeCrock(pursePub)) + .put(decodeCrock(coinPub)) + .put(bufferFromAmount(amount)) + .put(bufferFromAmount(fee)) + .build(); + return encodeCrock( + eddsaSign(preimage, signKey.eddsaPriv), + ) as EddsaSignatureString; + }; const history: CoinSpendHistoryItem[] = [ { type: "PURSE-DEPOSIT" as const, @@ -451,9 +456,7 @@ test("coin history verifies purse deposit and refund evidence", async () => { refund_fee: refundFee, purse_pub: pursePub, exchange_pub: encodeCrock(signKey.eddsaPub) as EddsaPublicKeyString, - exchange_sig: encodeCrock( - eddsaSign(refundPreimage, signKey.eddsaPriv), - ) as EddsaSignatureString, + exchange_sig: signRefund(refundAmount, refundFee), }, ]; const request = { @@ -465,6 +468,28 @@ test("coin history verifies purse deposit and refund evidence", async () => { history, }; + for (const [fee, valid] of [ + ["TESTKUDOS:0", true], + ["TESTKUDOS:0.01", false], + ["EUR:0", false], + ] as const) { + assert.deepEqual( + await nativeCryptoR.isValidCoinHistory(nativeCryptoR, { + ...request, + history: history.map((item) => + item.type === "PURSE-REFUND" + ? { + ...item, + amount: depositAmount, + refund_fee: fee, + exchange_sig: signRefund(depositAmount, fee), + } + : item, + ), + }), + { valid }, + ); + } assert.deepStrictEqual( await nativeCryptoR.isValidCoinHistory(nativeCryptoR, request), { valid: true }, diff --git a/packages/taler-wallet-core/src/crypto/cryptoImplementation.ts b/packages/taler-wallet-core/src/crypto/cryptoImplementation.ts @@ -1989,7 +1989,10 @@ export const nativeCryptoR: TalerCryptoInterfaceR = { break; } case "PURSE-REFUND": { - if (!feeMatches(item.refund_fee, req.feeRefund)) { + if ( + !feeMatches(item.refund_fee, req.feeRefund) && + !Amounts.isZero(item.refund_fee) + ) { return { valid: false }; } const preimage = buildSigPS( diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts @@ -115,8 +115,15 @@ function unknownCoinContext( }, }; const tx = { + async getExchange() { + return undefined; + }, async getCoin() { - return { coinPub: args.coinPub, coinPriv: "coin-priv" }; + return { + coinPub: args.coinPub, + coinPriv: "coin-priv", + exchangeBaseUrl: args.exchangeBaseUrl, + }; }, } as unknown as WalletDbTransaction; return { diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.ts @@ -19,18 +19,14 @@ import { Amounts, CoinPurseDepositTransaction, CoinRefreshRequest, - HttpStatusCode, TalerError, TalerErrorCode, - throwUnexpectedResponse, } from "@gnu-taler/taler-util"; import { checkDbInvariant } from "@gnu-taler/taler-util"; -import { requireValidExchangeCoinHistory } from "./exchange-signatures.js"; -import { validateAndRecomputeCoinHistoryBalance } from "./refresh.js"; +import { readVerifiedCoinHistory } from "./coin-history.js"; import { getDenomInfo, WalletExecutionContext, - walletExchangeClient, } from "./wallet.js"; export interface PurseDepositSelection { @@ -115,47 +111,18 @@ export async function reconcilePurgedPurseDeposits( const recoverable: CoinRefreshRequest[] = []; const committedCoinPubs = new Set<string>(); - const exchangeClient = walletExchangeClient(args.exchangeBaseUrl, wex); for (let i = 0; i < loaded.length; i++) { const { coin, denomination } = loaded[i]; - const historySig = await wex.cryptoApi.signCoinHistoryRequest({ - coinPriv: coin.coinPriv, - coinPub: coin.coinPub, - startOffset: 0, - }); - const historyResp = await exchangeClient.getCoinHistory( - coin.coinPub, - historySig.sig, - ); + const historyResp = await readVerifiedCoinHistory(wex, coin, denomination); if (historyResp.case !== "ok") { - if ( - historyResp.case === HttpStatusCode.NotFound && - historyResp.detail?.code === - TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN - ) { - // A selected coin whose deposit never reached the exchange has no - // history yet. Schedule recovery, but do not make the old coin fresh: - // only a successful refresh establishes the recovered balance. - recoverable.push({ - coinPub: coin.coinPub, - amount: args.selection.contributions[i], - }); - continue; - } - throwUnexpectedResponse(historyResp); + // The exchange has never seen this coin. Refresh verifies its value + // before the wallet makes the recovered funds available. + recoverable.push({ + coinPub: coin.coinPub, + amount: args.selection.contributions[i], + }); + continue; } - await requireValidExchangeCoinHistory(wex, { - exchangeBaseUrl: args.exchangeBaseUrl, - coinPub: coin.coinPub, - denomination, - response: historyResp.body, - }); - validateAndRecomputeCoinHistoryBalance( - coin.denomPubHash, - denomination.value, - historyResp.body, - ); - const outcome = classifyPurseDepositCoinHistory( historyResp.body.history.filter( (item): item is CoinPurseDepositTransaction => diff --git a/packages/taler-wallet-core/src/recoup.ts b/packages/taler-wallet-core/src/recoup.ts @@ -91,7 +91,6 @@ import { createRefreshGroup, recoverRefreshCoinNonce, deriveRefreshSession, - validateAndRecomputeCoinHistoryBalance, bindRefreshesToRecoup, settleRefreshesForRecoup, } from "./refresh.js"; @@ -115,12 +114,10 @@ import { } from "./withdraw.js"; export { reconstructWithdrawalBatchHPlanchets } from "./withdraw.js"; +import { readVerifiedCoinHistory } from "./coin-history.js"; import { WalletDbTransaction } from "./db/transaction.js"; -import { - requireValidRecoupBatchConfirmation, - requireValidExchangeCoinHistory, -} from "./exchange-signatures.js"; +import { requireValidRecoupBatchConfirmation } from "./exchange-signatures.js"; const logger = new Logger("operations/recoup.ts"); @@ -992,67 +989,36 @@ export async function processRecoupForCoin( !!denomination, "missing denomination for recoup reconciliation", ); - const historySig = await wex.cryptoApi.signCoinHistoryRequest({ - coinPriv: coin.coinPriv, - coinPub: coin.coinPub, - startOffset: 0, - }); - await requireExchangeCoinUseConfirmedOrThrow(wex, coin.exchangeBaseUrl); - const historyResponse = await walletExchangeClient( - coin.exchangeBaseUrl, - wex, - ).getCoinHistory(coin.coinPub, historySig.sig); - let residualAmount = denomination.value; - let historyItems: import("@gnu-taler/taler-util").CoinSpendHistoryItem[] = []; - if (historyResponse.case === "ok") { - const history = historyResponse.body; - historyItems = history.history; - await requireValidExchangeCoinHistory(wex, { - exchangeBaseUrl: coin.exchangeBaseUrl, - coinPub: coin.coinPub, - denomination, - response: history, - }); - const residual = validateAndRecomputeCoinHistoryBalance( - coin.denomPubHash, - denomination.value, - history, + const response = await readVerifiedCoinHistory(wex, coin, denomination); + const history = response.case === "ok" ? response.body : undefined; + const residualAmount = history?.balance ?? denomination.value; + const historyItems = history?.history ?? []; + const previousRecoup = historyItems.find( + (h) => h.type === "RECOUP-WITHDRAW" || h.type === "RECOUP-REFRESH", + ); + if (previousRecoup) { + const source = coin.coinSource; + checkDbInvariant( + (previousRecoup.type === "RECOUP-WITHDRAW" && + source.type === CoinSourceType.Withdraw && + previousRecoup.reserve_pub === source.reservePub) || + (previousRecoup.type === "RECOUP-REFRESH" && + source.type === CoinSourceType.Refresh && + previousRecoup.old_coin_pub === source.oldCoinPub), + "recoup history destination does not match coin source", ); - const previousRecoup = history.history.find( - (h) => h.type === "RECOUP-WITHDRAW" || h.type === "RECOUP-REFRESH", + await wex.runWalletDbTx((tx) => + recordRecoupCredit( + wex, + tx, + recoupGroupId, + coinIdx, + coin, + previousRecoup.amount, + ), ); - if (previousRecoup) { - const source = coin.coinSource; - checkDbInvariant( - (previousRecoup.type === "RECOUP-WITHDRAW" && - source.type === CoinSourceType.Withdraw && - previousRecoup.reserve_pub === source.reservePub) || - (previousRecoup.type === "RECOUP-REFRESH" && - source.type === CoinSourceType.Refresh && - previousRecoup.old_coin_pub === source.oldCoinPub), - "recoup history destination does not match coin source", - ); - await wex.runWalletDbTx((tx) => - recordRecoupCredit( - wex, - tx, - recoupGroupId, - coinIdx, - coin, - previousRecoup.amount, - ), - ); - return; - } - residualAmount = residual; - } else if ( - historyResponse.case !== HttpStatusCode.NotFound || - historyResponse.detail?.code !== - TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN - ) { - throwUnexpectedResponse(historyResponse); + return; } - if (!(await bindRefreshesToRecoup(wex, coin, recoupGroupId, historyItems))) return; if (Amounts.isZero(residualAmount)) { diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts @@ -13,6 +13,7 @@ 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 { validateAndRecomputeCoinHistoryBalance } from "./coin-history.js"; import { AbsoluteTime, Amounts, @@ -33,7 +34,6 @@ import { getTotalRefreshCostInternal, RefreshTransactionContext, requireValidNorevealIndex, - validateAndRecomputeCoinHistoryBalance, } from "./refresh.js"; import { DenominationVerificationStatus, @@ -409,30 +409,49 @@ test("coin history rejects unbound or non-conserving aggregates", () => { ); }); -test("coin history accounts for the waived fee of refunded purse deposits", () => { - const response = { - h_denom_pub: "denom", - balance: "TESTKUDOS:10.08", - history: [ - { - type: "PURSE-DEPOSIT", - history_offset: 0, - amount: "TESTKUDOS:3", - deposit_fee: "TESTKUDOS:0.1", - refunded: true, - h_denom_pub: "denom", - }, - { - type: "PURSE-REFUND", - history_offset: 1, - amount: "TESTKUDOS:2.98", - refund_fee: "TESTKUDOS:0.02", - }, - ], - } as never; - assert.strictEqual( - validateAndRecomputeCoinHistoryBalance("denom", "TESTKUDOS:10", response), - "TESTKUDOS:10.08", +test("current and legacy purse refunds restore the gross deposit exactly once", () => { + const deposit = { + type: "PURSE-DEPOSIT", + history_offset: 0, + purse_pub: "purse", + amount: "TESTKUDOS:3", + deposit_fee: "TESTKUDOS:0.1", + refunded: true, + }; + const refund = { + type: "PURSE-REFUND", + history_offset: 1, + purse_pub: "purse", + amount: "TESTKUDOS:3", + refund_fee: "TESTKUDOS:0", + }; + const balance = (history: unknown[], reported = "TESTKUDOS:10") => + validateAndRecomputeCoinHistoryBalance("denom", "TESTKUDOS:10", { + history, + h_denom_pub: "denom", + balance: reported, + } as never); + assert.equal(balance([deposit, refund]), "TESTKUDOS:10"); + assert.equal( + balance([ + deposit, + { ...refund, amount: "TESTKUDOS:2.98", refund_fee: "TESTKUDOS:0.02" }, + ]), + "TESTKUDOS:10", + ); + assert.throws(() => balance([deposit, refund], "TESTKUDOS:10.1"), /balance/); + assert.throws(() => balance([deposit]), /missing purse refund/); + assert.throws( + () => balance([deposit, { ...refund, purse_pub: "other" }]), + /does not match/, + ); + assert.throws( + () => balance([deposit, { ...refund, amount: "TESTKUDOS:2.9" }]), + /does not match/, + ); + assert.throws( + () => balance([deposit, refund, { ...refund, history_offset: 2 }]), + /does not match/, ); }); @@ -461,7 +480,7 @@ for (const refundAmounts of [["TESTKUDOS:3"], ["TESTKUDOS:1", "TESTKUDOS:2"]]) { merchant_pub: "merchant", h_contract_terms: "contract", })), - ], + ].reverse(), } as never; assert.strictEqual( validateAndRecomputeCoinHistoryBalance("denom", "TESTKUDOS:10", history), diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -24,6 +24,7 @@ import { ensureRecoupProvenance } from "./recoup.js"; /** * Imports. */ +import { readVerifiedCoinHistory } from "./coin-history.js"; import { settledRefreshOutput } from "./transaction-amounts.js"; import { addPermanentCoinFailure } from "./transaction-reasons.js"; import { AutoRefreshOutputPlan, evaluateAutoRefresh } from "./autoRefresh.js"; @@ -39,7 +40,6 @@ import { checkDbInvariant, checkLogicInvariant, CoinRefreshRequest, - CoinHistoryResponse, CoinStatus, DenominationInfo, DenomKeyType, @@ -96,10 +96,7 @@ import { TaskRunResultType, TransactionContext, } from "./common.js"; -import { - requireValidDirectExchangeRefundConfirmation, - requireValidExchangeCoinHistory, -} from "./exchange-signatures.js"; +import { requireValidDirectExchangeRefundConfirmation } from "./exchange-signatures.js"; import { RefreshNewDenomInfo } from "./crypto/cryptoTypes.js"; import { CryptoApiStoppedError } from "./crypto/workers/crypto-dispatcher.js"; import { @@ -1653,36 +1650,15 @@ export async function handleRefreshMeltConflict( if (result !== "refused") return; } - const historySig = await ctx.wex.cryptoApi.signCoinHistoryRequest({ - coinPriv: oldCoin.coinPriv, - coinPub: oldCoin.coinPub, - startOffset: 0, - }); - - const exchangeClient = walletExchangeClient(oldCoin.exchangeBaseUrl, ctx.wex); - const historyResp = await exchangeClient.getCoinHistory( - oldCoin.coinPub, - historySig.sig, - ); - - const historyJson = succeedOrThrow(historyResp); - logger.info(`coin history: ${j2s(historyJson)}`); 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; }); - await requireValidExchangeCoinHistory(ctx.wex, { - exchangeBaseUrl: oldCoin.exchangeBaseUrl, - coinPub: oldCoin.coinPub, - denomination, - response: historyJson, - }); - const correctedBalance = validateAndRecomputeCoinHistoryBalance( - oldCoin.denomPubHash, - denomination.value, - historyJson, + const history = succeedOrThrow( + await readVerifiedCoinHistory(ctx.wex, oldCoin, denomination), ); + const correctedBalance = history.balance; await ctx.wex.runWalletDbTx(async (tx) => { const [rg, h] = await ctx.getRecordHandle(tx); @@ -1772,195 +1748,6 @@ export async function handleRefreshMeltConflict( }); } -/** - * Recompute a coin balance from the typed history instead of trusting the - * unauthenticated top-level aggregate. - */ -export function validateAndRecomputeCoinHistoryBalance( - denomPubHash: string, - denomValue: AmountString, - response: CoinHistoryResponse, -): AmountString { - if (response.h_denom_pub !== denomPubHash) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "coin history denomination does not match the requested coin", - ); - } - let balance = Amounts.parseOrThrow(denomValue); - const offsets = new Set<number>(); - const deposits = new Map< - string, - { - amount: AmountString; - fee: AmountString; - refunded: AmountString; - } - >(); - for (const item of response.history) { - if ( - !Number.isInteger(item.history_offset) || - item.history_offset < 0 || - offsets.has(item.history_offset) - ) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "coin history contains an invalid or duplicate offset", - ); - } - offsets.add(item.history_offset); - let amount: AmountString; - let addsValue = false; - switch (item.type) { - case "DEPOSIT": - deposits.set(`${item.merchant_pub}:${item.h_contract_terms}`, { - amount: item.amount, - fee: item.deposit_fee, - refunded: Amounts.stringify( - Amounts.zeroOfCurrency(Amounts.currencyOf(denomValue)), - ), - }); - amount = item.amount; - break; - case "RECOUP-WITHDRAW": - case "RECOUP-REFRESH": - case "PURSE-DEPOSIT": - amount = item.amount; - break; - case "MELT": - amount = item.amount; - break; - case "REVEAL": - // Carries the signatures over the fresh coins of a melt, whose MELT - // entry already accounts for the value. - continue; - case "RESERVE-OPEN-DEPOSIT": - amount = item.coin_contribution; - break; - case "REFUND": { - const deposit = deposits.get( - `${item.merchant_pub}:${item.h_contract_terms}`, - ); - if (!deposit) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "coin history refund has no matching deposit", - ); - } - // History reports the net refund. The exchange also returns the - // deposit fee once gross cumulative refunds cover this deposit. - const grossRefund = Amounts.add(item.amount, item.refund_fee); - const totalRefund = Amounts.add(deposit.refunded, grossRefund.amount); - if ( - grossRefund.saturated || - totalRefund.saturated || - Amounts.cmp(totalRefund.amount, deposit.amount) > 0 - ) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "coin history refunds exceed their deposit", - ); - } - amount = item.amount; - if ( - Amounts.cmp(deposit.refunded, deposit.amount) < 0 && - Amounts.cmp(totalRefund.amount, deposit.amount) === 0 - ) { - const withWaivedFee = Amounts.add(amount, deposit.fee); - if (withWaivedFee.saturated) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "refunded deposit fee overflows the coin balance", - ); - } - amount = Amounts.stringify(withWaivedFee.amount); - } - deposit.refunded = Amounts.stringify(totalRefund.amount); - addsValue = true; - break; - } - case "RECOUP-REFRESH-RECEIVER": - case "PURSE-REFUND": - amount = item.amount; - addsValue = true; - break; - default: - assertUnreachable(item); - } - if (item.type === "PURSE-DEPOSIT" && item.refunded) { - if ( - !Amounts.isSameCurrency( - Amounts.currencyOf(item.deposit_fee), - Amounts.currencyOf(denomValue), - ) - ) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "refunded purse deposit has a fee in another currency", - ); - } - const waivedFeeBalance = Amounts.add(balance, item.deposit_fee); - if (waivedFeeBalance.saturated) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - "refunded purse deposit fee overflows the coin balance", - ); - } - balance = waivedFeeBalance.amount; - } - if ( - "h_denom_pub" in item && - item.h_denom_pub !== undefined && - item.h_denom_pub !== denomPubHash - ) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - `coin history ${item.type} entry has a different denomination`, - ); - } - if ( - !Amounts.isSameCurrency( - Amounts.currencyOf(amount), - Amounts.currencyOf(denomValue), - ) - ) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - `coin history ${item.type} entry has a different currency`, - ); - } - const result = addsValue - ? Amounts.add(balance, amount) - : Amounts.sub(balance, amount); - if (result.saturated) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - `coin history ${item.type} entry violates value conservation`, - ); - } - balance = result.amount; - } - const recomputed = Amounts.stringify(balance); - if (Amounts.cmp(recomputed, response.balance) !== 0) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - {}, - `coin history balance ${response.balance} does not match recomputed ${recomputed}`, - ); - } - return recomputed; -} - async function handleRefreshMeltNotFound( ctx: RefreshTransactionContext, coinIndex: number, diff --git a/packages/taler-wallet-core/src/testing-check-coins.ts b/packages/taler-wallet-core/src/testing-check-coins.ts @@ -33,7 +33,7 @@ import { import { WalletCoin, WalletDenomination } from "./db/records.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { requireValidExchangeCoinHistory } from "./exchange-signatures.js"; -import { validateAndRecomputeCoinHistoryBalance } from "./refresh.js"; +import { validateAndRecomputeCoinHistoryBalance } from "./coin-history.js"; import { WalletExecutionContext, denomRefKey, diff --git a/packages/taler-wallet-core/src/testing-recover-coins.ts b/packages/taler-wallet-core/src/testing-recover-coins.ts @@ -14,6 +14,7 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ +import { validateAndRecomputeCoinHistoryBalance } from "./coin-history.js"; import { AbsoluteTime, AgeRestriction, @@ -69,7 +70,6 @@ import { deriveRefreshSession, RefreshTransactionContext, requireValidMeltConfirmation, - validateAndRecomputeCoinHistoryBalance, } from "./refresh.js"; import { ensureCoinAvailabilityCounters,