taler-typescript-core

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

commit 01ee40218f4e7b934fa9169253eb29446697a211
parent 0ea690ba8f6435660bca0caeeae274948ab37791
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 22:46:36 +0100

wallet-core: use a separate coin lock for each exchange

Checking a rejected melt can mean waiting for coin history or a refund.
Let payments at other exchanges proceed while that request is pending.

Diffstat:
Mpackages/taler-wallet-core/src/autoRefreshLifecycle.test.ts | 48++++++++++++++++++++++++++++++++++++++++++++----
Mpackages/taler-wallet-core/src/pay-merchant.ts | 20++++++++++----------
Mpackages/taler-wallet-core/src/recoup.ts | 7++++---
Mpackages/taler-wallet-core/src/refresh.ts | 9+++++----
Mpackages/taler-wallet-core/src/testing-recover-coins.ts | 5+++--
Mpackages/taler-wallet-core/src/wallet.ts | 5++++-
6 files changed, 70 insertions(+), 24 deletions(-)

diff --git a/packages/taler-wallet-core/src/autoRefreshLifecycle.test.ts b/packages/taler-wallet-core/src/autoRefreshLifecycle.test.ts @@ -21,6 +21,7 @@ import { CoinStatus, DenomKeyType, encodeCrock, + openPromise, RefreshReason, ScopeType, TalerErrorCode, @@ -43,12 +44,13 @@ import { import { dummyHttpResponse, HeadersImpl } from "@gnu-taler/taler-util/http"; import { WalletDbTransaction } from "./db/transaction.js"; import { WalletExecutionContext } from "./wallet.js"; +import { SequentialLocks } from "./sequential-locks.js"; import { prepareAutoRefreshSession, processRefreshGroup } from "./refresh.js"; import { addRefreshBalanceInfo } from "./autoRefreshBalance.js"; import { handleDismissWalletWarning } from "./requests.js"; import { DAY_MS, selectAutoRefreshOutputs } from "./autoRefresh.js"; -function fixture() { +function fixture(exchangeBaseUrl = "https://exchange/") { const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); const stamp = (days: number) => timestampProtocolToDb({ t_s: Math.floor((now + days * DAY_MS) / 1000) }); @@ -56,7 +58,7 @@ function fixture() { currency: "TEST", value: "TEST:1", denomPubHash: "old", - exchangeBaseUrl: "https://exchange/", + exchangeBaseUrl, exchangeMasterPub: "master", denomPub: { cipher: DenomKeyType.Rsa, age_mask: 0, rsa_public_key: "rsa" }, fees: { @@ -170,8 +172,8 @@ test("an ambiguous melt retains its commitment despite loss of eligibility", asy assert.equal(JSON.stringify(session), before); }); -function meltFixture() { - const f = fixture(); +function meltFixture(url?: string) { + const f = fixture(url); const { tx, wex, session, rg, old, output } = f; const cts = CancellationToken.create(); const rc = encodeCrock(new Uint8Array(64).fill(23)); @@ -473,6 +475,44 @@ test("a scheduled retry fails for insufficient funds only when verified history assert.equal(rg.expectedOutputPerCoin[0], "TEST:0"); }); +test("a rejected melt serializes exchange coin requests while checking history", async () => { + const retry = meltFixture(); + const sameExchange = meltFixture(); + const otherExchange = meltFixture("https://other-exchange/"); + const locks = new SequentialLocks(); + for (const f of [retry, sameExchange, otherExchange]) { + f.wex.ws.runSequentialized = locks.run.bind(locks); + } + retry.session.autoRefreshMeltStarted = true; + retry.replies.set("/coins/coin/history", { + status: 404, + body: { code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN }, + }); + const readingHistory = openPromise<void>(); + const resume = openPromise<void>(); + const fetch = retry.wex.http.fetch.bind(retry.wex.http); + retry.wex.http.fetch = async (url, options) => { + if (new URL(url).pathname.endsWith("/history")) { + readingHistory.resolve(); + await resume.promise; + } + return fetch(url, options); + }; + const pending = retry.run(); + await readingHistory.promise; + const same = sameExchange.run(); + const other = otherExchange.run(); + try { + await new Promise<void>((resolve) => setImmediate(resolve)); + assert.deepEqual(otherExchange.requests, ["/melt"]); + assert.deepEqual(sameExchange.requests, []); + } finally { + resume.resolve(); + await Promise.all([pending, same, other]); + } + assert.deepEqual(sameExchange.requests, ["/melt"]); +}); + test("a scheduled retry settles an unknown coin only when its history also returns coin unknown", async () => { const { session, rg, old, replies, run } = meltFixture(); session.autoRefreshMeltStarted = true; diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -204,7 +204,7 @@ import { import { suspendForLongpoll, denomRefKey, - EXCHANGE_COINS_LOCK, + exchangeCoinLock, getDenomInfos, getDenomInfo, WalletExecutionContext, @@ -4283,12 +4283,13 @@ async function processPurchasePay( wex, { timeout: getPayRequestTimeout(purchase) }, ); + const exchanges = [ + ...new Set(depositPermissions.map((p) => p.exchange_url)), + ]; const resp = await wex.ws.runSequentialized( - [EXCHANGE_COINS_LOCK], + exchanges.map(exchangeCoinLock), async () => { - for (const exchangeBaseUrl of new Set( - depositPermissions.map((x) => x.exchange_url), - )) { + for (const exchangeBaseUrl of exchanges) { await requireExchangeCoinUseConfirmedOrThrow(wex, exchangeBaseUrl); } return merchantClient.makePayment( @@ -4519,11 +4520,10 @@ async function processPurchasePay( download.contractTerms.merchant_base_url, wex, ); - const resp = await wex.ws.runSequentialized([EXCHANGE_COINS_LOCK], () => - merchantClient.demostratePayment( - download.contractTerms.order_id, - reqBody, - ), + // Rebinding a paid order sends the merchant's receipt and uses no coins. + const resp = await merchantClient.demostratePayment( + download.contractTerms.order_id, + reqBody, ); logger.trace(`/paid response status: ${resp.response.status}`); if (isOrderUnknown(resp)) { diff --git a/packages/taler-wallet-core/src/recoup.ts b/packages/taler-wallet-core/src/recoup.ts @@ -99,7 +99,7 @@ import { makeTransactionActionUnsupportedError, } from "./transactions.js"; import { - EXCHANGE_COINS_LOCK, + exchangeCoinLock, WalletExecutionContext, getDenomInfo, walletExchangeClient, @@ -548,8 +548,9 @@ export async function processRecoupGroup( for (let i = 0; i < finishedCoins.length; i++) { if (finishedCoins[i]) continue; try { - await wex.ws.runSequentialized([EXCHANGE_COINS_LOCK], () => - processRecoupForCoin(wex, recoupGroupId, i), + await wex.ws.runSequentialized( + [exchangeCoinLock(recoupGroup.exchangeBaseUrl)], + () => processRecoupForCoin(wex, recoupGroupId, i), ); } catch (error) { logger.warn(`processRecoup failed: ${error}`); diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -141,7 +141,7 @@ import { import { coinAvailabilityRefKey, denomRefKey, - EXCHANGE_COINS_LOCK, + exchangeCoinLock, ensureCoinAvailabilityCounters, getDenomInfo, getDenomInfos, @@ -1395,7 +1395,8 @@ async function refreshMelt( }); // Keep recoup and other melt submissions from acting on this input between // reading its history and applying a rejection to the session. - return wex.ws.runSequentialized([EXCHANGE_COINS_LOCK], async () => { + const coinLock = exchangeCoinLock(oldCoin.exchangeBaseUrl); + return wex.ws.runSequentialized([coinLock], async () => { await requireExchangeCoinUseConfirmedOrThrow(wex, oldCoin.exchangeBaseUrl); const submission = await wex.runWalletDbTx(async (tx) => { // Recoup can claim or finish this input while the melt waits for the lock. @@ -2071,7 +2072,7 @@ async function refreshReveal( timeout: getRefreshRequestTimeout(refreshGroup), }); const resp = await wex.ws.runSequentialized( - [EXCHANGE_COINS_LOCK], + [exchangeCoinLock(oldCoin.exchangeBaseUrl)], async () => { await checkRefreshAllowed(wex); return exchangeClient.postRevealMelt({ body: req }); @@ -2435,7 +2436,7 @@ function isPendingRefreshCoin(status: RefreshCoinStatus): boolean { /** * Bind only currently pending, unaccepted melts before submitting recoup. - * The caller holds EXCHANGE_COINS_LOCK, so no melt can reach the exchange + * The caller holds the exchange's coin lock, so no melt can reach it * between examining its history and committing these associations. Return false * when a refund needs retrying or the caller must refresh the coin history. */ diff --git a/packages/taler-wallet-core/src/testing-recover-coins.ts b/packages/taler-wallet-core/src/testing-recover-coins.ts @@ -74,7 +74,7 @@ import { } from "./refresh.js"; import { ensureCoinAvailabilityCounters, - EXCHANGE_COINS_LOCK, + exchangeCoinLock, WalletExecutionContext, walletExchangeClient, } from "./wallet.js"; @@ -896,7 +896,8 @@ async function runCoinRecovery( failed = true; } } - await wex.ws.runSequentialized([EXCHANGE_COINS_LOCK], () => + const coinLock = exchangeCoinLock(coin.exchangeBaseUrl); + await wex.ws.runSequentialized([coinLock], () => wex.runWalletDbTx(async (tx) => { const current = await requireUnchangedCoin(tx, coin, denom); if (journal.quarantined.includes(pub)) { diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -455,7 +455,10 @@ export function walletMerchantClient( }); } -export const EXCHANGE_COINS_LOCK = "exchange-coins-lock"; +/** Serialize coin requests to the same exchange, including recoup credits to a parent coin. */ +export function exchangeCoinLock(exchangeBaseUrl: string): string { + return `exchange-coins:${exchangeBaseUrl}`; +} export type NotificationListener = (n: WalletNotification) => void;