commit 49ac18d393917a5b787e2caa3961f1267a9f2b37 parent 1be2fb192e54725b2e2ee581ea9561779b8dc95b Author: Florian Dold <dold@taler.net> Date: Mon, 23 Nov 2026 19:49:21 +0100 wallet-core: group double-spend warnings by transaction A payment and its change refresh can both see the same debit in the exchange's coin history. Count it once in the warning for the payment. Diffstat:
11 files changed, 545 insertions(+), 13 deletions(-)
diff --git a/packages/taler-harness/src/integrationtests/test-peer-push-recovery.ts b/packages/taler-harness/src/integrationtests/test-peer-push-recovery.ts @@ -16,6 +16,7 @@ import { AbsoluteTime, + type AmountString, Duration, RefreshReason, NotificationType, @@ -381,7 +382,8 @@ export async function runPeerPushRefundedDuringRepairTest(t: GlobalTestState) { message: /^Coin [0-9A-Z]+ has insufficient balance for purse deposit of amount TESTKUDOS:1$/, maxOccurrences: 1, - justification: "the last coin of the restored selection was already spent", + justification: + "the final batch of the restored selection was already spent", }); const { walletClient: original, @@ -401,33 +403,35 @@ export async function runPeerPushRefundedDuringRepairTest(t: GlobalTestState) { walletClient: original, bank, exchange, - amount: "TESTKUDOS:65", + amount: "TESTKUDOS:66", }) ).withdrawalFinishedCond; await sender.call(Op.ImportDb, { dump: await original.call(Op.ExportDb, {}), }); - // The first batch funds 64 units. Spending the final coin in the original - // wallet makes the restored sender wait for one unit of replacement funding. - let spentLastCoin = false; + // After 64 accepted deposits, the original wallet spends both remaining inputs. + let spentLastBatch = false; exchange.faultProxy.addFault({ async modifyRequest(req) { if ( - spentLastCoin || + spentLastBatch || req.method !== "POST" || !new URL(req.requestUrl).pathname.endsWith("/deposit") ) return; const { deposits } = JSON.parse(req.requestBody!.toString()); - t.assertDeepEqual(deposits.length, 1); - spentLastCoin = true; + t.assertDeepEqual(deposits.length, 2); + spentLastBatch = true; await original.call(Op.ForceRefresh, { - refreshCoinSpecs: [{ coinPub: deposits[0].coin_pub }], + refreshCoinSpecs: deposits.map((d: { coin_pub: string }) => ({ + coinPub: d.coin_pub, + })), }); await original.call(Op.TestingWaitRefreshesFinal, {}); }, }); + const baseline = await sender.call(Op.GetUserAttentionSummary, {}); const needsFunds = sender.waitForNotificationCond( (n) => n.type === NotificationType.TransactionStateTransition && @@ -438,10 +442,31 @@ export async function runPeerPushRefundedDuringRepairTest(t: GlobalTestState) { exchangeBaseUrl: exchange.baseUrl, partialContractTerms: { summary: "abort a partly funded push payment from a copy", - amount: "TESTKUDOS:65", + amount: "TESTKUDOS:66", }, }); await needsFunds; + async function warning(wallet: WalletClient, expectedAmount: AmountString) { + const { items } = await wallet.call(Op.GetUserAttention, {}); + const conflicts = items.filter((item) => item.type === "coin-double-spent"); + t.assertDeepEqual(conflicts.length, 1); + const item = conflicts[0]; + t.assertDeepEqual(item.transactionId, transactionId); + t.assertDeepEqual(item.exchangeBaseUrls, [exchange.baseUrl]); + t.assertAmountEquals(item.amountSpentElsewhere, expectedAmount); + return item; + } + const first = await warning(sender, "TESTKUDOS:2"); + t.assertTrue(!first.readAt); + t.assertDeepEqual( + (await sender.call(Op.GetUserAttentionSummary, {})).unreadCount, + baseline.unreadCount + 1, + ); + await sender.call(Op.MarkUserAttentionRead, { + attentionId: first.attentionId, + }); + const read = await warning(sender, "TESTKUDOS:2"); + t.assertTrue(!!read.readAt); await sender.call(Op.SuspendTransaction, { transactionId }); await copy.call(Op.ImportDb, { dump: await sender.call(Op.ExportDb, {}) }); await copy.call(Op.AbortTransaction, { transactionId }); @@ -465,6 +490,18 @@ export async function runPeerPushRefundedDuringRepairTest(t: GlobalTestState) { (await sender.call(Op.GetBalances, {})).balances[0].available, "TESTKUDOS:0", ); + // The copy recovered 64 refunded units. Only the sender sees those new melts as foreign. + t.assertDeepEqual(await warning(copy, "TESTKUDOS:2"), read); + t.assertDeepEqual(await warning(sender, "TESTKUDOS:66"), { + ...read, + amountSpentElsewhere: "TESTKUDOS:66", + }); + for (const wallet of [copy, sender]) { + t.assertDeepEqual( + (await wallet.call(Op.GetUserAttentionSummary, {})).unreadCount, + baseline.unreadCount, + ); + } } runPeerPushRefundedDuringRepairTest.suites = ["wallet"]; diff --git a/packages/taler-harness/src/integrationtests/test-peer-spent-coin.ts b/packages/taler-harness/src/integrationtests/test-peer-spent-coin.ts @@ -378,6 +378,11 @@ export async function runPeerSpentCoinHistoryTest(t: GlobalTestState) { failed.failReason?.code, TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, ); + const inbox = await sender.call(Op.GetUserAttention, {}); + t.assertDeepEqual( + inbox.items.filter((item) => item.type === "coin-double-spent"), + [], + ); t.assertTrue(pullCoinUnknown); t.assertDeepEqual(pullSubmissions.length, 1); t.assertAmountEquals( diff --git a/packages/taler-wallet-core/src/coin-history.ts b/packages/taler-wallet-core/src/coin-history.ts @@ -19,12 +19,20 @@ import { Amounts, assertUnreachable, CoinHistoryResponse, + TransactionType, + TransactionIdStr, DenominationInfo, HttpStatusCode, TalerError, TalerErrorCode, throwUnexpectedResponse, } from "@gnu-taler/taler-util"; +import type { WalletDbTransaction } from "./db/transaction.js"; +import { addConflictingSpend } from "./user-attention.js"; +import { + constructTransactionIdentifier, + parseTransactionIdentifier, +} from "./transactions.js"; import { WalletCoin } from "./db/records.js"; import { requireValidExchangeCoinHistory } from "./exchange-signatures.js"; import { requireExchangeCoinUseConfirmedOrThrow } from "./exchanges.js"; @@ -273,3 +281,132 @@ export function validateAndRecomputeCoinHistoryBalance( } return recomputed; } + +/** + * Compare verified debits with the authorizations this wallet recorded. A + * transaction can be gone after deletion or import. In that case we cannot + * identify a foreign authorization from the exchange's reply alone. + */ +export async function recordConflictingCoinHistory( + tx: WalletDbTransaction, + coin: WalletCoin, + transactionId: TransactionIdStr, + verified: CoinHistoryResponse, + originatingTransactionId?: string, +) { + const local = await tx.getCoinHistory(coin.coinPub); + if (!local?.history.some((h) => h.transactionId === transactionId)) return; + const deposits: Array<{ target: string; amount: AmountString }> = []; + const purses: Array<{ target: string; amount: AmountString }> = []; + for (const allocation of local.history) { + if (allocation.type !== "spend") continue; + const ref = parseTransactionIdentifier(allocation.transactionId); + switch (ref?.tag) { + case TransactionType.Payment: { + const purchase = await tx.getPurchase(ref.proposalId); + if (!purchase?.download) return; + deposits.push({ + target: purchase.download.contractTermsHash, + amount: allocation.amount, + }); + break; + } + case TransactionType.Deposit: { + const deposit = await tx.getDepositGroup(ref.depositGroupId); + if (!deposit) return; + deposits.push({ + target: deposit.contractTermsHash, + amount: allocation.amount, + }); + break; + } + case TransactionType.PeerPushDebit: + purses.push({ target: ref.pursePub, amount: allocation.amount }); + break; + case TransactionType.PeerPullDebit: { + const debit = await tx.getPeerPullDebit(ref.peerPullDebitId); + if (!debit) return; + purses.push({ target: debit.pursePub, amount: allocation.amount }); + break; + } + default: + return; + } + } + const conflicts: Array<{ signature: string; amount: AmountString }> = []; + for (const debit of verified.history) { + switch (debit.type) { + case "DEPOSIT": + if ( + deposits.some( + (d) => + d.target === debit.h_contract_terms && + Amounts.cmp(d.amount, debit.amount) === 0, + ) + ) + continue; + break; + case "PURSE-DEPOSIT": + if ( + purses.some( + (p) => + p.target === debit.purse_pub && + Amounts.cmp(p.amount, debit.amount) === 0, + ) + ) + continue; + break; + case "MELT": + // A consumed refresh session may already have been deleted; its + // absence cannot establish that a different wallet made the melt. + // Zero change allocations never authorize a melt. + if ( + local.history.some( + (h) => h.type === "refresh" && Amounts.isNonZero(h.amount), + ) + ) + continue; + break; + default: + continue; + } + conflicts.push({ signature: debit.coin_sig, amount: debit.amount }); + } + if (!conflicts.length) return; + + const origin = + originatingTransactionId && + parseTransactionIdentifier(originatingTransactionId); + const ownerId = + origin && + (origin.tag === TransactionType.Payment || + origin.tag === TransactionType.PeerPushDebit || + origin.tag === TransactionType.PeerPullDebit || + origin.tag === TransactionType.Deposit) + ? constructTransactionIdentifier(origin) + : transactionId; + + // A payment can be deleted while fetching history or before its change refresh completes. + if (!(await tx.getTransactionMeta(ownerId))) return; + let merchantName: string | undefined; + const owner = parseTransactionIdentifier(ownerId); + if (owner?.tag === TransactionType.Payment) { + const purchase = await tx.getPurchase(owner.proposalId); + const terms = + purchase?.download && + (await tx.getContractTerms(purchase.download.contractTermsHash)); + const name = terms?.contractTermsRaw?.merchant?.name; + if (typeof name === "string") merchantName = name; + } + for (const debit of conflicts) { + await addConflictingSpend( + tx, + ownerId, + coin.coinPub, + coin.exchangeBaseUrl, + debit.signature, + debit.amount, + merchantName, + ); + } +} diff --git a/packages/taler-wallet-core/src/common.ts b/packages/taler-wallet-core/src/common.ts @@ -82,6 +82,7 @@ import { } from "./db/indexeddb/schema.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { ReadyExchangeSummary, markExchangeUsed } from "./exchanges.js"; +import { deleteConflictingSpends } from "./user-attention.js"; import { createRefreshGroup } from "./refresh.js"; import { BalanceEffect, applyNotifyTransition } from "./transactions.js"; import { @@ -1138,6 +1139,7 @@ export async function getGenericRecordHandle<T>( newTxState = { major: TransactionMajorState.Deleted }; newStId = -1; await deleteRec(); + await deleteConflictingSpends(tx, ctx.transactionId); } else { // Neither old or new record. Nothing to do. return; diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -25,6 +25,10 @@ * Imports. */ import { + readVerifiedCoinHistory, + recordConflictingCoinHistory, +} from "./coin-history.js"; +import { AbortingCoin, AbortRequest, AbsoluteTime, @@ -202,6 +206,7 @@ import { denomRefKey, EXCHANGE_COINS_LOCK, getDenomInfos, + getDenomInfo, WalletExecutionContext, walletMerchantClient, } from "./wallet.js"; @@ -2833,7 +2838,32 @@ async function handleInsufficientFunds( // FIXME: Above code should go into the transaction. // TODO: also do token re-selection. + const coinPub = brokenCoinPub; + const coin = await wex.runWalletDbTx(async (tx) => { + if (!coinPub) return; + const coin = await tx.getCoin(coinPub); + const denom = coin && (await getDenomInfo(wex, tx, coin)); + return coin && denom ? { coin, denom } : undefined; + }); + let verified; + if (coin) { + try { + const reply = await readVerifiedCoinHistory(wex, coin.coin, coin.denom); + if (reply.case === "ok") verified = reply.body; + } catch (err) { + wex.cancellationToken.throwIfCancelled(); + logger.info(`Could not verify the rejected coin's history: ${err}`); + } + } + const history = verified; const repair = await wex.runWalletDbTx(async (tx) => { + if (coin && history) + await recordConflictingCoinHistory( + tx, + coin.coin, + ctx.transactionId, + history, + ); return reselectCoinsTx(tx, ctx, { excludeCoinPub: brokenCoinPub }); }); diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts @@ -133,6 +133,9 @@ function coinHistoryContext( }, }; const tx = { + async getCoinHistory() { + return undefined; + }, async getExchange() { return undefined; }, diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.ts @@ -35,7 +35,10 @@ import { coinsAddedByRepair, selectPeerCoinsInTx, } from "./coinSelection.js"; -import { readVerifiedCoinHistory } from "./coin-history.js"; +import { + recordConflictingCoinHistory, + readVerifiedCoinHistory, +} from "./coin-history.js"; import { RecordHandle, TaskRunResult, spendCoins } from "./common.js"; import { PurseDepositSelection, RefreshCoinStatus } from "./db/records.js"; import { @@ -150,6 +153,10 @@ async function inspectPurseCoins( const { coinPub } = coin; const response = await readVerifiedCoinHistory(wex, coin, denom); const history = response.case === "ok" ? response.body : undefined; + if (history) + await wex.runWalletDbTx((tx) => + recordConflictingCoinHistory(tx, coin, transactionId, history), + ); const authorization = classifyPurseDepositCoinHistory( history?.history ?? [], { exchangeBaseUrl, pursePub, coinPub, contribution }, diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts @@ -270,6 +270,7 @@ test("deleting a live refresh removes its pending output count", async () => { let sessionDeleted = false; let metaDeleted = false; const tx = { + getUserAttention: async () => undefined, notify() {}, async getRefreshGroup() { return storedRefreshGroup; @@ -758,6 +759,7 @@ test("a corrected melt keeps the recouped sibling's output at zero", async (t) = }, } as unknown as WalletRefreshGroup; const tx = { + getCoinHistory: async () => undefined, getRefreshSession: async () => ({ coinIndex: 1, newDenoms: [] }), deleteRefreshSession: async () => {}, upsertRefreshSession: async () => {}, diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -24,7 +24,10 @@ import { ensureRecoupProvenance } from "./recoup.js"; /** * Imports. */ -import { readVerifiedCoinHistory } from "./coin-history.js"; +import { + readVerifiedCoinHistory, + recordConflictingCoinHistory, +} from "./coin-history.js"; import { settledRefreshOutput } from "./transaction-amounts.js"; import { addPermanentCoinFailure } from "./transaction-reasons.js"; import { AutoRefreshOutputPlan, evaluateAutoRefresh } from "./autoRefresh.js"; @@ -1672,6 +1675,13 @@ export async function handleRefreshMeltConflict( if (rg.statusPerCoin[coinIndex] !== RefreshCoinStatus.Pending) { return; } + await recordConflictingCoinHistory( + tx, + oldCoin, + ctx.transactionId, + history, + rg.originatingTransactionId, + ); if (Amounts.isZero(correctedBalance)) { const refreshSession = await tx.getRefreshSession( ctx.refreshGroupId, diff --git a/packages/taler-wallet-core/src/user-attention.ts b/packages/taler-wallet-core/src/user-attention.ts @@ -5,6 +5,10 @@ */ import { AbsoluteTime, + Amounts, + type AmountString, + type TransactionIdStr, + checkDbInvariant, encodeCrock, getRandomBytes, NotificationType, @@ -198,6 +202,73 @@ export async function reconcileExchangeAttention( await setCondition(tx, "master:" + url, identityChange); } +export async function addConflictingSpend( + tx: WalletDbTransaction, + transactionId: TransactionIdStr, + coinPub: string, + exchangeBaseUrl: string, + authorization: string, + amount: AmountString, + merchantName?: string, +) { + const evidence = (await tx.getTransactionCoinConflict( + transactionId, + coinPub, + )) ?? { + transactionId, + coinPub, + exchangeBaseUrl, + debits: {}, + }; + if (Object.hasOwn(evidence.debits, authorization)) return; + evidence.debits[authorization] = amount; + await tx.upsertTransactionCoinConflict(evidence); + + const key = "spend:" + transactionId; + const old = await tx.getUserAttention(key); + if (!old) { + await save( + tx, + key, + newItem({ + type: "coin-double-spent", + transactionId, + amountSpentElsewhere: amount, + exchangeBaseUrls: [exchangeBaseUrl], + merchantName, + }), + ); + } else { + const item = old.item; + checkDbInvariant( + item.type === "coin-double-spent", + "unexpected attention item for spend", + ); + const total = Amounts.add(item.amountSpentElsewhere, amount); + checkDbInvariant( + !total.saturated, + "conflicting spend total exceeds amount range", + ); + item.amountSpentElsewhere = Amounts.stringify(total.amount); + if (!item.exchangeBaseUrls.includes(exchangeBaseUrl)) + item.exchangeBaseUrls.push(exchangeBaseUrl); + await save(tx, key, item, old.dismissed); + } + if (!old?.dismissed) changed(tx); +} + +export async function deleteConflictingSpends( + tx: WalletDbTransaction, + transactionId: string, +) { + const key = "spend:" + transactionId; + const row = await tx.getUserAttention(key); + if (!row) return; + await tx.deleteTransactionCoinConflicts(transactionId); + await tx.deleteUserAttention(key); + if (!row.dismissed) changed(tx); +} + // A deadline also wakes clients that only requested the home-screen count. const expiryTimers = new WeakMap<WalletExecutionContext["ws"], TimerHandle>(); export async function scheduleAttentionExpirations( diff --git a/packages/taler-wallet-core/src/wallet-notifications.test.ts b/packages/taler-wallet-core/src/wallet-notifications.test.ts @@ -21,6 +21,7 @@ import { CancellationToken, ContractTermsUtil, DenomKeyType, + CoinStatus, encodeCrock, NotificationType, openPromise, @@ -47,6 +48,8 @@ import { timestampPreciseToDb, timestampProtocolToDb, WalletDenomination, + WalletCoin, + CoinSourceType, WalletExchangeDetails, WalletExchangeEntry, WalletPurchase, @@ -56,12 +59,18 @@ import { WithdrawalGroupStatus, } from "./db/records.js"; import { + addConflictingSpend, clearReadUserAttention, getUserAttention, initializeAttention, markAllUserAttentionRead, updateAttention, } from "./user-attention.js"; +import { recordConflictingCoinHistory } from "./coin-history.js"; +import type { + CoinHistoryResponse, + TransactionIdStr, +} from "@gnu-taler/taler-util"; import { runnerFactories } from "./db/testing/runners.js"; import { getBalances } from "./balance.js"; import { @@ -71,7 +80,11 @@ import { markExchangeUsed, waitReadyExchange, } from "./exchanges.js"; -import { preparePayForUriV2, processPurchase } from "./pay-merchant.js"; +import { + PayMerchantTransactionContext, + preparePayForUriV2, + processPurchase, +} from "./pay-merchant.js"; import { RefreshTransactionContext } from "./refresh.js"; import { processRefreshBalance } from "./refreshBalance.js"; import { WithdrawTransactionContext } from "./withdraw.js"; @@ -454,6 +467,221 @@ for (const makeRunner of runnerFactories) { } }); + test(`${makeRunner.name}: concurrent spend reports retain one amount and read state per payment`, async () => { + const f = await fixture(makeRunner); + try { + const payment = new PayMerchantTransactionContext(f.wex, "grouped"); + const other = new PayMerchantTransactionContext(f.wex, "other"); + const coinPub = (index: number) => + encodeCrock(new Uint8Array(32).fill(index)); + const otherExchange = "https://second.example/"; + const record = ( + id: TransactionIdStr, + index: number, + authorization = "first", + ) => + f.wex.runWalletDbTx((tx) => + addConflictingSpend( + tx, + id, + coinPub(index), + index % 2 ? otherExchange : exchangeUrl, + authorization, + "TESTKUDOS:1", + ), + ); + + await f.db.runReadWriteTx((tx) => tx.upsertPurchase(purchase("grouped"))); + await Promise.all([ + record(payment.transactionId, 0), + record(payment.transactionId, 1), + ]); + await record(payment.transactionId, 1); + const first = (await getUserAttention(f.wex)).items[0]; + assert.equal(first.type, "coin-double-spent"); + assert.equal(first.amountSpentElsewhere, "TESTKUDOS:2"); + assert.deepEqual( + first.exchangeBaseUrls.slice().sort(), + [exchangeUrl, otherExchange].sort(), + ); + assert.equal((await getUserAttention(f.wex)).unreadCount, 1); + await updateAttention(f.wex, first.attentionId, false); + await record(payment.transactionId, 1, "second"); + const read = (await getUserAttention(f.wex)).items[0]; + assert.equal(read.type, "coin-double-spent"); + assert.equal(read.amountSpentElsewhere, "TESTKUDOS:3"); + assert.equal(read.attentionId, first.attentionId); + assert.ok(read.readAt); + await record(other.transactionId, 1); + await clearReadUserAttention(f.wex); + await record(payment.transactionId, 1, "third"); + assert.equal((await getUserAttention(f.wex)).items.length, 1); + await f.wex.runWalletDbTx((tx) => payment.deleteTransactionInTx(tx)); + const remaining = await f.db.runReadWriteTx((tx) => + tx.listTransactionCoinConflicts(), + ); + assert.deepEqual( + remaining.map((row) => row.transactionId), + [other.transactionId], + ); + const { items } = await getUserAttention(f.wex); + assert.equal(items.length, 1); + assert.equal(items[0].type, "coin-double-spent"); + assert.equal(items[0].transactionId, other.transactionId); + } finally { + await f.close(); + } + }); + + test(`${makeRunner.name}: coin history assigns foreign debits to the affected payment or standalone refresh`, async () => { + const f = await fixture(makeRunner); + try { + const coinPub = encodeCrock(new Uint8Array(32).fill(17)); + const id = "txn:peer-push-debit:local" as TransactionIdStr; + const coin: WalletCoin = { + coinPub, + coinPriv: master, + exchangeBaseUrl: exchangeUrl, + exchangeMasterPub: master, + denomPubHash: signature, + denomSig: { cipher: DenomKeyType.Rsa, rsa_signature: signature }, + blindingKey: master, + coinEvHash: signature, + exchangeWithdrawValues: { cipher: DenomKeyType.Rsa }, + status: CoinStatus.Dormant, + maxAge: 0, + ageCommitmentProof: undefined, + coinSource: { + type: CoinSourceType.Withdraw, + withdrawalGroupId: "withdrawal", + reservePub: master, + coinIndex: 0, + }, + }; + await f.db.runReadWriteTx(async (tx) => { + await tx.upsertCoin(coin); + await tx.upsertTransactionMeta({ + transactionId: id, + currency: "TESTKUDOS", + status: 1, + exchanges: [exchangeUrl], + timestamp: timestampPreciseToDb({ t_s: 1 }), + }); + }); + const history = (purse_pub: string) => + ({ + history: [ + { + type: "PURSE-DEPOSIT", + purse_pub, + amount: "TESTKUDOS:1", + coin_sig: "signature", + }, + ], + }) as CoinHistoryResponse; + const check = (purse: string) => + f.wex.runWalletDbTx((tx) => + recordConflictingCoinHistory(tx, coin, id, history(purse)), + ); + await check("foreign"); + assert.equal((await getUserAttention(f.wex)).unreadCount, 0); + await f.wex.runWalletDbTx((tx) => + tx.upsertCoinHistory({ + coinPub, + history: [ + { type: "spend", amount: "TESTKUDOS:1", transactionId: id }, + ], + }), + ); + await check("local"); + assert.equal((await getUserAttention(f.wex)).unreadCount, 0); + await check("foreign"); + const { items } = await getUserAttention(f.wex); + assert.equal(items.length, 1); + assert.equal(items[0].type, "coin-double-spent"); + assert.equal(items[0].amountSpentElsewhere, "TESTKUDOS:1"); + // Checking change uses the refresh allocation to verify the evidence, and its parent for the inbox. + const change = "txn:refresh:change" as TransactionIdStr; + const deposit = history("foreign").history[0]; + await f.wex.runWalletDbTx(async (tx) => { + const local = (await tx.getCoinHistory(coinPub))!; + local.history.push({ + type: "refresh", + transactionId: change, + amount: "TESTKUDOS:0", + }); + await tx.upsertCoinHistory(local); + await recordConflictingCoinHistory( + tx, + coin, + change, + { + ...history("foreign"), + history: [ + deposit, + { + type: "MELT", + amount: "TESTKUDOS:4", + coin_sig: "other", + } as CoinHistoryResponse["history"][number], + ], + }, + id, + ); + }); + const grouped = (await getUserAttention(f.wex)).items; + assert.equal(grouped.length, 1); + assert.equal(grouped[0].type, "coin-double-spent"); + assert.equal(grouped[0].attentionId, items[0].attentionId); + assert.equal(grouped[0].amountSpentElsewhere, "TESTKUDOS:5"); + // A standalone refresh owns its own warning. A later partial refund + // changes the exchange balance but keeps the original debit in the inbox. + const refundedDeposit: CoinHistoryResponse = { + h_denom_pub: signature, + balance: "TESTKUDOS:2", + history: [ + { + type: "DEPOSIT", + history_offset: 0, + amount: "TESTKUDOS:5", + deposit_fee: "TESTKUDOS:0", + merchant_pub: master, + coin_sig: signature, + h_wire: signature, + h_denom_pub: signature, + h_contract_terms: signature, + timestamp: { t_s: 1 }, + }, + { + type: "REFUND", + history_offset: 1, + amount: "TESTKUDOS:2", + refund_fee: "TESTKUDOS:0", + merchant_pub: master, + merchant_sig: signature, + h_contract_terms: signature, + rtransaction_id: 1, + }, + ], + }; + await f.wex.runWalletDbTx(async (tx) => { + await tx.upsertTransactionMeta({ + ...(await tx.getTransactionMeta(id))!, + transactionId: change, + }); + await recordConflictingCoinHistory(tx, coin, change, refundedDeposit); + }); + const standalone = (await getUserAttention(f.wex)).items.find( + (item) => + item.type === "coin-double-spent" && item.transactionId === change, + ); + assert.ok(standalone?.type === "coin-double-spent"); + assert.equal(standalone.amountSpentElsewhere, "TESTKUDOS:5"); + } finally { + await f.close(); + } + }); + test(`${makeRunner.name}: exchange retry publishes changed errors and their removal`, async () => { const f = await fixture(makeRunner); try {