taler-typescript-core

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

commit 0b98aada82322bb332f9646004abf50e8626d325
parent cee7c7f2083c4b200bcd4086035113fe1ef29706
Author: Florian Dold <dold@taler.net>
Date:   Sun, 22 Nov 2026 22:46:55 +0100

wallet-core: fund only the unpaid remainder of a peer invoice

Keep deposits proven by receipts or coin history when repairing an
invoice, and submit only the still-unpaid coins. Recheck the signed
balance, the local selection and the deadline before spending again.

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-peer-pull-recovery.ts | 455++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-harness/src/integrationtests/test-peer-spent-coin.ts | 167++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-harness/src/integrationtests/testrunner.ts | 13+++++++++++++
Mpackages/taler-wallet-core/src/db/records.ts | 6++++--
Mpackages/taler-wallet-core/src/db/testing/conformance-cases.ts | 3++-
Mpackages/taler-wallet-core/src/pay-peer-common.ts | 10++++++++++
Mpackages/taler-wallet-core/src/pay-peer-pull-debit.test.ts | 129++++++++++++++++++++++++++++++++++++++++++-------------------------------------
Mpackages/taler-wallet-core/src/pay-peer-pull-debit.ts | 1192++++++++++++++++++++++---------------------------------------------------------
Mpackages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/purse-deposit-reconciliation.ts | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
10 files changed, 1646 insertions(+), 934 deletions(-)

diff --git a/packages/taler-harness/src/integrationtests/test-peer-pull-recovery.ts b/packages/taler-harness/src/integrationtests/test-peer-pull-recovery.ts @@ -18,8 +18,10 @@ import { AbsoluteTime, AmountString, Duration, + NotificationType, TransactionMajorState as Major, TransactionMinorState as Minor, + TalerErrorCode, openPromise, } from "@gnu-taler/taler-util"; import { WalletApiOperation as Op } from "@gnu-taler/taler-wallet-core"; @@ -29,7 +31,7 @@ import { createWalletDaemonWithClient, withdrawViaBankV4, } from "../harness/environments.js"; -import { GlobalTestState } from "../harness/harness.js"; +import { delayMs, GlobalTestState, WalletClient } from "../harness/harness.js"; import { readyUri } from "./test-peer-spent-coin.js"; async function testPeerRoundedChangeAbort( @@ -144,3 +146,454 @@ export async function runPeerPendingChangeAbortTest(t: GlobalTestState) { runPeerRoundedChangeAbortTest.suites = ["wallet"]; runPeerPendingChangeAbortTest.suites = ["wallet"]; runPeerUnmeltedChangeAbortTest.suites = ["wallet"]; + +/** A restored payer lacks the receipt for one coin and must replace a second one. */ +export async function runPeerPullRecordedDepositRepairTest(t: GlobalTestState) { + const [one] = makeLargeCoinTestConfig(); + const { + walletClient: original, + faultyExchange: exchange, + bank, + } = await createSimpleTestkudosEnvironmentV3( + t, + [one, { ...one, name: "sixty-four", value: "TESTKUDOS:64" }], + { faultInjection: true }, + ); + const withdraw = async (walletClient: WalletClient, amount: string) => { + const withdrawal = await withdrawViaBankV4(t, { + walletClient, + amount, + bank, + exchange, + }); + await withdrawal.withdrawalFinishedCond; + }; + await withdraw(original, "TESTKUDOS:128"); + const start = () => + createWalletDaemonWithClient(t, { name: "restored", persistent: true }); + let restored = await start(); + await restored.walletClient.call(Op.ImportDb, { + dump: await original.call(Op.ExportDb, {}), + }); + const { walletClient: recipient } = await createWalletDaemonWithClient(t, { + name: "recipient", + }); + const invoice = await recipient.call(Op.InitiatePeerPullCredit, { + exchangeBaseUrl: exchange.baseUrl, + partialContractTerms: { + summary: "one recorded and one stale coin", + amount: "TESTKUDOS:128", + purse_expiration: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + Duration.fromSpec({ minutes: 10 }), + ), + ), + }, + }); + const talerUri = await readyUri(recipient, invoice.transactionId); + const { transactionId } = await restored.walletClient.call( + Op.PreparePeerPullDebit, + { talerUri }, + ); + const submissions: string[][] = []; + const rejected: string[] = []; + exchange.faultProxy.addFault({ + async modifyRequest(req) { + if ( + req.method !== "POST" || + !new URL(req.requestUrl).pathname.endsWith("/deposit") + ) + return; + const body = JSON.parse(req.requestBody!.toString()); + const pubs = body.deposits.map((c: { coin_pub: string }) => c.coin_pub); + submissions.push(pubs); + if (submissions.length !== 1) return; + t.assertDeepEqual(pubs.length, 2); + // The exchange has a genuine signed deposit for A and a spent B. + await original.call(Op.ForceRefresh, { + refreshCoinSpecs: [{ coinPub: pubs[1] }], + }); + await original.call(Op.TestingWaitRefreshesFinal, {}); + req.requestBody = Buffer.from( + JSON.stringify({ deposits: [body.deposits[0]] }), + ); + }, + async modifyResponse(resp) { + if ( + resp.request.method !== "POST" || + !new URL(resp.request.requestUrl).pathname.endsWith("/deposit") + ) + return; + if (submissions.length === 1) { + t.assertDeepEqual(resp.statusCode, 200); + resp.statusCode = 409; + resp.responseBody = Buffer.from( + JSON.stringify({ + code: TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS, + coin_pub: submissions[0][0], + hint: "spent", + }), + ); + } + if (resp.statusCode === 409) + rejected.push(JSON.parse(resp.responseBody!.toString()).coin_pub); + }, + }); + const needsFunds = restored.walletClient.waitForNotificationCond( + (n) => + n.type === NotificationType.TransactionStateTransition && + n.transactionId === transactionId && + n.errorInfo?.code === + TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE, + ); + await restored.walletClient.call(Op.ConfirmPeerPullDebit, { transactionId }); + await needsFunds; + // The changed purse balance triggers repair before the spent sibling is submitted again. + t.assertDeepEqual(rejected, [submissions[0][0]]); + restored.walletClient.remoteWallet?.close(); + await restored.walletService.stop(); + restored = await start(); + // Two withdrawals below the large denomination give the payer 64 one-unit coins. + await withdraw(restored.walletClient, "TESTKUDOS:32"); + await withdraw(restored.walletClient, "TESTKUDOS:32"); + await restored.walletClient.call(Op.TestingWaitTransactionState, { + transactionId, + txState: { major: Major.Done }, + }); + await recipient.call(Op.TestingWaitTransactionState, { + transactionId: invoice.transactionId, + txState: { major: Major.Done }, + }); + const [recorded, spent] = submissions[0]; + const replacements = submissions.slice(1); + t.assertDeepEqual( + replacements.map((batch) => batch.length), + [64], + ); + t.assertTrue(!replacements[0].includes(recorded)); + t.assertTrue(!replacements[0].includes(spent)); + t.assertDeepEqual(new Set(replacements[0]).size, 64); + t.assertAmountEquals( + (await recipient.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:128", + ); + await restored.walletClient.call(Op.TestingWaitRefreshesFinal, {}); + const payment = await restored.walletClient.call(Op.GetTransactionById, { + transactionId, + }); + t.assertAmountEquals(payment.amountEffectiveFinal!, "TESTKUDOS:192"); +} +runPeerPullRecordedDepositRepairTest.timeoutMs = 120000; +runPeerPullRecordedDepositRepairTest.suites = ["wallet"]; + +export async function runPeerPullReplayedBatchTest(t: GlobalTestState) { + const { + walletClient: original, + bank, + faultyExchange: exchange, + } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig(), { + faultInjection: true, + }); + const { walletClient: restored } = await createWalletDaemonWithClient(t, { + name: "restored", + }); + const { walletClient: recipient } = await createWalletDaemonWithClient(t, { + name: "recipient", + }); + const withdraw = async (walletClient: WalletClient, amount: string) => { + await ( + await withdrawViaBankV4(t, { walletClient, bank, exchange, amount }) + ).withdrawalFinishedCond; + }; + await withdraw(original, "TESTKUDOS:65"); + await restored.call(Op.ImportDb, { + dump: await original.call(Op.ExportDb, {}), + }); + const invoice = await recipient.call(Op.InitiatePeerPullCredit, { + exchangeBaseUrl: exchange.baseUrl, + partialContractTerms: { + summary: "restore after the first batch", + amount: "TESTKUDOS:65", + purse_expiration: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + Duration.fromSpec({ minutes: 10 }), + ), + ), + }, + }); + const talerUri = await readyUri(recipient, invoice.transactionId); + const firstBatch: string[] = []; + const secondBatch = openPromise<void>(); + let originalSuspended = false; + exchange.faultProxy.addFault({ + async modifyRequest(req) { + if ( + req.method !== "POST" || + !new URL(req.requestUrl).pathname.endsWith("/deposit") || + originalSuspended + ) + return; + const { deposits } = JSON.parse(req.requestBody!.toString()); + if (!firstBatch.length) { + firstBatch.push( + ...deposits.map((d: { coin_pub: string }) => d.coin_pub), + ); + return; + } + req.dropRequest = true; + req.substituteResponseStatusCode = 503; + req.substituteResponseHeaders = { "content-type": "application/json" }; + req.substituteResponseBody = Buffer.from(JSON.stringify({ code: 1 })); + secondBatch.resolve(); + }, + }); + const originalPayment = await original.call(Op.PreparePeerPullDebit, { + talerUri, + }); + await original.call(Op.ConfirmPeerPullDebit, { + transactionId: originalPayment.transactionId, + }); + await secondBatch.promise; + await original.call(Op.SuspendTransaction, { + transactionId: originalPayment.transactionId, + }); + originalSuspended = true; + t.assertDeepEqual(firstBatch.length, 64); + // Make exactly one coin from the accepted batch available to the restored payer. + for (const coin of (await restored.call(Op.DumpCoins, {})).coins) { + if (coin.coinPub !== firstBatch[0]) + await restored.call(Op.SetCoinSuspended, { + coinPub: coin.coinPub, + suspended: true, + }); + } + const { transactionId } = await restored.call(Op.PreparePeerPullDebit, { + talerUri, + }); + const waiting = restored.waitForNotificationCond( + (n) => + n.type === NotificationType.TransactionStateTransition && + n.transactionId === transactionId && + n.errorInfo?.code === + TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE, + ); + await restored.call(Op.ConfirmPeerPullDebit, { transactionId }); + await waiting; + await withdraw(restored, "TESTKUDOS:1"); + await restored.call(Op.TestingWaitTransactionState, { + transactionId, + txState: { major: Major.Done }, + }); + await recipient.call(Op.TestingWaitTransactionState, { + transactionId: invoice.transactionId, + txState: { major: Major.Done }, + }); + t.assertAmountEquals( + (await recipient.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:65", + ); +} + +runPeerPullReplayedBatchTest.suites = ["wallet"]; +runPeerPullReplayedBatchTest.timeoutMs = 120000; + +/** An independent payer credits a suspended wallet's invoice after it has allocated three coins. */ +export async function runPeerPullStaleSelectionTest(t: GlobalTestState) { + const { + walletClient: payer, + bank, + faultyExchange: exchange, + } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig(), { + faultInjection: true, + }); + const { walletClient: other } = await createWalletDaemonWithClient(t, { + name: "other", + }); + const { walletClient: recipient } = await createWalletDaemonWithClient(t, { + name: "recipient", + }); + for (const walletClient of [payer, other]) { + const withdrawal = await withdrawViaBankV4(t, { + walletClient, + exchange, + bank, + amount: "TESTKUDOS:3", + }); + await withdrawal.withdrawalFinishedCond; + } + const invoice = await recipient.call(Op.InitiatePeerPullCredit, { + exchangeBaseUrl: exchange.baseUrl, + partialContractTerms: { + summary: "partially paid during suspension", + amount: "TESTKUDOS:3", + purse_expiration: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + Duration.fromSpec({ minutes: 10 }), + ), + ), + }, + }); + const talerUri = await readyUri(recipient, invoice.transactionId); + const payerCoins = new Set( + (await payer.call(Op.DumpCoins, {})).coins.map((c) => c.coinPub), + ); + const selected = openPromise<void>(); + const credited = openPromise<void>(); + let resume = false; + const submitted: number[] = []; + exchange.faultProxy.addFault({ + async modifyRequest(req) { + if ( + req.method !== "POST" || + !new URL(req.requestUrl).pathname.endsWith("/deposit") + ) + return; + const { deposits } = JSON.parse(req.requestBody!.toString()); + if (payerCoins.has(deposits[0].coin_pub)) { + if (resume) { + submitted.push(deposits.length); + return; + } + t.assertDeepEqual(deposits.length, 3); + req.dropRequest = true; + req.substituteResponseStatusCode = 503; + req.substituteResponseHeaders = { "content-type": "application/json" }; + req.substituteResponseBody = Buffer.from(JSON.stringify({ code: 1 })); + selected.resolve(); + } else { + req.requestBody = Buffer.from( + JSON.stringify({ deposits: [deposits[0]] }), + ); + } + }, + async modifyResponse(resp) { + if ( + resp.request.method !== "POST" || + !new URL(resp.request.requestUrl).pathname.endsWith("/deposit") || + resp.statusCode !== 200 + ) + return; + const { deposits } = JSON.parse(resp.request.requestBody!.toString()); + if (payerCoins.has(deposits[0].coin_pub)) return; + t.assertAmountEquals( + JSON.parse(resp.responseBody!.toString()).total_deposited, + "TESTKUDOS:1", + ); + resp.statusCode = 503; + resp.responseBody = Buffer.from(JSON.stringify({ code: 1 })); + credited.resolve(); + }, + }); + const pay = await payer.call(Op.PreparePeerPullDebit, { talerUri }); + await payer.call(Op.ConfirmPeerPullDebit, { + transactionId: pay.transactionId, + }); + await selected.promise; + await payer.call(Op.SuspendTransaction, { transactionId: pay.transactionId }); + const partial = await other.call(Op.PreparePeerPullDebit, { talerUri }); + await other.call(Op.ConfirmPeerPullDebit, { + transactionId: partial.transactionId, + }); + await credited.promise; + await other.call(Op.SuspendTransaction, { + transactionId: partial.transactionId, + }); + resume = true; + await payer.call(Op.ResumeTransaction, { transactionId: pay.transactionId }); + await payer.call(Op.TestingWaitTransactionState, { + transactionId: pay.transactionId, + txState: { major: Major.Done }, + }); + await recipient.call(Op.TestingWaitTransactionState, { + transactionId: invoice.transactionId, + txState: { major: Major.Done }, + }); + await payer.call(Op.TestingWaitRefreshesFinal, {}); + t.assertDeepEqual(submitted, [2]); + t.assertAmountEquals( + (await payer.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:1", + ); + t.assertAmountEquals( + (await recipient.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:3", + ); +} +runPeerPullStaleSelectionTest.suites = ["wallet"]; + +/** A signed status requested before the deadline can arrive after it. */ +export async function runPeerPullDepositDeadlineTest(t: GlobalTestState) { + const { + walletClient: payer, + bank, + exchange, + faultyExchange, + } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig(), { + faultInjection: true, + }); + const { walletClient: recipient } = await createWalletDaemonWithClient(t, { + name: "recipient", + }); + await ( + await withdrawViaBankV4(t, { + walletClient: payer, + exchange: faultyExchange, + bank, + amount: "TESTKUDOS:1", + }) + ).withdrawalFinishedCond; + const deadline = Math.ceil(Date.now() / 1000) + 10; + const invoice = await recipient.call(Op.InitiatePeerPullCredit, { + exchangeBaseUrl: faultyExchange.baseUrl, + partialContractTerms: { + summary: "status arrives after expiry", + amount: "TESTKUDOS:1", + purse_expiration: { t_s: deadline }, + }, + }); + const talerUri = await readyUri(recipient, invoice.transactionId); + const { transactionId } = await payer.call(Op.PreparePeerPullDebit, { + talerUri, + }); + let statusReads = 0; + const nextRequest = openPromise<string>(); + faultyExchange.faultProxy.addFault({ + async modifyRequest(req) { + if (statusReads < 2) return; + const path = new URL(req.requestUrl).pathname; + if (req.method === "POST" && path.endsWith("/deposit")) + nextRequest.resolve("deposit"); + if (req.method === "GET" && path.endsWith("/merge")) + nextRequest.resolve("status"); + }, + async modifyResponse(resp) { + if ( + resp.request.method !== "GET" || + !new URL(resp.request.requestUrl).pathname.endsWith("/merge") + ) + return; + // Confirmation reads the balance once. Hold the deposit worker's read. + if (++statusReads !== 2) return; + t.assertDeepEqual(resp.statusCode, 200); + const untilDeadline = deadline * 1000 - Date.now(); + t.assertTrue(untilDeadline > 0); + await delayMs(untilDeadline + 50); + }, + }); + await payer.call(Op.ConfirmPeerPullDebit, { transactionId }); + t.assertDeepEqual(await nextRequest.promise, "status"); + await exchange.runExpireOnce(); + await payer.call(Op.TestingWaitTransactionState, { + transactionId, + txState: { major: Major.Expired }, + }); + await payer.call(Op.TestingWaitRefreshesFinal, {}); + t.assertAmountEquals( + (await payer.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:1", + ); +} +runPeerPullDepositDeadlineTest.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 @@ -15,13 +15,23 @@ */ import { + AbsoluteTime, + Duration, TransactionIdStr, + TransactionType, TransactionMajorState as Major, TransactionMinorState as Minor, - TransactionType, + TalerErrorCode, + openPromise, } from "@gnu-taler/taler-util"; import { WalletApiOperation as Op } from "@gnu-taler/taler-wallet-core"; -import { WalletClient } from "../harness/harness.js"; +import { makeLargeCoinTestConfig } from "../harness/denomStructures.js"; +import { + createSimpleTestkudosEnvironmentV3, + createWalletDaemonWithClient, + withdrawViaBankV4, +} from "../harness/environments.js"; +import { GlobalTestState, WalletClient } from "../harness/harness.js"; export async function readyUri( wallet: WalletClient, @@ -40,3 +50,156 @@ export async function readyUri( throw Error("ready purse has no payment URI"); return tx.talerUri; } + +export async function runPeerPullSpentCoinTest(t: GlobalTestState) { + const one = makeLargeCoinTestConfig()[0]; + const { + walletClient: original, + bank, + faultyExchange: exchange, + } = await createSimpleTestkudosEnvironmentV3( + t, + [one, { ...one, name: "two", value: "TESTKUDOS:2" }], + { + faultInjection: true, + }, + ); + const w = await withdrawViaBankV4(t, { + walletClient: original, + bank, + exchange, + amount: "TESTKUDOS:130", + }); + await w.withdrawalFinishedCond; + const coins = (await original.call(Op.DumpCoins, {})).coins; + t.assertDeepEqual(coins.length, 65); + t.assertTrue(coins.every((c) => c.denomValue === "TESTKUDOS:2")); + const startSender = () => + createWalletDaemonWithClient(t, { name: "restored", persistent: true }); + let sender = await startSender(); + await sender.walletClient.call(Op.ImportDb, { + dump: await original.call(Op.ExportDb, {}), + }); + const { walletClient: recipient } = await createWalletDaemonWithClient(t, { + name: "recipient", + }); + let firstBatchAccepted = false; + let stale: string | undefined; + let rejected: string | undefined; + const residualMeltAccepted = openPromise<void>(); + const releaseMelt = openPromise<void>(); + const recoverySeeds = new Set<string>(); + exchange.faultProxy.addFault({ + async modifyRequest(req) { + const path = new URL(req.requestUrl).pathname; + if ( + !firstBatchAccepted || + stale || + req.method !== "POST" || + !path.endsWith("/deposit") + ) + return; + const deposits = JSON.parse(req.requestBody!.toString()).deposits; + t.assertDeepEqual(deposits.length, 1); + stale = deposits[0].coin_pub as string; + // Leave one unit on the old coin, which the sender allocated in full. + await original.call(Op.ForceRefresh, { + refreshCoinSpecs: [{ coinPub: stale, amount: "TESTKUDOS:1" }], + }); + await original.call(Op.TestingWaitRefreshesFinal, {}); + }, + async modifyResponse(resp) { + const path = new URL(resp.request.requestUrl).pathname; + if (resp.request.method !== "POST") return; + if (path.endsWith("/create") || path.endsWith("/deposit")) { + const deposits = JSON.parse( + resp.request.requestBody!.toString(), + ).deposits; + if (resp.statusCode === 200 && deposits?.length === 64) + firstBatchAccepted = true; + if (resp.statusCode === 409) { + const error = JSON.parse(resp.responseBody!.toString()); + if (error.code === TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS) + rejected = error.coin_pub; + } + } + if (rejected && path.endsWith("/melt")) { + const melt = JSON.parse(resp.request.requestBody!.toString()); + if (melt.old_coin_pub === rejected && resp.statusCode === 200) { + t.assertAmountEquals(melt.value_with_fee, "TESTKUDOS:1"); + const first = recoverySeeds.size === 0; + recoverySeeds.add(melt.refresh_seed); + if (first) { + residualMeltAccepted.resolve(); + await releaseMelt.promise; + } + } + } + }, + }); + const partialContractTerms = { + summary: "pay with restored wallet", + amount: "TESTKUDOS:130" as const, + purse_expiration: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + Duration.fromSpec({ days: 1 }), + ), + ), + }; + const credit = ( + await recipient.call(Op.InitiatePeerPullCredit, { + partialContractTerms, + exchangeBaseUrl: exchange.baseUrl, + }) + ).transactionId; + const talerUri = await readyUri(recipient, credit); + const debit = ( + await sender.walletClient.call(Op.PreparePeerPullDebit, { talerUri }) + ).transactionId; + await sender.walletClient.call(Op.ConfirmPeerPullDebit, { + transactionId: debit, + }); + // Restart after the exchange accepted the melt but before the wallet saw + // the response. Restarting must resume the same recovery session. + await residualMeltAccepted.promise; + try { + sender.walletClient.remoteWallet?.close(); + await sender.walletService.stop(); + } finally { + releaseMelt.resolve(); + } + sender = await startSender(); + t.assertTrue(!!stale && rejected === stale); + const topup = await withdrawViaBankV4(t, { + walletClient: sender.walletClient, + bank, + exchange, + amount: "TESTKUDOS:2", + }); + await topup.withdrawalFinishedCond; + await recipient.call(Op.TestingWaitTransactionState, { + transactionId: credit, + txState: { major: Major.Done }, + }); + await sender.walletClient.call(Op.TestingWaitTransactionState, { + transactionId: debit, + txState: { major: Major.Done }, + }); + await sender.walletClient.call(Op.TestingWaitRefreshesFinal, {}); + t.assertAmountEquals( + (await recipient.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:130", + ); + t.assertAmountEquals( + (await sender.walletClient.call(Op.GetBalances, {})).balances[0].available, + "TESTKUDOS:1", + ); + const settled = await sender.walletClient.call(Op.GetTransactionById, { + transactionId: debit, + }); + t.assertAmountEquals(settled.amountEffectiveFinal!, "TESTKUDOS:131"); + t.assertDeepEqual(recoverySeeds.size, 1); +} +runPeerPullSpentCoinTest.suites = ["wallet"]; +runPeerPullSpentCoinTest.timeoutMs = 120000; diff --git a/packages/taler-harness/src/integrationtests/testrunner.ts b/packages/taler-harness/src/integrationtests/testrunner.ts @@ -182,7 +182,14 @@ import { runPeerRoundedChangeAbortTest, runPeerPendingChangeAbortTest, runPeerUnmeltedChangeAbortTest, + runPeerPullRecordedDepositRepairTest, + runPeerPullReplayedBatchTest, + runPeerPullStaleSelectionTest, + runPeerPullDepositDeadlineTest, } from "./test-peer-pull-recovery.js"; +import { + runPeerPullSpentCoinTest, +} from "./test-peer-spent-coin.js"; import { runPeerPullTest } from "./test-peer-pull.js"; import { runPeerPushLargeTest } from "./test-peer-push-large.js"; import { runPeerPushTest } from "./test-peer-push.js"; @@ -407,6 +414,12 @@ const allTests: TestMainFunction[] = [ runPeerRoundedChangeAbortTest, runPeerPendingChangeAbortTest, runPeerUnmeltedChangeAbortTest, + runPeerPullSpentCoinTest, + withWalletDbBackend(runPeerPullRecordedDepositRepairTest, "default"), + withWalletDbBackend(runPeerPullRecordedDepositRepairTest, "indexeddb"), + runPeerPullReplayedBatchTest, + runPeerPullStaleSelectionTest, + runPeerPullDepositDeadlineTest, runPeerAbortBeforeCreateTest, runTransactionFinalAmountsTest, runPeerPullDebitPurseGoneTest, diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -2557,6 +2557,8 @@ export enum DonationReceiptStatus { export interface PurseDepositSelection { contributions: AmountString[]; coinPubs: string[]; + /** Purse balance the outstanding selection was sized for. */ + balanceAtSelection?: AmountString; /** Leading coins with a matching deposit in verified history or a signed receipt. */ knownDepositCount?: number; /** Coins observed on this purse, including deposits with different authorizations. */ @@ -2573,12 +2575,12 @@ export interface PurseDepositSelection { export type DbPeerPushPaymentCoinSelection = PurseDepositSelection; export interface PeerPullPaymentCoinSelection extends PurseDepositSelection { + /** Only confirmed or history-recorded deposits remain; select fresh funding for the remainder. */ + needsRepair?: boolean; totalCost: AmountString | undefined; /** Leading contributions confirmed by a signed receipt or verified coin history. */ depositedCoinCount?: number; - /** Latest purse balance covered by a verified deposit confirmation. */ - confirmedPurseBalance?: AmountString; } /** diff --git a/packages/taler-wallet-core/src/db/testing/conformance-cases.ts b/packages/taler-wallet-core/src/db/testing/conformance-cases.ts @@ -4662,7 +4662,8 @@ export const conformanceCases: ConformanceCase[] = [ contributions: [amt("TESTKUDOS:1"), amt("TESTKUDOS:2")], totalCost: amt("TESTKUDOS:3.1"), depositedCoinCount: 1, - confirmedPurseBalance: amt("TESTKUDOS:1"), + knownDepositCount: 2, + balanceAtSelection: amt("TESTKUDOS:1"), }; rec.cleanupFinalStatus = PeerPullDebitRecordStatus.Aborted; await runner.runReadWriteTx((tx) => tx.upsertPeerPullDebit(rec)); diff --git a/packages/taler-wallet-core/src/pay-peer-common.ts b/packages/taler-wallet-core/src/pay-peer-common.ts @@ -50,6 +50,16 @@ import { import { updateWithdrawalDenomsForExchange } from "./withdraw.js"; import { WalletDbTransaction } from "./db/transaction.js"; +export function netPurseDeposits( + currency: string, + coins: readonly Pick<SpendCoinDetails, "contribution" | "feeDeposit">[], +): AmountJson { + return Amounts.sumOrZero( + currency, + coins.map((c) => Amounts.sub(c.contribution, c.feeDeposit).amount), + ).amount; +} + /** * Get information about the coin selected for signatures. */ diff --git a/packages/taler-wallet-core/src/pay-peer-pull-debit.test.ts b/packages/taler-wallet-core/src/pay-peer-pull-debit.test.ts @@ -19,13 +19,13 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { PeerPullPaymentCoinSelection } from "./db/records.js"; import { - getPeerPullDebitRecoverableCoins, + getPeerPullDebitDepositedCoinCount, getPeerPullDebitRemainder, - getPeerPullDebitUnconfirmedCoins, markPeerPullDebitCoinsDeposited, - partitionPeerPullDebitRepair, } from "./pay-peer-pull-debit.js"; +import { partitionPurseRepair } from "./purse-deposit-reconciliation.js"; + test("peer pull debit selects only the authenticated purse remainder", () => { assert.strictEqual( Amounts.stringify( @@ -65,29 +65,80 @@ test("signed batch progress advances only in prefix order", () => { contributions: ["TESTKUDOS:1", "TESTKUDOS:2", "TESTKUDOS:3"], totalCost: "TESTKUDOS:6", }; - markPeerPullDebitCoinsDeposited(selection, 0, 2, "TESTKUDOS:3"); + const batch = [ + { contribution: "TESTKUDOS:1", feeDeposit: "TESTKUDOS:0" }, + { contribution: "TESTKUDOS:2", feeDeposit: "TESTKUDOS:0" }, + ] as const; + markPeerPullDebitCoinsDeposited(selection, 0, batch, "TESTKUDOS:0"); assert.strictEqual(selection.depositedCoinCount, 2); - assert.strictEqual(selection.confirmedPurseBalance, "TESTKUDOS:3"); + assert.strictEqual(selection.balanceAtSelection, "TESTKUDOS:3"); assert.throws( - () => markPeerPullDebitCoinsDeposited(selection, 0, 1, "TESTKUDOS:4"), + () => markPeerPullDebitCoinsDeposited(selection, 0, batch, "TESTKUDOS:4"), /sequence/, ); }); -test("conflict repair never carries coins beyond the latest remainder", () => { +test("a restored pull selection skips history-proven coins and credits only the new batch", () => { const selection: PeerPullPaymentCoinSelection = { - coinPubs: ["accepted", "too-large", "fits", "broken"], - contributions: ["TESTKUDOS:2", "TESTKUDOS:6", "TESTKUDOS:3", "TESTKUDOS:2"], - totalCost: "TESTKUDOS:13", - depositedCoinCount: 1, + coinPubs: ["replay", "fresh", "remaining"], + contributions: ["TESTKUDOS:5", "TESTKUDOS:2", "TESTKUDOS:1"], + knownDepositCount: 1, + totalCost: "TESTKUDOS:8", }; - const partition = partitionPeerPullDebitRepair( - selection, - ["TESTKUDOS:1", "TESTKUDOS:1", "TESTKUDOS:1", "TESTKUDOS:1"], - "broken", - "TESTKUDOS:4", + assert.equal(getPeerPullDebitDepositedCoinCount(selection), 1); + const batch = [ + { contribution: "TESTKUDOS:2", feeDeposit: "TESTKUDOS:0.1" }, + ] as const; + assert.throws( + () => markPeerPullDebitCoinsDeposited(selection, 0, batch, "TESTKUDOS:7"), + /sequence/, ); + markPeerPullDebitCoinsDeposited(selection, 1, batch, "TESTKUDOS:7"); + assert.equal(getPeerPullDebitDepositedCoinCount(selection), 2); + for (const invalid of [-1, 0.5, 4]) { + assert.throws( + () => + getPeerPullDebitDepositedCoinCount({ + ...selection, + knownDepositCount: invalid, + }), + /progress/, + ); + } + assert.equal(selection.depositedCoinCount, 2); + assert.equal(selection.balanceAtSelection, "TESTKUDOS:8.9"); +}); +test("conflict repair never carries coins beyond the latest remainder", () => { + const recorded = { + coinPub: "recorded", + contribution: "TESTKUDOS:3", + } as const; + const accepted = { + coinPub: "accepted", + contribution: "TESTKUDOS:2", + } as const; + const partition = partitionPurseRepair( + [ + { disposition: "deposited", coin: accepted }, + { + disposition: "allocated", + recovery: { coinPub: "too-large", amount: "TESTKUDOS:7" }, + coin: { coinPub: "too-large", contribution: "TESTKUDOS:6" }, + feeDeposit: "TESTKUDOS:1", + }, + { disposition: "deposited", coin: recorded }, + { + disposition: "allocated", + recovery: { coinPub: "fits", amount: "TESTKUDOS:3" }, + coin: { coinPub: "fits", contribution: "TESTKUDOS:3" }, + feeDeposit: "TESTKUDOS:1", + }, + { disposition: "unavailable" }, + ], + "TESTKUDOS:4", + ); + assert.deepEqual(partition.deposited, [accepted, recorded]); assert.deepStrictEqual(partition.repair, [ { coinPub: "fits", @@ -95,50 +146,6 @@ test("conflict repair never carries coins beyond the latest remainder", () => { }, ]); assert.deepStrictEqual(partition.recover, [ - { coinPub: "too-large", amount: "TESTKUDOS:6" }, + { coinPub: "too-large", amount: "TESTKUDOS:7" }, ]); }); - -test("race recovery excludes confirmed and externally broken coins", () => { - const selection: PeerPullPaymentCoinSelection = { - coinPubs: ["accepted", "unsubmitted", "broken"], - contributions: ["TESTKUDOS:1", "TESTKUDOS:2", "TESTKUDOS:3"], - totalCost: "TESTKUDOS:6", - depositedCoinCount: 1, - }; - - assert.deepStrictEqual( - getPeerPullDebitUnconfirmedCoins(selection, new Set(["broken"])), - [{ coinPub: "unsubmitted", amount: "TESTKUDOS:2" }], - ); -}); - -test("a refunded pull purse gives back the confirmed deposits as well", () => { - const selection: PeerPullPaymentCoinSelection = { - coinPubs: ["one", "two", "three"], - contributions: ["TESTKUDOS:1", "TESTKUDOS:2", "TESTKUDOS:3"], - totalCost: "TESTKUDOS:6", - }; - markPeerPullDebitCoinsDeposited(selection, 0, 2, "TESTKUDOS:3"); - - assert.deepStrictEqual( - getPeerPullDebitRecoverableCoins(selection, "deposited").map( - (c) => c.coinPub, - ), - ["three"], - ); - assert.deepStrictEqual( - getPeerPullDebitRecoverableCoins(selection, "refunded").map( - (c) => c.coinPub, - ), - ["one", "two", "three"], - ); - assert.deepStrictEqual( - getPeerPullDebitRecoverableCoins( - selection, - "refunded", - new Set(["two"]), - ).map((c) => c.coinPub), - ["one", "three"], - ); -}); diff --git a/packages/taler-wallet-core/src/pay-peer-pull-debit.ts b/packages/taler-wallet-core/src/pay-peer-pull-debit.ts @@ -25,8 +25,8 @@ import { AbsoluteTime, AmountJson, AmountLike, + AmountString, Amounts, - CoinRefreshRequest, ConfirmPeerPullDebitRequest, ContractTermsUtil, ExchangePurseDeposits, @@ -46,6 +46,7 @@ import { TalerErrorDetail, TalerPayPullUri, TalerPreciseTimestamp, + TalerProtocolTimestamp, TalerUriAction, TalerUris, Transaction, @@ -57,7 +58,6 @@ import { TransactionType, assertUnreachable, checkDbInvariant, - checkLogicInvariant, codecForPeerContractTerms, decodeCrock, eddsaGetPublic, @@ -66,11 +66,7 @@ import { j2s, makeErrorDetail, } from "@gnu-taler/taler-util"; -import { - PreviousPayCoins, - coinsAddedByRepair, - selectPeerCoins, -} from "./coinSelection.js"; +import { selectPeerCoins } from "./coinSelection.js"; import { PendingTaskType, RecordHandle, @@ -102,7 +98,7 @@ import { import { getStoredPurseSelectionCostInTx, getTotalPeerPaymentCost, - getTotalPeerPaymentCostInTx, + netPurseDeposits, isPurseDeposited, isPurseGoneByExpiration, queryCoinInfosForSelection, @@ -129,8 +125,12 @@ import { import { PurseDepositReconciliation, reconcilePurseDeposits, + inspectPurseFunding, + applyPurseFundingInTx, makePurseDepositObserver, samePurseSelection, + resolvePurseDepositConflict, + SubmittedPurseCoin, } from "./purse-deposit-reconciliation.js"; const logger = new Logger("pay-peer-pull-debit.ts"); @@ -157,179 +157,59 @@ export function getPeerPullDebitRemainder( export function getPeerPullDebitDepositedCoinCount( selection: PeerPullPaymentCoinSelection, ): number { - const count = selection.depositedCoinCount ?? 0; + // Older repairs stored history-proven deposits separately from signed + // receipts. Both describe a prefix of the same selection. + const counts = [ + selection.depositedCoinCount ?? 0, + selection.knownDepositCount ?? 0, + ]; if ( - !Number.isSafeInteger(count) || - count < 0 || - count > selection.coinPubs.length || - selection.coinPubs.length !== selection.contributions.length + selection.coinPubs.length !== selection.contributions.length || + counts.some( + (n) => !Number.isSafeInteger(n) || n < 0 || n > selection.coinPubs.length, + ) ) { throw Error("invalid persisted peer pull-debit deposit progress"); } - return count; + return Math.max(...counts); +} + +function samePullFunding( + current: WalletPeerPullDebit, + expected: WalletPeerPullDebit, +): boolean { + const sel = current.coinSel; + const previous = expected.coinSel; + return ( + current.status === expected.status && + samePurseSelection(sel, previous) && + sel?.depositedCoinCount === previous?.depositedCoinCount && + sel?.knownDepositCount === previous?.knownDepositCount && + sel?.balanceAtSelection === previous?.balanceAtSelection && + sel?.needsRepair === previous?.needsRepair + ); } export function markPeerPullDebitCoinsDeposited( selection: PeerPullPaymentCoinSelection, batchStart: number, - batchSize: number, - confirmedPurseBalance: AmountLike, + coins: readonly { contribution: AmountString; feeDeposit: AmountString }[], + balanceBefore: AmountString, ): void { const oldCount = getPeerPullDebitDepositedCoinCount(selection); + const end = batchStart + coins.length; if ( batchStart !== oldCount || - !Number.isSafeInteger(batchSize) || - batchSize <= 0 || - batchStart + batchSize > selection.coinPubs.length + !coins.length || + end > selection.coinPubs.length ) { throw Error("invalid peer pull-debit deposit confirmation sequence"); } - selection.depositedCoinCount = batchStart + batchSize; - selection.confirmedPurseBalance = Amounts.stringify(confirmedPurseBalance); -} - -export function getPeerPullDebitUnconfirmedCoins( - selection: PeerPullPaymentCoinSelection, - unrecoverableCoinPubs: ReadonlySet<string> = new Set(), -): CoinRefreshRequest[] { - const acceptedCount = getPeerPullDebitDepositedCoinCount(selection); - const coins: CoinRefreshRequest[] = []; - for (let i = acceptedCount; i < selection.coinPubs.length; i++) { - if (unrecoverableCoinPubs.has(selection.coinPubs[i])) { - continue; - } - coins.push({ - amount: selection.contributions[i], - coinPub: selection.coinPubs[i], - }); - } - return coins; -} - -/** - * How a pull purse ended from the payer's point of view: "deposited" when - * it was filled and the payee gets the money, "refunded" when the exchange - * gave every deposit back (the invoice lapsed or was withdrawn). - */ -export type PeerPullDebitPurseOutcome = "deposited" | "refunded"; - -/** - * The coins whose contribution the wallet can claim back once the purse is - * gone. After a refund that is every coin; after a deposit only the ones - * whose batch was never confirmed by the exchange. - */ -export function getPeerPullDebitRecoverableCoins( - selection: PeerPullPaymentCoinSelection, - outcome: PeerPullDebitPurseOutcome, - unrecoverableCoinPubs: ReadonlySet<string> = new Set(), -): CoinRefreshRequest[] { - if (outcome === "deposited") { - return getPeerPullDebitUnconfirmedCoins(selection, unrecoverableCoinPubs); - } - const coins: CoinRefreshRequest[] = []; - for (let i = 0; i < selection.coinPubs.length; i++) { - if (unrecoverableCoinPubs.has(selection.coinPubs[i])) { - continue; - } - coins.push({ - amount: selection.contributions[i], - coinPub: selection.coinPubs[i], - }); - } - return coins; -} - -export function partitionPeerPullDebitRepair( - selection: PeerPullPaymentCoinSelection, - depositFees: AmountLike[], - brokenCoinPub: string, - remainder: AmountLike, -): { - repair: PreviousPayCoins; - recover: CoinRefreshRequest[]; -} { - if (depositFees.length !== selection.coinPubs.length) { - throw Error("missing deposit fee for peer pull-debit repair"); - } - let remaining = Amounts.parseOrThrow(remainder); - const repair: PreviousPayCoins = []; - const recover: CoinRefreshRequest[] = []; - const acceptedCount = getPeerPullDebitDepositedCoinCount(selection); - for (let i = acceptedCount; i < selection.coinPubs.length; i++) { - const coinPub = selection.coinPubs[i]; - if (coinPub === brokenCoinPub) { - continue; - } - const contribution = Amounts.parseOrThrow(selection.contributions[i]); - const netContribution = Amounts.sub(contribution, depositFees[i]); - if ( - !netContribution.saturated && - Amounts.isNonZero(netContribution.amount) && - Amounts.cmp(netContribution.amount, remaining) <= 0 - ) { - repair.push({ coinPub, contribution }); - remaining = Amounts.sub(remaining, netContribution.amount).amount; - } else { - recover.push({ - coinPub, - amount: Amounts.stringify(contribution), - }); - } - } - return { repair, recover }; -} - -async function getStoredPeerPullDebitSelectionCostInTx( - wex: WalletExecutionContext, - tx: WalletDbTransaction, - selection: PeerPullPaymentCoinSelection, - end: number, - currency: string, -): Promise<AmountJson> { - if (end === 0) { - return Amounts.zeroOfCurrency(currency); - } - const pubs = selection.coinPubs.slice(0, end); - const coins = await tx.getCoinsByPubs(pubs); - const coinsByPub = new Map(coins.map((coin) => [coin.coinPub, coin])); - const prospective = pubs.map((coinPub, i) => { - const coin = coinsByPub.get(coinPub); - checkDbInvariant(!!coin, `coin ${coinPub} missing from peer pull debit`); - return { - coinPub, - contribution: selection.contributions[i], - denomPubHash: coin.denomPubHash, - exchangeBaseUrl: coin.exchangeBaseUrl, - exchangeMasterPub: coin.exchangeMasterPub, - }; - }); - return getTotalPeerPaymentCostInTx(wex, tx, prospective); -} - -async function retainPeerPullDebitAcceptedSelectionInTx( - wex: WalletExecutionContext, - tx: WalletDbTransaction, - rec: WalletPeerPullDebit, -): Promise<number> { - if (!rec.coinSel) { - return 0; - } - const acceptedCount = getPeerPullDebitDepositedCoinCount(rec.coinSel); - if (acceptedCount === 0) { - return 0; - } - rec.coinSel.totalCost = Amounts.stringify( - await getStoredPeerPullDebitSelectionCostInTx( - wex, - tx, - rec.coinSel, - acceptedCount, - Amounts.currencyOf(rec.amount), - ), + const added = netPurseDeposits(Amounts.currencyOf(balanceBefore), coins); + selection.depositedCoinCount = end; + selection.balanceAtSelection = Amounts.stringify( + Amounts.add(balanceBefore, added).amount, ); - rec.coinSel.coinPubs = rec.coinSel.coinPubs.slice(0, acceptedCount); - rec.coinSel.contributions = rec.coinSel.contributions.slice(0, acceptedCount); - return acceptedCount; } async function retainPeerPullDebitReconciliationCoins( @@ -383,20 +263,13 @@ type PeerPullDebitCleanupStatus = | PeerPullDebitRecordStatus.Expired | PeerPullDebitRecordStatus.Failed; -function makePeerPullDebitPartialDepositError(): TalerErrorDetail { - return makeErrorDetail( - TalerErrorCode.WALLET_PEER_PULL_DEBIT_PURSE_GONE, - { purseExpired: false }, - "only part of this wallet's payment was accepted by the purse", - ); -} - /** * Common context for a peer-pull-debit transaction. */ export class PeerPullDebitTransactionContext implements TransactionContext { readonly transactionId: TransactionIdStr; readonly taskId: TaskIdStr; + readonly matchesFunding = samePullFunding; constructor( public wex: WalletExecutionContext, @@ -495,40 +368,6 @@ export class PeerPullDebitTransactionContext implements TransactionContext { ); } - async failTransaction( - fromSt: PeerPullDebitRecordStatus, - reason?: TalerErrorDetail, - unrecoverableCoinPubs: ReadonlySet<string> = new Set(), - ): Promise<void> { - const { wex } = this; - await wex.runWalletDbTx(async (tx) => { - const [rec, h] = await this.getRecordHandle(tx); - if (rec?.status != fromSt) { - return; - } - if (rec.coinSel) { - const recover = getPeerPullDebitUnconfirmedCoins( - rec.coinSel, - unrecoverableCoinPubs, - ); - if (recover.length > 0) { - await createRefreshGroup( - wex, - tx, - Amounts.currencyOf(rec.amount), - recover, - RefreshReason.AbortPeerPullDebit, - this.transactionId, - ); - } - await retainPeerPullDebitAcceptedSelectionInTx(wex, tx, rec); - } - rec.status = PeerPullDebitRecordStatus.Failed; - rec.failReason = reason; - await h.update(rec, "fail"); - }); - } - private async setCleanupStatus( tx: WalletDbTransaction, rec: WalletPeerPullDebit, @@ -554,21 +393,16 @@ export class PeerPullDebitTransactionContext implements TransactionContext { } async beginPurseReconciliation( - fromSt: PeerPullDebitRecordStatus, + expected: WalletPeerPullDebit, finalStatus: PeerPullDebitCleanupStatus, reason?: TalerErrorDetail, ): Promise<void> { await this.wex.runWalletDbTx(async (tx) => { const [rec, h] = await this.getRecordHandle(tx); - if (rec?.status !== fromSt) { + if (!rec || !samePullFunding(rec, expected)) { return; } - if (!rec.coinSel) { - rec.status = finalStatus; - } else { - rec.status = PeerPullDebitRecordStatus.AbortingReconcile; - rec.cleanupFinalStatus = finalStatus; - } + await this.setCleanupStatus(tx, rec, finalStatus); if (finalStatus === PeerPullDebitRecordStatus.Failed) { rec.failReason = reason; } else if (finalStatus === PeerPullDebitRecordStatus.Aborted) { @@ -644,72 +478,6 @@ export class PeerPullDebitTransactionContext implements TransactionContext { }); } - /** - * Terminate the transaction because the exchange does not have the purse of - * the invoice anymore, which happens when the invoice lapsed, when the - * payee withdrew it and when another wallet paid it first. - */ - async purseGoneTransaction( - fromSt: PeerPullDebitRecordStatus, - outcome: PeerPullDebitPurseOutcome, - unrecoverableCoinPubs: ReadonlySet<string> = new Set(), - ): Promise<void> { - const { wex } = this; - await wex.runWalletDbTx(async (tx) => { - const [rec, h] = await this.getRecordHandle(tx); - if (rec?.status != fromSt) { - return; - } - if (rec.coinSel) { - // Coins with a signed deposit confirmation did reach the purse. - // If the purse was completed and merged, their value went to the - // payee; if the exchange refunded the purse, every deposit went back - // onto its coin and all of them can be refreshed. - const acceptedCount = - outcome === "deposited" - ? getPeerPullDebitDepositedCoinCount(rec.coinSel) - : 0; - const coinPubs = getPeerPullDebitRecoverableCoins( - rec.coinSel, - outcome, - unrecoverableCoinPubs, - ); - if (coinPubs.length > 0) { - const refresh = await createRefreshGroup( - wex, - tx, - Amounts.currencyOf(rec.totalCostEstimated), - coinPubs, - RefreshReason.AbortPeerPullDebit, - this.transactionId, - ); - rec.abortRefreshGroupId = refresh.refreshGroupId; - } - if (acceptedCount > 0) { - await retainPeerPullDebitAcceptedSelectionInTx(wex, tx, rec); - rec.status = PeerPullDebitRecordStatus.Failed; - rec.failReason = makePeerPullDebitPartialDepositError(); - await h.update(rec, "purse-gone-after-partial-deposit"); - return; - } - } - const ct = await tx.getContractTerms(rec.contractTermsHash); - checkDbInvariant(!!ct, "contract terms for P2P payment not found"); - if (isPurseGoneByExpiration(ct.contractTermsRaw.purse_expiration)) { - rec.status = PeerPullDebitRecordStatus.Expired; - await h.update(rec, "expire"); - } else { - rec.status = PeerPullDebitRecordStatus.Aborted; - rec.abortReason = makeErrorDetail( - TalerErrorCode.WALLET_PEER_PULL_DEBIT_PURSE_GONE, - { purseExpired: false }, - "this invoice was already paid or withdrawn by the payee", - ); - await h.update(rec, "purse-gone"); - } - }); - } - async userDeleteTransaction(): Promise<void> { await this.wex.runWalletDbTx(async (tx) => { await this.deleteTransactionInTx(tx); @@ -852,216 +620,34 @@ export class PeerPullDebitTransactionContext implements TransactionContext { } } -async function handlePurseCreationConflict( +async function handlePurseDepositConflict( ctx: PeerPullDebitTransactionContext, peerPullInc: WalletPeerPullDebit, conflict: PurseConflict, + batch: readonly SubmittedPurseCoin[], ): Promise<TaskRunResult> { - if (conflict.code !== TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS) { - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Failed, - { ...conflict }, - ); - return TaskRunResult.progress(); - } - - const brokenCoinPub = conflict.coin_pub; - logger.trace(`excluded broken coin pub=${brokenCoinPub}`); - const exchangeBaseUrl = peerPullInc.exchangeBaseUrl; - const currency = Amounts.currencyOf(peerPullInc.amount); - - const sel = peerPullInc.coinSel; - checkDbInvariant( - !!sel, - `no coin selected for peer pull deposit ${peerPullInc.pursePub}`, - ); - - const statusResp = await walletExchangeClient( - exchangeBaseUrl, - ctx.wex, - ).getPurseStatusAtMerge(peerPullInc.pursePub); - switch (statusResp.case) { - case "ok": - break; - case HttpStatusCode.Gone: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Aborted, - ); - return TaskRunResult.progress(); - case HttpStatusCode.NotFound: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Failed, - statusResp.detail, - ); - return TaskRunResult.progress(); - default: - assertUnreachable(statusResp); - } - await requireValidExchangePurseStatus( - ctx.wex, - exchangeBaseUrl, - statusResp.body, + const resolution = await resolvePurseDepositConflict( + ctx, + peerPullInc, + conflict, + batch, ); - - const instructedAmount = getPeerPullDebitRemainder( - peerPullInc.amount, - statusResp.body.balance, - ); - if (isPurseDeposited(statusResp.body) || !instructedAmount) { + if (resolution.type === "retry") return resolution.result; + if (resolution.type === "failure") { await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Aborted, + peerPullInc, + PeerPullDebitRecordStatus.Failed, + resolution.reason, ); return TaskRunResult.progress(); } - const coinDetails = await queryCoinInfosForSelection(ctx.wex, sel); - const { repair, recover } = partitionPeerPullDebitRepair( - sel, - coinDetails.map((x) => x.feeDeposit), - brokenCoinPub, - instructedAmount, - ); - - const coinSelRes = await selectPeerCoins(ctx.wex, { - instructedAmount, - repair, - restrictScope: { - type: ScopeType.Exchange, - currency, - url: exchangeBaseUrl, - }, - }); - - switch (coinSelRes.type) { - case "failure": { - // Recover every unsubmitted, non-broken allocation. Once those - // refreshes produce fresh coins, the normal pending path re-selects - // against a newly authenticated remainder. - const recoverAfterFailure = [ - ...recover, - ...repair.map((x) => ({ - coinPub: x.coinPub, - amount: Amounts.stringify(x.contribution), - })), - ]; - await ctx.wex.runWalletDbTx(async (tx) => { - const [rec, h] = await ctx.getRecordHandle(tx); - if ( - rec?.status !== PeerPullDebitRecordStatus.PendingDeposit || - !rec.coinSel - ) { - return; - } - const acceptedCount = getPeerPullDebitDepositedCoinCount(rec.coinSel); - if (recoverAfterFailure.length > 0) { - await createRefreshGroup( - ctx.wex, - tx, - currency, - recoverAfterFailure, - RefreshReason.AbortPeerPullDebit, - ctx.transactionId, - ); - } - if (acceptedCount === 0) { - rec.coinSel = undefined; - } else { - rec.coinSel.totalCost = Amounts.stringify( - await getStoredPeerPullDebitSelectionCostInTx( - ctx.wex, - tx, - rec.coinSel, - acceptedCount, - currency, - ), - ); - rec.coinSel.coinPubs = rec.coinSel.coinPubs.slice(0, acceptedCount); - rec.coinSel.contributions = rec.coinSel.contributions.slice( - 0, - acceptedCount, - ); - rec.coinSel.confirmedPurseBalance = statusResp.body.balance; - } - await h.update(rec, "purse-conflict-await-refresh"); - }); - return TaskRunResult.backoff(); - } - case "success": - break; - default: - assertUnreachable(coinSelRes); - } - - const replacementCost = await getTotalPeerPaymentCost( - ctx.wex, - coinSelRes.result.coins, - ); - + // Re-read the purse and all outstanding allocations on the next attempt. await ctx.wex.runWalletDbTx(async (tx) => { - const [rec, h] = await ctx.getRecordHandle(tx); - if (!rec) { - return; - } - switch (rec.status) { - case PeerPullDebitRecordStatus.PendingDeposit: - case PeerPullDebitRecordStatus.SuspendedDeposit: { - if (!rec.coinSel) { - return; - } - const acceptedCount = getPeerPullDebitDepositedCoinCount(rec.coinSel); - const oldSelection = rec.coinSel; - const acceptedCost = await getStoredPeerPullDebitSelectionCostInTx( - ctx.wex, - tx, - oldSelection, - acceptedCount, - currency, - ); - if (recover.length > 0) { - await createRefreshGroup( - ctx.wex, - tx, - currency, - recover, - RefreshReason.AbortPeerPullDebit, - ctx.transactionId, - ); - } - const replacement = coinSelRes.result; - rec.coinSel = { - coinPubs: [ - ...oldSelection.coinPubs.slice(0, acceptedCount), - ...replacement.coins.map((x) => x.coinPub), - ], - contributions: [ - ...oldSelection.contributions.slice(0, acceptedCount), - ...replacement.coins.map((x) => x.contribution), - ], - totalCost: Amounts.stringify( - Amounts.add(acceptedCost, replacementCost).amount, - ), - depositedCoinCount: acceptedCount, - confirmedPurseBalance: statusResp.body.balance, - }; - // The carried-over coins were spent when they were first selected, - // the ones that replace the double-spent coin still have to be. - const added = coinsAddedByRepair(repair, replacement.coins); - await spendCoins(ctx.wex, tx, { - transactionId: ctx.transactionId, - coinPubs: added.map((x) => x.coinPub), - contributions: added.map((x) => Amounts.parseOrThrow(x.contribution)), - refreshReason: RefreshReason.PayPeerPull, - }); - await h.update(rec, "purse-conflict-repair"); - break; - } - default: - break; - } + const [rec, handle] = await ctx.getRecordHandle(tx); + if (!rec?.coinSel || !samePullFunding(rec, peerPullInc)) return; + rec.coinSel.needsRepair = true; + await handle.update(rec, "purse-conflict"); }); return TaskRunResult.progress(); } @@ -1069,6 +655,7 @@ async function handlePurseCreationConflict( async function processPeerPullDebitDialogProposed( wex: WalletExecutionContext, pullIni: WalletPeerPullDebit, + purseExpiration: TalerProtocolTimestamp, ): Promise<TaskRunResult> { const ctx = new PeerPullDebitTransactionContext(wex, pullIni.peerPullDebitId); const exchangeClient = walletExchangeClient(pullIni.exchangeBaseUrl, wex); @@ -1082,14 +669,20 @@ async function processPeerPullDebitDialogProposed( case HttpStatusCode.Gone: // The purse is gone: the invoice lapsed, the payee withdrew it, or // another wallet paid it. - await ctx.purseGoneTransaction( - PeerPullDebitRecordStatus.DialogProposed, - "refunded", + await ctx.beginPurseReconciliation( + pullIni, + isPurseGoneByExpiration(purseExpiration) + ? PeerPullDebitRecordStatus.Expired + : PeerPullDebitRecordStatus.Aborted, ); - return TaskRunResult.finished(); + return TaskRunResult.progress(); case HttpStatusCode.NotFound: - await ctx.failTransaction(pullIni.status, resp.detail); - return TaskRunResult.finished(); + await ctx.beginPurseReconciliation( + pullIni, + PeerPullDebitRecordStatus.Failed, + resp.detail, + ); + return TaskRunResult.progress(); default: assertUnreachable(resp); } @@ -1105,23 +698,16 @@ async function processPeerPullDebitDialogProposed( !getPeerPullDebitRemainder(pullIni.amount, resp.body.balance) ) { logger.info("purse completed by another wallet"); - await ctx.wex.runWalletDbTx(async (tx) => { - const [rec, h] = await ctx.getRecordHandle(tx); - switch (rec?.status) { - case PeerPullDebitRecordStatus.DialogProposed: - rec.status = PeerPullDebitRecordStatus.Aborted; - rec.abortReason = makeErrorDetail( - TalerErrorCode.WALLET_PEER_PULL_DEBIT_ALREADY_PAID, - {}, - "invoice paid by another wallet", - ); - break; - default: - return; - } - await h.update(rec, "dialog-aborted"); - }); - return TaskRunResult.finished(); + await ctx.beginPurseReconciliation( + pullIni, + PeerPullDebitRecordStatus.Aborted, + makeErrorDetail( + TalerErrorCode.WALLET_PEER_PULL_DEBIT_ALREADY_PAID, + {}, + "invoice paid by another wallet", + ), + ); + return TaskRunResult.progress(); } return TaskRunResult.longpollReturnedPending(); @@ -1130,388 +716,248 @@ async function processPeerPullDebitDialogProposed( async function processPeerPullDebitPendingDeposit( wex: WalletExecutionContext, peerPullInc: WalletPeerPullDebit, + purseExpiration: TalerProtocolTimestamp, ): Promise<TaskRunResult> { const ctx = new PeerPullDebitTransactionContext( wex, peerPullInc.peerPullDebitId, ); - const { pursePub, coinSel } = peerPullInc; - - const exchangeBaseUrl = peerPullInc.exchangeBaseUrl; - - if (coinSel) { - const depositedCount = getPeerPullDebitDepositedCoinCount(coinSel); - if ( - depositedCount > 0 && - depositedCount === coinSel.coinPubs.length && - coinSel.confirmedPurseBalance && - !getPeerPullDebitRemainder( - peerPullInc.amount, - coinSel.confirmedPurseBalance, + const { pursePub, coinSel, exchangeBaseUrl } = peerPullInc; + + const depositedCoinCount = coinSel + ? getPeerPullDebitDepositedCoinCount(coinSel) + : 0; + const allConfirmed = + coinSel && + depositedCoinCount > 0 && + depositedCoinCount === coinSel.coinPubs.length; + const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex); + const statusResp = isPurseGoneByExpiration(purseExpiration) + ? await suspendForLongpoll(wex, () => + exchangeClient.getPurseStatusAtMerge(pursePub, true), ) - ) { + : await exchangeClient.getPurseStatusAtMerge(pursePub); + switch (statusResp.case) { + case "ok": + break; + case HttpStatusCode.Gone: + await ctx.beginPurseReconciliation( + peerPullInc, + isPurseGoneByExpiration(purseExpiration) + ? PeerPullDebitRecordStatus.Expired + : PeerPullDebitRecordStatus.Aborted, + ); + return TaskRunResult.progress(); + case HttpStatusCode.NotFound: + await ctx.beginPurseReconciliation( + peerPullInc, + isPurseGoneByExpiration(purseExpiration) + ? PeerPullDebitRecordStatus.Expired + : PeerPullDebitRecordStatus.Failed, + statusResp.detail, + ); + return TaskRunResult.progress(); + default: + assertUnreachable(statusResp); + } + await requireValidExchangePurseStatus(wex, exchangeBaseUrl, statusResp.body); + const expired = isPurseGoneByExpiration(purseExpiration); + const instructedAmount = getPeerPullDebitRemainder( + peerPullInc.amount, + statusResp.body.balance, + ); + if (isPurseDeposited(statusResp.body) || (!expired && !instructedAmount)) { + if (allConfirmed) { await wex.runWalletDbTx(async (tx) => { const [rec, h] = await ctx.getRecordHandle(tx); - if (rec?.status !== PeerPullDebitRecordStatus.PendingDeposit) { - return; - } + if (!rec?.coinSel || !samePullFunding(rec, peerPullInc)) return; + rec.coinSel.balanceAtSelection = statusResp.body.balance; + rec.coinSel.totalCost = Amounts.stringify( + await getStoredPurseSelectionCostInTx( + wex, + tx, + rec.coinSel, + Amounts.currencyOf(rec.amount), + ), + ); rec.status = PeerPullDebitRecordStatus.Done; - await h.update(rec, "deposit-replay-confirmed"); + await h.update(rec, "deposit-confirmed"); }); - return TaskRunResult.finished(); + return TaskRunResult.progress(); } - } - - const contractTerms = await wex.runWalletDbTx(async (tx) => - tx.getContractTerms(peerPullInc.contractTermsHash), - ); - checkDbInvariant( - !!contractTerms, - `no contract terms for peer pull debit ${peerPullInc.peerPullDebitId}`, - ); - - if ( - isPurseGoneByExpiration(contractTerms.contractTermsRaw.purse_expiration) - ) { - const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex); - const statusResp = await suspendForLongpoll(wex, () => - exchangeClient.getPurseStatusAtMerge(pursePub, true), + await ctx.beginPurseReconciliation( + peerPullInc, + expired + ? PeerPullDebitRecordStatus.Expired + : PeerPullDebitRecordStatus.Aborted, ); - switch (statusResp.case) { - case "ok": - await requireValidExchangePurseStatus( - wex, - exchangeBaseUrl, - statusResp.body, - ); - // A pull purse carries its merge timestamp from creation, so only - // the deposit timestamp says that the payee got the money. - if (isPurseDeposited(statusResp.body)) { - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Expired, - ); - return TaskRunResult.progress(); - } - // The local clock reached the deadline first. Reconcile again after - // the exchange has either expired or merged the purse, but do not - // select or submit any more coins. - return TaskRunResult.longpollReturnedPending(); - case HttpStatusCode.Gone: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Expired, - ); - return TaskRunResult.progress(); - case HttpStatusCode.NotFound: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Expired, - statusResp.detail, - ); - return TaskRunResult.progress(); - default: - assertUnreachable(statusResp); - } + return TaskRunResult.progress(); } - - // This can happen when there was a prospective coin selection, or after a - // conflict where the already-confirmed prefix was retained and every - // unsubmitted coin was sent to recovery. + // The local deadline can precede expiry at the exchange. + if (expired) return TaskRunResult.longpollReturnedPending(); + checkDbInvariant(!!instructedAmount, "missing outstanding purse amount"); + // Old selections have no expected balance. A receipt total can double-count + // a replay, so only reuse a plan sized for the balance we just observed. if ( - coinSel == null || - getPeerPullDebitDepositedCoinCount(coinSel) === coinSel.coinPubs.length + !coinSel?.balanceAtSelection || + coinSel.needsRepair || + depositedCoinCount === coinSel.coinPubs.length || + Amounts.cmp(coinSel.balanceAtSelection, statusResp.body.balance) !== 0 ) { - const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex); - const statusResp = await exchangeClient.getPurseStatusAtMerge(pursePub); - switch (statusResp.case) { - case "ok": - break; - case HttpStatusCode.Gone: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Aborted, - ); - return TaskRunResult.progress(); - case HttpStatusCode.NotFound: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Failed, - statusResp.detail, - ); - return TaskRunResult.progress(); - default: - assertUnreachable(statusResp); - } - await requireValidExchangePurseStatus( - wex, - exchangeBaseUrl, - statusResp.body, - ); - const instructedAmount = getPeerPullDebitRemainder( - peerPullInc.amount, - statusResp.body.balance, + const inspected = await inspectPurseFunding( + ctx, + peerPullInc, + depositedCoinCount, ); - if (isPurseDeposited(statusResp.body) || !instructedAmount) { + if (inspected.type === "unresolved") return TaskRunResult.backoff(); + if (inspected.type === "conflict") { await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Aborted, + peerPullInc, + PeerPullDebitRecordStatus.Failed, + makeErrorDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "Purse repair found conflicting deposit histories", + ), ); return TaskRunResult.progress(); } - const currency = instructedAmount.currency; - - const coinSelRes = await selectPeerCoins(wex, { - instructedAmount, - restrictScope: { - type: ScopeType.Exchange, - currency, - url: exchangeBaseUrl, - }, - }); - if (logger.shouldLogTrace()) { - logger.trace(`selected p2p coins (pull): ${j2s(coinSelRes)}`); - } - - let coins: SelectedProspectiveCoin[] | undefined = undefined; - - switch (coinSelRes.type) { - case "failure": - throw TalerError.fromDetail( - TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE, - { - insufficientBalanceDetails: coinSelRes.insufficientBalanceDetails, - }, - ); - case "success": - coins = coinSelRes.result.coins; - break; - default: - assertUnreachable(coinSelRes); - } - - const totalAmount = await getTotalPeerPaymentCost(wex, coins); - return await wex.runWalletDbTx(async (tx) => { + // A deposit may have arrived between the status and the history reads. + if (Amounts.cmp(inspected.depositedAmount, statusResp.body.balance) > 0) + return TaskRunResult.backoff(); + return wex.runWalletDbTx(async (tx) => { const [rec, h] = await ctx.getRecordHandle(tx); - if (!rec) { - return TaskRunResult.finished(); - } - if (rec.status !== PeerPullDebitRecordStatus.PendingDeposit) { - return TaskRunResult.backoff(); - } if ( - isPurseGoneByExpiration(contractTerms.contractTermsRaw.purse_expiration) - ) { + !rec || + !samePullFunding(rec, peerPullInc) || + isPurseGoneByExpiration(purseExpiration) + ) return TaskRunResult.progress(); - } - const acceptedCount = rec.coinSel - ? getPeerPullDebitDepositedCoinCount(rec.coinSel) - : 0; - if ( - (coinSel == null && rec.coinSel != null) || - (coinSel != null && - (!rec.coinSel || - acceptedCount !== rec.coinSel.coinPubs.length || - acceptedCount !== coinSel.coinPubs.length)) - ) { - return TaskRunResult.backoff(); - } - await spendCoins(wex, tx, { - transactionId: ctx.transactionId, - coinPubs: coinSelRes.result.coins.map((x) => x.coinPub), - contributions: coinSelRes.result.coins.map((x) => - Amounts.parseOrThrow(x.contribution), - ), - refreshReason: RefreshReason.PayPeerPull, - }); - const acceptedCoinPubs = rec.coinSel?.coinPubs ?? []; - const acceptedContributions = rec.coinSel?.contributions ?? []; - const acceptedCost = rec.coinSel?.totalCost - ? Amounts.parseOrThrow(rec.coinSel.totalCost) - : Amounts.zeroOfCurrency(currency); - rec.coinSel = { - coinPubs: [ - ...acceptedCoinPubs, - ...coinSelRes.result.coins.map((x) => x.coinPub), - ], - contributions: [ - ...acceptedContributions, - ...coinSelRes.result.coins.map((x) => x.contribution), - ], - totalCost: Amounts.stringify( - Amounts.add(acceptedCost, totalAmount).amount, - ), - depositedCoinCount: acceptedCount, - confirmedPurseBalance: statusResp.body.balance, - }; + const { selection, totalCost, insufficient, refreshGroupId } = + await applyPurseFundingInTx(wex, tx, { + inputs: inspected.inputs, + remainder: instructedAmount, + previousSelection: rec.coinSel, + balanceAtSelection: statusResp.body.balance, + transactionId: ctx.transactionId, + exchangeBaseUrl, + reason: RefreshReason.PayPeerPull, + }); + if (refreshGroupId) rec.abortRefreshGroupId = refreshGroupId; + const { knownDepositCount, ...funding } = selection; + rec.coinSel = funding.coinPubs.length + ? { ...funding, totalCost, depositedCoinCount: knownDepositCount } + : undefined; await h.update(rec, "select-coins"); - return TaskRunResult.progress(); + return insufficient + ? TaskRunResult.error( + makeErrorDetail( + TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE, + { + insufficientBalanceDetails: insufficient, + }, + ), + ) + : TaskRunResult.progress(); }); } - const exchangeClient = walletExchangeClient(peerPullInc.exchangeBaseUrl, wex); - // FIXME: We could skip batches that we've already submitted. - - const coins = await queryCoinInfosForSelection(wex, coinSel); + const batchCoins = await queryCoinInfosForSelection(wex, { + coinPubs: coinSel.coinPubs.slice( + depositedCoinCount, + depositedCoinCount + 64, + ), + contributions: coinSel.contributions.slice( + depositedCoinCount, + depositedCoinCount + 64, + ), + }); + wex.oc.observe({ + type: ObservabilityEventType.Message, + contents: `Depositing batch at ${depositedCoinCount}/${coinSel.coinPubs.length} of size ${batchCoins.length}`, + }); + const depositSigsResp = await wex.cryptoApi.signPurseDeposits({ + exchangeBaseUrl: peerPullInc.exchangeBaseUrl, + pursePub: peerPullInc.pursePub, + coins: batchCoins, + }); - const maxBatchSize = 64; - const depositedCoinCount = getPeerPullDebitDepositedCoinCount(coinSel); + const depositPayload: ExchangePurseDeposits = { + deposits: depositSigsResp.deposits, + }; - for (let i = depositedCoinCount; i < coins.length; i += maxBatchSize) { - if ( - isPurseGoneByExpiration(contractTerms.contractTermsRaw.purse_expiration) - ) { + if (logger.shouldLogTrace()) { + logger.trace(`purse deposit payload: ${j2s(depositPayload)}`); + } + await requireExchangeCoinUseConfirmedOrThrow(wex, exchangeBaseUrl); + // Signing can overlap a suspend or a repair of this payment. + const current = await wex.runWalletDbTx((tx) => + tx.getPeerPullDebit(peerPullInc.peerPullDebitId), + ); + if ( + !current || + !samePullFunding(current, peerPullInc) || + isPurseGoneByExpiration(purseExpiration) + ) { + return TaskRunResult.progress(); + } + const resp = await exchangeClient.depositIntoPurse(pursePub, depositPayload); + switch (resp.case) { + case "ok": { + await requireValidExchangePurseDepositConfirmation(wex, { + exchangeBaseUrl, + pursePub, + contractTermsHash: peerPullInc.contractTermsHash, + purseValueAfterFees: peerPullInc.amount, + purseExpiration, + response: resp.body, + }); + await wex.runWalletDbTx(async (tx) => { + const [rec, h] = await ctx.getRecordHandle(tx); + if (!rec?.coinSel || !samePullFunding(rec, peerPullInc)) return; + markPeerPullDebitCoinsDeposited( + rec.coinSel, + depositedCoinCount, + batchCoins, + statusResp.body.balance, + ); + await h.update(rec, "deposit-confirmed"); + }); return TaskRunResult.progress(); } - const batchSize = Math.min(maxBatchSize, coins.length - i); - - wex.oc.observe({ - type: ObservabilityEventType.Message, - contents: `Depositing batch at ${i}/${coins.length} of size ${batchSize}`, - }); - - const batchCoins = coins.slice(i, i + batchSize); - const depositSigsResp = await wex.cryptoApi.signPurseDeposits({ - exchangeBaseUrl: peerPullInc.exchangeBaseUrl, - pursePub: peerPullInc.pursePub, - coins: batchCoins, - }); - - const depositPayload: ExchangePurseDeposits = { - deposits: depositSigsResp.deposits, - }; - - if (logger.shouldLogTrace()) { - logger.trace(`purse deposit payload: ${j2s(depositPayload)}`); - } - await requireExchangeCoinUseConfirmedOrThrow(wex, exchangeBaseUrl); - const resp = await exchangeClient.depositIntoPurse( - pursePub, - depositPayload, - ); - switch (resp.case) { - case "ok": { - await requireValidExchangePurseDepositConfirmation(wex, { - exchangeBaseUrl, - pursePub, - contractTermsHash: peerPullInc.contractTermsHash, - purseValueAfterFees: peerPullInc.amount, - purseExpiration: contractTerms.contractTermsRaw.purse_expiration, - response: resp.body, - }); - const purseComplete = - getPeerPullDebitRemainder( - peerPullInc.amount, - resp.body.total_deposited, - ) === undefined; - const confirmationStored = await wex.runWalletDbTx(async (tx) => { - const [rec, h] = await ctx.getRecordHandle(tx); - if ( - rec?.status !== PeerPullDebitRecordStatus.PendingDeposit || - !rec.coinSel - ) { - return false; - } - const currentCount = getPeerPullDebitDepositedCoinCount(rec.coinSel); - if (currentCount !== i) { - return false; - } - markPeerPullDebitCoinsDeposited( - rec.coinSel, - i, - batchSize, - resp.body.total_deposited, - ); - if (purseComplete) { - const acceptedCount = i + batchSize; - const unsubmitted: CoinRefreshRequest[] = []; - for ( - let coinIndex = acceptedCount; - coinIndex < rec.coinSel.coinPubs.length; - coinIndex++ - ) { - unsubmitted.push({ - coinPub: rec.coinSel.coinPubs[coinIndex], - amount: rec.coinSel.contributions[coinIndex], - }); - } - if (unsubmitted.length > 0) { - await createRefreshGroup( - wex, - tx, - Amounts.currencyOf(peerPullInc.amount), - unsubmitted, - RefreshReason.AbortPeerPullDebit, - ctx.transactionId, - ); - } - rec.coinSel.totalCost = Amounts.stringify( - await getStoredPeerPullDebitSelectionCostInTx( - wex, - tx, - rec.coinSel, - acceptedCount, - Amounts.currencyOf(peerPullInc.amount), - ), - ); - rec.coinSel.coinPubs = rec.coinSel.coinPubs.slice(0, acceptedCount); - rec.coinSel.contributions = rec.coinSel.contributions.slice( - 0, - acceptedCount, - ); - rec.status = PeerPullDebitRecordStatus.Done; - } - await h.update(rec, "deposit-confirmed"); - return true; - }); - if (!confirmationStored) { - return TaskRunResult.progress(); - } - if (purseComplete) { - return TaskRunResult.finished(); - } - continue; - } - case HttpStatusCode.Gone: { - await ctx.beginPurseReconciliation( - peerPullInc.status, - isPurseGoneByExpiration( - contractTerms.contractTermsRaw.purse_expiration, - ) - ? PeerPullDebitRecordStatus.Expired - : PeerPullDebitRecordStatus.Aborted, - ); - return TaskRunResult.progress(); - } - case HttpStatusCode.Conflict: - return handlePurseCreationConflict(ctx, peerPullInc, resp.body); - case HttpStatusCode.Forbidden: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Failed, - resp.detail, - ); - return TaskRunResult.progress(); - case HttpStatusCode.NotFound: - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Failed, - resp.detail, - ); - return TaskRunResult.progress(); - default: - assertUnreachable(resp); + case HttpStatusCode.Gone: { + await ctx.beginPurseReconciliation( + peerPullInc, + isPurseGoneByExpiration(purseExpiration) + ? PeerPullDebitRecordStatus.Expired + : PeerPullDebitRecordStatus.Aborted, + ); + return TaskRunResult.progress(); } + case HttpStatusCode.Conflict: + return handlePurseDepositConflict( + ctx, + peerPullInc, + resp.body, + batchCoins, + ); + case HttpStatusCode.Forbidden: + await ctx.beginPurseReconciliation( + peerPullInc, + PeerPullDebitRecordStatus.Failed, + resp.detail, + ); + return TaskRunResult.progress(); + case HttpStatusCode.NotFound: + await ctx.beginPurseReconciliation( + peerPullInc, + PeerPullDebitRecordStatus.Failed, + resp.detail, + ); + return TaskRunResult.progress(); + default: + assertUnreachable(resp); } - await ctx.beginPurseReconciliation( - peerPullInc.status, - PeerPullDebitRecordStatus.Failed, - { - code: TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, - hint: "exchange accepted every selected coin but reported an incomplete purse", - }, - ); - return TaskRunResult.progress(); } async function processPeerPullDebitAbortingRefresh( @@ -1691,8 +1137,11 @@ export async function processPeerPullDebit( isPurseGoneByExpiration(purseExpiration) ) { const ctx = new PeerPullDebitTransactionContext(wex, peerPullDebitId); - await ctx.purseGoneTransaction(peerPullInc.status, "refunded"); - return TaskRunResult.finished(); + await ctx.beginPurseReconciliation( + peerPullInc, + PeerPullDebitRecordStatus.Expired, + ); + return TaskRunResult.progress(); } if (!wex.ws.networkAvailable) { @@ -1714,9 +1163,17 @@ export async function processPeerPullDebit( switch (peerPullInc.status) { case PeerPullDebitRecordStatus.DialogProposed: - return processPeerPullDebitDialogProposed(wex, peerPullInc); + return processPeerPullDebitDialogProposed( + wex, + peerPullInc, + purseExpiration, + ); case PeerPullDebitRecordStatus.PendingDeposit: - return processPeerPullDebitPendingDeposit(wex, peerPullInc); + return processPeerPullDebitPendingDeposit( + wex, + peerPullInc, + purseExpiration, + ); case PeerPullDebitRecordStatus.AbortingRefresh: return processPeerPullDebitAbortingRefresh(wex, peerPullInc); case PeerPullDebitRecordStatus.AbortingReconcile: @@ -1766,7 +1223,10 @@ export async function confirmPeerPullDebit( ); const purseExpiration = contractTerms.contractTermsRaw.purse_expiration; if (isPurseGoneByExpiration(purseExpiration)) { - await ctx.purseGoneTransaction(peerPullInc.status, "refunded"); + await ctx.beginPurseReconciliation( + peerPullInc, + PeerPullDebitRecordStatus.Expired, + ); return { transactionId: ctx.transactionId }; } @@ -1780,10 +1240,19 @@ export async function confirmPeerPullDebit( case "ok": break; case HttpStatusCode.Gone: - await ctx.purseGoneTransaction(peerPullInc.status, "refunded"); + await ctx.beginPurseReconciliation( + peerPullInc, + isPurseGoneByExpiration(purseExpiration) + ? PeerPullDebitRecordStatus.Expired + : PeerPullDebitRecordStatus.Aborted, + ); return { transactionId: ctx.transactionId }; case HttpStatusCode.NotFound: - await ctx.failTransaction(peerPullInc.status, statusResp.detail); + await ctx.beginPurseReconciliation( + peerPullInc, + PeerPullDebitRecordStatus.Failed, + statusResp.detail, + ); return { transactionId: ctx.transactionId }; default: assertUnreachable(statusResp); @@ -1795,7 +1264,10 @@ export async function confirmPeerPullDebit( statusResp.body.balance, ); if (isPurseDeposited(statusResp.body) || !instructedAmount) { - await ctx.purseGoneTransaction(peerPullInc.status, "deposited"); + await ctx.beginPurseReconciliation( + peerPullInc, + PeerPullDebitRecordStatus.Aborted, + ); return { transactionId: ctx.transactionId }; } const currency = instructedAmount.currency; @@ -1858,7 +1330,7 @@ export async function confirmPeerPullDebit( contributions: coinSelRes.result.coins.map((x) => x.contribution), totalCost: Amounts.stringify(totalAmount), depositedCoinCount: 0, - confirmedPurseBalance: statusResp.body.balance, + balanceAtSelection: statusResp.body.balance, }; } rec.status = PeerPullDebitRecordStatus.PendingDeposit; diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.test.ts @@ -31,13 +31,17 @@ import { classifyPurseDepositCoinHistory, reconcilePurseDeposits, makePurseDepositObserver, + inspectPurseFunding, + resolvePurseDepositConflict, } from "./purse-deposit-reconciliation.js"; import { HttpRequestLibrary, HttpResponse } from "@gnu-taler/taler-util/http"; import { PeerPushDebitTransactionContext } from "./pay-peer-push-debit.js"; import { PeerPullDebitTransactionContext } from "./pay-peer-pull-debit.js"; +import { TaskRunResultType } from "./common.js"; import { PeerPullDebitRecordStatus, + PurseDepositSelection, RefreshCoinStatus, WalletPeerPullDebit, } from "./db/records.js"; @@ -252,6 +256,29 @@ test("an unknown purse coin recovers its face value after change settles", async } }); +test("a previously observed purse deposit missing from a later read remains unresolved", async () => { + const wex = coinHistoryContext(HttpStatusCode.NotFound, { + code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN, + }); + const payment = { + ...args, + status: 1, + amount: args.contribution, + coinSel: { ...selection, observedPurseCoinPubs: [args.coinPub] }, + }; + const inspected = await inspectPurseFunding( + { + wex, + transactionId, + async getRecordHandle() { + throw Error("unexpected record update"); + }, + }, + payment, + ); + assert.equal(inspected.type, "unresolved"); +}); + test("purse coin recovery rejects unrelated, malformed and transient errors", async () => { for (const [status, body] of [ [ @@ -279,6 +306,58 @@ test("purse coin recovery rejects unrelated, malformed and transient errors", as } }); +function resolveConflict( + wex: WalletExecutionContext, + coinPub = args.coinPub, + stored: PurseDepositSelection = structuredClone(selection), +) { + const payment = { + status: 1, + pursePub: args.pursePub, + exchangeBaseUrl: args.exchangeBaseUrl, + coinSel: stored, + }; + return resolvePurseDepositConflict( + { + wex, + transactionId: new PeerPushDebitTransactionContext(wex, args.pursePub) + .transactionId, + async getRecordHandle() { + const rec = structuredClone(payment); + return [ + rec, + { + rec, + async update(updated) { + assert.ok(updated); + Object.assign(stored, updated.coinSel); + }, + }, + ]; + }, + }, + structuredClone(payment), + { + code: TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS, + hint: "spent", + coin_pub: coinPub, + }, + stored.coinPubs.map((coinPub, i) => ({ + coinPub, + contribution: stored.contributions[i], + })), + ); +} + +test("an insufficient-funds response must identify a coin in the submitted batch", async () => { + const result = await resolveConflict(coinHistoryContext(500, {}), "outside"); + assert.equal(result.type, "failure"); + assert.equal( + result.reason.code, + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + ); +}); + test("only recovery of a positive purse residual waits for an unconfirmed change melt", async () => { const history = { balance: "TESTKUDOS:1", @@ -326,6 +405,186 @@ test("only recovery of a positive purse residual waits for an unconfirmed change } }); +test("a rejected coin with enough value retries the same contribution before failing a repeated contradiction", async () => { + for (const [amount, balance] of [ + ["TESTKUDOS:3", "TESTKUDOS:2"], + ["TESTKUDOS:2", "TESTKUDOS:3"], + ] as const) { + const history = { + balance, + h_denom_pub: "denom", + history: [deposit({ amount, purse_pub: "other" })], + }; + const stored = structuredClone(selection); + const first = await resolveConflict( + coinHistoryContext(200, history), + args.coinPub, + stored, + ); + assert.equal(first.type, "retry"); + assert.equal(first.result.type, TaskRunResultType.Error); + const repeated = await resolveConflict( + coinHistoryContext(200, history), + args.coinPub, + structuredClone(stored), + ); + assert.equal(repeated.type, "failure"); + assert.equal( + repeated.reason.code, + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + ); + } +}); + +test("a deposit to this purse keeps its authorization when the remaining balance is insufficient", async () => { + const stored: PurseDepositSelection = structuredClone(selection); + const history = { + balance: "TESTKUDOS:0", + h_denom_pub: "denom", + history: [ + deposit({ purse_pub: "other", amount: "TESTKUDOS:3" }), + deposit({ history_offset: 1 }), + ], + }; + const first = await resolveConflict( + coinHistoryContext(200, history), + args.coinPub, + stored, + ); + assert.deepEqual(first, { type: "repair" }); + assert.deepEqual(stored.observedPurseCoinPubs, [args.coinPub]); + assert.equal(stored.retriedDepositConflicts, undefined); +}); + +test("alternating rejections survive intervening errors and a wallet restart", async () => { + const stored: PurseDepositSelection = { + coinPubs: [args.coinPub, "second"], + contributions: [args.contribution, args.contribution], + }; + const history = { + balance: "TESTKUDOS:3", + h_denom_pub: "denom", + history: [deposit({ purse_pub: "other" })], + }; + for (const pub of stored.coinPubs) { + const result = await resolveConflict( + coinHistoryContext(200, history, undefined, pub), + pub, + stored, + ); + assert.equal(result.type, "retry"); + assert.equal(result.result.type, TaskRunResultType.Error); + } + await assert.rejects( + resolveConflict(coinHistoryContext(503, {}), args.coinPub, stored), + ); + const restarted = structuredClone(stored); + const result = await resolveConflict( + coinHistoryContext(200, history), + args.coinPub, + restarted, + ); + assert.equal(result.type, "failure"); + assert.equal( + result.reason.code, + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + ); +}); + +test("missing history for a rejected coin triggers reconciliation while transport errors remain retryable", async () => { + const missing = { code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN }; + const result = await resolveConflict( + coinHistoryContext(HttpStatusCode.NotFound, missing), + ); + assert.equal(result.type, "failure"); + assert.equal( + result.reason.code, + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + ); + await assert.rejects( + resolveConflict( + coinHistoryContext(HttpStatusCode.ServiceUnavailable, missing), + ), + ); +}); + +test("different authorizations on the same purse neither retry nor count toward the payment", async () => { + for (const overrides of [ + { amount: "TESTKUDOS:4" }, + { amount: args.contribution, exchange_base_url: "https://other.example/" }, + ] as const) { + const balance = + overrides.amount === "TESTKUDOS:4" ? "TESTKUDOS:1" : "TESTKUDOS:3"; + const history = { + balance, + h_denom_pub: "denom", + history: [deposit(overrides)], + }; + assert.equal( + classifyPurseDepositCoinHistory( + [deposit({ ...overrides, refunded: true })], + args, + ), + "different-refunded", + ); + const stored: PurseDepositSelection = structuredClone(selection); + const result = await resolveConflict( + coinHistoryContext(200, history), + args.coinPub, + stored, + ); + assert.equal(result.type, "failure"); + assert.equal( + result.reason.code, + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + ); + assert.equal(stored.retriedDepositConflicts, undefined); + assert.deepEqual(stored.observedPurseCoinPubs, [args.coinPub]); + + const mixed = { + coinPubs: [args.coinPub, "unused", "paid"], + contributions: [args.contribution, args.contribution, args.contribution], + }; + const wex = coinHistoryContext( + 200, + (pub: string) => { + if (pub === args.coinPub) return history; + if (pub === "paid") + return { + balance: "TESTKUDOS:3", + h_denom_pub: "denom", + history: [deposit()], + }; + return { balance: "TESTKUDOS:5", h_denom_pub: "denom", history: [] }; + }, + undefined, + mixed.coinPubs, + ); + const live = await reconcilePurseDeposits(wex, { + ...args, + transactionId, + selection: mixed, + purseFinal: false, + }); + assert.deepEqual(live, { + recoverable: [{ coinPub: "unused", amount: "TESTKUDOS:5" }], + committedDeposits: new Map([["paid", "TESTKUDOS:1.9"]]), + waitingCoinPubs: new Set([args.coinPub]), + }); + const final = await reconcilePurseDeposits(wex, { + ...args, + transactionId, + selection: stored, + purseFinal: true, + }); + assert.deepEqual(final, { + recoverable: [{ coinPub: args.coinPub, amount: balance }], + committedDeposits: new Map(), + waitingCoinPubs: new Set(), + }); + } +}); + test("a restarted pull reconciliation retains both matching and different live deposits", async (t) => { const pubs = ["matching", "different"]; let interrupt = true; diff --git a/packages/taler-wallet-core/src/purse-deposit-reconciliation.ts b/packages/taler-wallet-core/src/purse-deposit-reconciliation.ts @@ -16,19 +16,37 @@ import { AmountString, + AmountJson, + RefreshReason, + ScopeType, + AmountLike, Amounts, CoinSpendHistoryItem, TalerError, TalerErrorCode, TransactionIdStr, + TalerErrorDetail, + PurseConflict, + makeErrorDetail, checkDbInvariant, } from "@gnu-taler/taler-util"; +import { + PreviousPayCoins, + coinsAddedByRepair, + selectPeerCoinsInTx, +} from "./coinSelection.js"; import { readVerifiedCoinHistory } from "./coin-history.js"; -import { RecordHandle } from "./common.js"; +import { RecordHandle, TaskRunResult, spendCoins } from "./common.js"; import { PurseDepositSelection, RefreshCoinStatus } from "./db/records.js"; +import { + getStoredPurseSelectionCostInTx, + netPurseDeposits, + queryCoinInfosForSelection, +} from "./pay-peer-common.js"; import { BalanceEffect } from "./transactions.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { + createRefreshGroup, getUnconfirmedPurseChangeCoins, WalletCoinRefreshRequest, } from "./refresh.js"; @@ -154,8 +172,15 @@ async function inspectPurseCoins( } : { coinPub, amount: residual }; } + // The local allocation can coexist with its original change at full face + // value. A reduced balance is usable only after that change is settled. + const canUseAllocation = + !balance || + (Amounts.cmp(balance, contribution) >= 0 && + (!pendingChange || Amounts.cmp(balance, denom.value) === 0)); inspected.push({ recovery, + canUseAllocation, coinPub, contribution, feeDeposit: denom.feeDeposit, @@ -207,11 +232,24 @@ type PursePayment = PurseIdentity & { interface PursePaymentContext<T extends PursePayment> { wex: WalletExecutionContext; transactionId: TransactionIdStr; + matchesFunding?(current: T, expected: T): boolean; getRecordHandle( tx: WalletDbTransaction, ): Promise<[T | undefined, RecordHandle<T>]>; } +function matchesPursePayment<T extends PursePayment>( + ctx: PursePaymentContext<T>, + current: T, + expected: T, +) { + return ( + ctx.matchesFunding?.(current, expected) ?? + (current.status === expected.status && + samePurseSelection(current.coinSel, expected.coinSel)) + ); +} + /** Persist the first observation before another history request can fail. */ export function makePurseDepositObserver<T extends PursePayment>( ctx: PursePaymentContext<T>, @@ -226,12 +264,7 @@ export function makePurseDepositObserver<T extends PursePayment>( await ctx.wex.runWalletDbTx(async (tx) => { const [current, handle] = await ctx.getRecordHandle(tx); const sel = current?.coinSel; - if ( - !current || - !sel || - current.status !== payment.status || - !samePurseSelection(sel, selection) - ) + if (!current || !sel || !matchesPursePayment(ctx, current, payment)) return; if (!observedPurseCoinPubs(sel).has(coinPub)) { (sel.observedPurseCoinPubs ??= []).push(coinPub); @@ -246,6 +279,104 @@ export function makePurseDepositObserver<T extends PursePayment>( }; } +export async function inspectPurseCoinHistories<T extends PursePayment>( + ctx: PursePaymentContext<T>, + payment: T, + submitted: SubmittedPurseCoin[], +) { + return inspectPurseCoins( + ctx.wex, + ctx.transactionId, + payment, + submitted, + makePurseDepositObserver(ctx, payment), + ); +} + +type PurseConflictResolution = + | { type: "retry"; result: TaskRunResult } + | { type: "failure"; reason: TalerErrorDetail } + | { type: "repair" }; + +/** Decide whether to keep the selection, reconcile the purse, or replace a coin. */ +export async function resolvePurseDepositConflict<T extends PursePayment>( + ctx: PursePaymentContext<T>, + payment: T, + conflict: PurseConflict, + batch: readonly SubmittedPurseCoin[], +): Promise<PurseConflictResolution> { + if (conflict.code !== TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS) { + return { type: "failure", reason: { ...conflict } }; + } + const submitted = batch.find((coin) => coin.coinPub === conflict.coin_pub); + if (!submitted) { + return { + type: "failure", + reason: makeErrorDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + "Exchange rejected a coin outside the submitted purse deposit batch", + ), + }; + } + const { wex } = ctx; + const { coinPub, contribution } = submitted; + const [{ authorization, balance }] = await inspectPurseCoinHistories( + ctx, + payment, + [submitted], + ); + if ( + !balance || + (authorization === "absent" && + payment.coinSel && + observedPurseCoinPubs(payment.coinSel).has(coinPub)) || + authorization === "different" || + authorization === "different-refunded" || + authorization === "refunded" + ) { + return { + type: "failure", + reason: makeErrorDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + balance + ? "Rejected purse coin history contradicts the deposit authorization" + : "Exchange has no history for the coin it rejected as spent", + ), + }; + } + if (authorization === "committed" || Amounts.cmp(balance, contribution) < 0) { + return { type: "repair" }; + } + // The balance can change between a rejection and its history read. Retry + // this authorization once for each verified balance, including after restart. + return wex.runWalletDbTx(async (tx) => { + const [current, handle] = await ctx.getRecordHandle(tx); + const sel = current?.coinSel; + if (!current || !sel || !matchesPursePayment(ctx, current, payment)) { + return { type: "retry", result: TaskRunResult.progress() }; + } + const retried = (sel.retriedDepositConflicts ??= []); + if (retried.some((r) => r.coinPub === coinPub && r.balance === balance)) { + return { + type: "failure", + reason: makeErrorDetail( + TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION, + {}, + `Exchange repeatedly rejected a purse deposit of ${contribution} from coin ${coinPub} with verified balance ${balance}`, + ), + }; + } + retried.push({ coinPub, balance }); + await handle.update(current, "retry-purse-deposit"); + return { + type: "retry", + result: TaskRunResult.error({ ...conflict, contribution, balance }), + }; + }); +} + /** Reconcile local authorizations against history after checking the purse status. */ export async function reconcilePurseDeposits( wex: WalletExecutionContext, @@ -295,3 +426,204 @@ export async function reconcilePurseDeposits( } return { recoverable, committedDeposits, waitingCoinPubs }; } + +type PurseRepairCoin = + | { disposition: "deposited"; coin: SubmittedPurseCoin } + | { + disposition: "allocated"; + coin: SubmittedPurseCoin; + feeDeposit: AmountString; + recovery: WalletCoinRefreshRequest; + } + | { disposition: "unavailable"; recovery?: WalletCoinRefreshRequest }; + +/** Keep proven deposits for accounting. Only outstanding allocations can fund the remainder. */ +export function partitionPurseRepair( + coins: PurseRepairCoin[], + remainder: AmountLike, +) { + const deposited: SubmittedPurseCoin[] = []; + const repair: PreviousPayCoins = []; + const unusedIfUnfunded: WalletCoinRefreshRequest[] = []; + const recover: WalletCoinRefreshRequest[] = []; + let remaining = Amounts.parseOrThrow(remainder); + for (const input of coins) { + switch (input.disposition) { + case "deposited": + deposited.push(input.coin); + break; + case "unavailable": + if (input.recovery) recover.push(input.recovery); + break; + case "allocated": { + const { coinPub, contribution } = input.coin; + const net = Amounts.sub(contribution, input.feeDeposit); + if ( + Amounts.isNonZero(net.amount) && + Amounts.cmp(net.amount, remaining) <= 0 + ) { + repair.push({ + coinPub, + contribution: Amounts.parseOrThrow(contribution), + }); + unusedIfUnfunded.push(input.recovery); + remaining = Amounts.sub(remaining, net.amount).amount; + } else { + recover.push(input.recovery); + } + break; + } + } + } + return { deposited, repair, recover, unusedIfUnfunded }; +} + +/** Replace the outstanding funding and release unused allocations in the same transaction. */ +export async function applyPurseFundingInTx( + wex: WalletExecutionContext, + tx: WalletDbTransaction, + args: { + inputs: PurseRepairCoin[]; + previousSelection?: PurseDepositSelection; + balanceAtSelection?: AmountString; + remainder: AmountJson; + exchangeBaseUrl: string; + transactionId: TransactionIdStr; + reason: RefreshReason.PayPeerPush | RefreshReason.PayPeerPull; + }, +) { + const { remainder, inputs, transactionId, reason } = args; + const { currency } = remainder; + const { deposited, repair, recover, unusedIfUnfunded } = partitionPurseRepair( + inputs, + remainder, + ); + const coins = [...deposited]; + const replacement = Amounts.isNonZero(remainder) + ? await selectPeerCoinsInTx(wex, tx, { + instructedAmount: remainder, + repair, + restrictScope: { + type: ScopeType.Exchange, + currency, + url: args.exchangeBaseUrl, + }, + }) + : undefined; + if (replacement?.type === "success") { + coins.push(...replacement.result.coins); + const added = coinsAddedByRepair(repair, replacement.result.coins); + await spendCoins(wex, tx, { + transactionId, + coinPubs: added.map((c) => c.coinPub), + contributions: added.map((c) => Amounts.parseOrThrow(c.contribution)), + refreshReason: reason, + }); + } else if (replacement) { + recover.push(...unusedIfUnfunded); + } + const refresh = recover.length + ? await createRefreshGroup( + wex, + tx, + currency, + recover, + reason === RefreshReason.PayPeerPush + ? RefreshReason.AbortPeerPushDebit + : RefreshReason.AbortPeerPullDebit, + transactionId, + ) + : undefined; + const coinPubs = coins.map((c) => c.coinPub); + const retained = new Set(coinPubs); + const selection = { + coinPubs, + contributions: coins.map((c) => c.contribution), + balanceAtSelection: args.balanceAtSelection, + knownDepositCount: deposited.length, + retriedDepositConflicts: + args.previousSelection?.retriedDepositConflicts?.filter((retry) => + retained.has(retry.coinPub), + ), + needsRepair: replacement?.type === "failure", + }; + return { + selection, + totalCost: Amounts.stringify( + await getStoredPurseSelectionCostInTx(wex, tx, selection, currency), + ), + insufficient: + replacement?.type === "failure" + ? replacement.insufficientBalanceDetails + : undefined, + refreshGroupId: refresh?.refreshGroupId, + }; +} + +/** A restored wallet can be missing receipts for any coin in the unconfirmed suffix. */ +export async function inspectPurseFunding<T extends PursePayment>( + ctx: PursePaymentContext<T>, + payment: T & { amount: AmountString }, + acceptedCount = 0, +) { + const selection = payment.coinSel; + const inputs: PurseRepairCoin[] = []; + if (!selection) + return { + type: "success" as const, + inputs, + depositedAmount: Amounts.zeroOfAmount(payment.amount), + }; + const coins = purseSelectionCoins(selection); + if (new Set(selection.coinPubs).size !== coins.length) + return { type: "conflict" as const }; + const accepted = acceptedCount + ? await queryCoinInfosForSelection(ctx.wex, { + coinPubs: selection.coinPubs.slice(0, acceptedCount), + contributions: selection.contributions.slice(0, acceptedCount), + }) + : []; + for (const coin of coins.slice(0, acceptedCount)) + inputs.push({ disposition: "deposited", coin }); + let depositedAmount = netPurseDeposits( + Amounts.currencyOf(payment.amount), + accepted, + ); + const inspected = await inspectPurseCoinHistories( + ctx, + payment, + coins.slice(acceptedCount), + ); + const previouslySeen = observedPurseCoinPubs(selection); + for (const { + coinPub, + contribution, + authorization, + canUseAllocation, + feeDeposit, + recovery, + } of inspected) { + const coin = { coinPub, contribution }; + if (authorization === "committed") { + inputs.push({ disposition: "deposited", coin }); + depositedAmount = Amounts.add( + depositedAmount, + Amounts.sub(contribution, feeDeposit).amount, + ).amount; + } else if (authorization === "different") { + return { type: "conflict" as const }; + } else if (authorization !== "absent" || previouslySeen.has(coinPub)) { + // A history read can race a refund or temporarily omit a known deposit. + return { type: "unresolved" as const }; + } else if (!canUseAllocation) { + inputs.push({ disposition: "unavailable", recovery }); + } else { + checkDbInvariant( + !!recovery, + "usable purse allocation has no recoverable value", + ); + inputs.push({ disposition: "allocated", coin, feeDeposit, recovery }); + } + } + return { type: "success" as const, inputs, depositedAmount }; +}