commit bb1247050d60f04418d99161696dde4257af9343
parent 0b98aada82322bb332f9646004abf50e8626d325
Author: Florian Dold <dold@taler.net>
Date: Sun, 22 Nov 2026 22:51:36 +0100
wallet-core: verify local push deposits before funding another batch
Persist the batch before submitting it and confirm its coins from
signed history before advancing. Compare the proven net deposits with
the purse balance before spending again or sharing the payment URI.
A restored wallet can then resume a lost reply or wait when another
copy has funded part of the purse.
Diffstat:
8 files changed, 1739 insertions(+), 418 deletions(-)
diff --git a/packages/taler-harness/src/harness/harness.ts b/packages/taler-harness/src/harness/harness.ts
@@ -1755,6 +1755,7 @@ export interface ExchangeConfig {
allowExistingMasterPriv?: boolean;
overrideTestDir?: string;
overrideWireFee?: string;
+ overridePurseFee?: string;
/**
* Extra environment variables to pass to the exchange processes.
*/
@@ -2365,7 +2366,8 @@ export class ExchangeService implements ExchangeServiceInterface {
// account fee
`${this.exchangeConfig.currency}:0.01`,
// purse fee
- `${this.exchangeConfig.currency}:0.00`,
+ this.exchangeConfig.overridePurseFee ??
+ `${this.exchangeConfig.currency}:0.00`,
// purse timeout
"1h",
// history expiration
diff --git a/packages/taler-harness/src/integrationtests/test-peer-push-funding.ts b/packages/taler-harness/src/integrationtests/test-peer-push-funding.ts
@@ -0,0 +1,512 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import {
+ AmountString,
+ ExchangePurseStatus,
+ PurseDepositSuccessResponse,
+ NotificationType,
+ TalerErrorCode,
+ TransactionIdStr,
+ TransactionMajorState as Major,
+ TransactionMinorState as Minor,
+ TransactionType,
+ openPromise,
+} from "@gnu-taler/taler-util";
+import {
+ makeIdbRunner,
+ makeSqliteRunner,
+ WalletApiOperation as Op,
+} from "@gnu-taler/taler-wallet-core";
+import { makeLargeCoinTestConfig } from "../harness/denomStructures.js";
+import {
+ createSimpleTestkudosEnvironmentV3,
+ createWalletDaemonWithClient,
+ withdrawViaBankV4,
+} from "../harness/environments.js";
+import { FaultInjectionRequestContext } from "../harness/faultInjection.js";
+import {
+ GlobalTestState,
+ WalletClient,
+ harnessHttpLib,
+} from "../harness/harness.js";
+
+function reply(
+ req: FaultInjectionRequestContext,
+ status: number,
+ body: object,
+) {
+ req.dropRequest = true;
+ req.substituteResponseStatusCode = status;
+ req.substituteResponseHeaders = { "content-type": "application/json" };
+ req.substituteResponseBody = Buffer.from(JSON.stringify(body));
+}
+
+async function suspendPush(
+ wallet: WalletClient,
+ exchangeBaseUrl: string,
+ amount: AmountString,
+) {
+ await wallet.call(Op.HintNetworkAvailability, { isNetworkAvailable: false });
+ const push = await wallet.call(Op.InitiatePeerPushDebit, {
+ exchangeBaseUrl,
+ partialContractTerms: { amount, summary: "interrupt push funding" },
+ });
+ await wallet.call(Op.SuspendTransaction, {
+ transactionId: push.transactionId,
+ });
+ await wallet.call(Op.HintNetworkAvailability, { isNetworkAvailable: true });
+ await wallet.call(Op.TestingWaitRefreshesFinal, {});
+ return push;
+}
+
+async function stopWallet({
+ walletClient,
+ walletService,
+}: Awaited<ReturnType<typeof createWalletDaemonWithClient>>) {
+ walletClient.remoteWallet?.close();
+ await walletService.stop();
+}
+
+function waitReady(wallet: WalletClient, transactionId: TransactionIdStr) {
+ return wallet.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Pending, minor: Minor.Ready },
+ });
+}
+
+/** Lose the acknowledgement after only the last four authorizations reached the exchange. */
+export async function runPeerPushPartialFundingTest(t: GlobalTestState) {
+ const [one] = makeLargeCoinTestConfig();
+ const denom = {
+ ...one,
+ value: "TESTKUDOS:1.1",
+ feeDeposit: "TESTKUDOS:0.1",
+ } as const;
+ const {
+ bank,
+ faultyExchange: exchange,
+ walletClient: recipient,
+ } = await createSimpleTestkudosEnvironmentV3(t, [denom], {
+ faultInjection: true,
+ });
+ const start = (name: string) =>
+ createWalletDaemonWithClient(t, { name, persistent: true });
+ let payer = await start("payer");
+ const withdrawal = await withdrawViaBankV4(t, {
+ bank,
+ exchange,
+ walletClient: payer.walletClient,
+ amount: "TESTKUDOS:17.6",
+ });
+ await withdrawal.withdrawalFinishedCond;
+ const { transactionId, pursePub } = await suspendPush(
+ payer.walletClient,
+ exchange.baseUrl,
+ "TESTKUDOS:10",
+ );
+ const saved = await payer.walletClient.call(Op.ExportDb, {});
+ const accepted = openPromise<void>();
+ const release = openPromise<void>();
+ const posts: string[][] = [];
+ let deletes = 0;
+ let checkingCopy = false;
+ exchange.faultProxy.addFault({
+ async modifyRequest(req) {
+ const path = new URL(req.requestUrl).pathname;
+ if (!path.startsWith(`/purses/${pursePub}`)) return;
+ const postsCoins =
+ req.method === "POST" && /\/(create|deposit)$/.test(path);
+ if (req.method === "DELETE" || postsCoins)
+ t.assertTrue(
+ !checkingCopy,
+ "restored wallet modified a purse with unexplained funding",
+ );
+ if (req.method === "DELETE") deletes++;
+ if (!postsCoins) return;
+ const body = JSON.parse(req.requestBody!.toString());
+ posts.push(body.deposits.map((d: { coin_pub: string }) => d.coin_pub));
+ if (posts.length === 1) {
+ t.assertDeepEqual(body.deposits.length, 10);
+ body.deposits = body.deposits.slice(6);
+ req.requestBody = Buffer.from(JSON.stringify(body));
+ }
+ },
+ async modifyResponse(resp) {
+ if (
+ !new URL(resp.request.requestUrl).pathname.endsWith(
+ `/${pursePub}/create`,
+ )
+ )
+ return;
+ t.assertDeepEqual(resp.statusCode, 200);
+ t.assertAmountEquals(
+ JSON.parse(resp.responseBody!.toString()).total_deposited,
+ "TESTKUDOS:4",
+ );
+ accepted.resolve();
+ await release.promise;
+ },
+ });
+ await payer.walletClient.call(Op.ResumeTransaction, { transactionId });
+ await accepted.promise;
+ try {
+ await stopWallet(payer);
+ } finally {
+ release.resolve();
+ }
+
+ // A pre-upgrade copy remembers a balance of four, but retains evidence for
+ // only one of those units and has two unused allocations and six fresh coins.
+ checkingCopy = true;
+ let copy = await start("copy");
+ const localCoins = [posts[0][9], ...posts[0].slice(0, 2)];
+ const db = await (saved.databases ? makeIdbRunner() : makeSqliteRunner());
+ try {
+ await db.importDatabase(saved, async () => {});
+ await db.runReadWriteTx(async (tx) => {
+ const rec = await tx.getPeerPushDebit(pursePub);
+ if (!rec) throw Error("missing suspended payment");
+ rec.coinSel = {
+ coinPubs: localCoins,
+ contributions: localCoins.map(() => "TESTKUDOS:1.1"),
+ knownDepositCount: 1,
+ balanceAtSelection: "TESTKUDOS:4",
+ };
+ await tx.upsertPeerPushDebit(rec);
+ });
+ await copy.walletClient.call(Op.ImportDb, {
+ dump: await db.exportDatabase(),
+ });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const wallet = copy.walletClient;
+ const mismatch = wallet.waitForNotificationCond(
+ (n) =>
+ n.type === NotificationType.TransactionStateTransition &&
+ n.transactionId === transactionId &&
+ n.errorInfo?.code ===
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ );
+ await wallet.call(Op.ResumeTransaction, { transactionId });
+ await mismatch;
+ const pending = await wallet.call(Op.GetTransactionById, {
+ transactionId,
+ });
+ t.assertDeepEqual(pending.txState.major, Major.Pending);
+ t.assertTrue(
+ pending.type === TransactionType.PeerPushDebit && !pending.talerUri,
+ );
+ t.assertAmountEquals(
+ (await wallet.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:6.6",
+ );
+ await db.importDatabase(
+ await wallet.call(Op.ExportDb, {}),
+ async () => {},
+ );
+ await db.runReadWriteTx(async (tx) => {
+ const rec = await tx.getPeerPushDebit(pursePub);
+ t.assertDeepEqual(rec?.coinSel?.coinPubs, localCoins);
+ t.assertDeepEqual(rec?.abortRefreshGroupId, undefined);
+ });
+ t.assertDeepEqual(posts.length, 1);
+ t.assertDeepEqual(deletes, 0);
+ await wallet.call(Op.SuspendTransaction, { transactionId });
+ await stopWallet(copy);
+ if (attempt === 0) copy = await start("copy");
+ }
+ } finally {
+ await db.close();
+ }
+
+ checkingCopy = false;
+ payer = await start("payer");
+ await waitReady(payer.walletClient, transactionId);
+ t.assertDeepEqual(posts.slice(1), [posts[0].slice(0, 6)]);
+ t.assertDeepEqual(deletes, 0);
+ t.assertAmountEquals(
+ (await payer.walletClient.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:6.6",
+ );
+
+ // A matching copy restored after collection can finish directly from histories.
+ const ready = await payer.walletClient.call(Op.GetTransactionById, {
+ transactionId,
+ });
+ t.assertTrue(
+ ready.type === TransactionType.PeerPushDebit && !!ready.talerUri,
+ );
+ const credit = await recipient.call(Op.PreparePeerPushCredit, {
+ talerUri: ready.talerUri,
+ });
+ await recipient.call(Op.ConfirmPeerPushCredit, {
+ transactionId: credit.transactionId,
+ });
+ await recipient.call(Op.TestingWaitTransactionState, {
+ transactionId: credit.transactionId,
+ txState: { major: Major.Done },
+ });
+ checkingCopy = true;
+ const matching = await start("matching");
+ await matching.walletClient.call(Op.ImportDb, { dump: saved });
+ let becameReady = false;
+ const stopListening = matching.walletClient.addNotificationListener((n) => {
+ if (
+ n.type === NotificationType.TransactionStateTransition &&
+ n.transactionId === transactionId &&
+ n.newTxState.minor === Minor.Ready
+ )
+ becameReady = true;
+ });
+ await matching.walletClient.call(Op.ResumeTransaction, { transactionId });
+ await matching.walletClient.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Done },
+ });
+ t.assertTrue(!becameReady);
+ stopListening();
+}
+runPeerPushPartialFundingTest.suites = ["wallet"];
+
+/** Exercise an early full receipt with both a partial and a fully funded purse. */
+export async function runPeerPushBatchProofTest(t: GlobalTestState) {
+ const {
+ bank,
+ walletClient: source,
+ exchange: upstream,
+ faultyExchange: exchange,
+ } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig(), {
+ faultInjection: true,
+ });
+ const withdrawal = await withdrawViaBankV4(t, {
+ bank,
+ exchange,
+ walletClient: source,
+ amount: "TESTKUDOS:66",
+ });
+ await withdrawal.withdrawalFinishedCond;
+ const { transactionId, pursePub } = await suspendPush(
+ source,
+ exchange.baseUrl,
+ "TESTKUDOS:65",
+ );
+ const spare = await suspendPush(source, exchange.baseUrl, "TESTKUDOS:1");
+ const saved = await source.call(Op.ExportDb, {});
+ const mergePath = `/purses/${pursePub}/merge`;
+ const createPath = `/purses/${pursePub}/create`;
+ const depositPath = `/purses/${pursePub}/deposit`;
+ let partialStatus: ExchangePurseStatus | undefined;
+ let fullReceipt: PurseDepositSuccessResponse | undefined;
+ let lastCoin: string | undefined;
+ exchange.faultProxy.addFault({
+ async modifyResponse(resp) {
+ const path = new URL(resp.request.requestUrl).pathname;
+ if (path === createPath && resp.statusCode === 200) {
+ const res = await harnessHttpLib.fetch(
+ new URL(mergePath, upstream.baseUrl).href,
+ {},
+ );
+ const status = await res.json();
+ t.assertAmountEquals(status.balance, "TESTKUDOS:64");
+ partialStatus = status;
+ }
+ if (
+ path === depositPath &&
+ resp.request.method === "POST" &&
+ resp.statusCode === 200
+ ) {
+ t.assertAmountEquals(
+ JSON.parse(resp.responseBody!.toString()).total_deposited,
+ "TESTKUDOS:65",
+ );
+ lastCoin = JSON.parse(resp.request.requestBody!.toString()).deposits[0]
+ .coin_pub;
+ fullReceipt = JSON.parse(resp.responseBody!.toString());
+ }
+ },
+ });
+ await source.call(Op.ResumeTransaction, { transactionId });
+ await waitReady(source, transactionId);
+ await source.call(Op.SuspendTransaction, { transactionId });
+ exchange.faultProxy.clearAllFaults();
+ if (!fullReceipt || !partialStatus || !lastCoin)
+ throw Error("missing signed exchange responses");
+ const { total_deposited, exchange_timestamp, exchange_sig, exchange_pub } =
+ fullReceipt;
+ const createReceipt = {
+ total_deposited,
+ exchange_timestamp,
+ exchange_sig,
+ exchange_pub,
+ };
+ const depositReceipt = fullReceipt;
+ const statusAt64 = partialStatus;
+
+ // Build a restored selection that still holds an extra, unused authorization.
+ // Reserve the spare through the wallet so coin state and availability are real.
+ const db = await (saved.databases ? makeIdbRunner() : makeSqliteRunner());
+ let savedWithSpare: typeof saved;
+ let sparePub: string;
+ try {
+ await db.importDatabase(saved, async () => {});
+ await db.runReadWriteTx(async (tx) => {
+ const rec = await tx.getPeerPushDebit(pursePub);
+ const extra = await tx.getPeerPushDebit(spare.pursePub);
+ if (!rec?.coinSel || !extra?.coinSel) throw Error("missing allocations");
+ sparePub = extra.coinSel.coinPubs[0];
+ rec.coinSel.coinPubs.push(sparePub);
+ rec.coinSel.contributions.push(extra.coinSel.contributions[0]);
+ rec.totalCost = "TESTKUDOS:66";
+ await tx.upsertPeerPushDebit(rec);
+ const history = await tx.getCoinHistory(sparePub);
+ if (!history) throw Error("missing spare coin history");
+ for (const e of history.history) {
+ if (e.transactionId === spare.transactionId)
+ e.transactionId = transactionId;
+ }
+ await tx.upsertCoinHistory(history);
+ await tx.deletePeerPushDebit(spare.pursePub);
+ await tx.deleteTransactionMeta(spare.transactionId);
+ });
+ savedWithSpare = await db.exportDatabase();
+ } finally {
+ await db.close();
+ }
+
+ for (const actualFull of [false, true]) {
+ const name = actualFull ? "full" : "partial";
+ const start = () =>
+ createWalletDaemonWithClient(t, { name, persistent: true });
+ let copy = await start();
+ await copy.walletClient.call(Op.ImportDb, {
+ dump: actualFull ? savedWithSpare : saved,
+ });
+ const posts: string[][] = [];
+ const histories = new Set<string>();
+ const recoveries = new Set<string>();
+ const readingHistory = openPromise<void>();
+ const releaseHistory = openPromise<void>();
+ let interruptHistory = actualFull;
+ let readPurseAfterPost = false;
+ let deletes = 0;
+ exchange.faultProxy.addFault({
+ async modifyRequest(req) {
+ const path = new URL(req.requestUrl).pathname;
+ if (req.method === "DELETE" && path.includes(pursePub)) deletes++;
+ if (path.endsWith("/melt")) {
+ const melt = JSON.parse(req.requestBody!.toString());
+ if (melt.old_coin_pub === sparePub) recoveries.add(melt.refresh_seed);
+ }
+ if (
+ req.method === "GET" &&
+ path.startsWith("/coins/") &&
+ path.endsWith("/history") &&
+ posts.length
+ ) {
+ if (interruptHistory) {
+ interruptHistory = false;
+ readingHistory.resolve();
+ await releaseHistory.promise;
+ }
+ if (
+ !actualFull &&
+ posts.length === 1 &&
+ path === `/coins/${lastCoin}/history`
+ )
+ reply(req, 404, {
+ code: TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN,
+ });
+ }
+ if (req.method === "GET" && path === mergePath) {
+ if (!posts.length) {
+ reply(req, 404, {
+ code: TalerErrorCode.EXCHANGE_GENERIC_PURSE_UNKNOWN,
+ });
+ } else {
+ readPurseAfterPost = true;
+ if (!actualFull && posts.length === 1) reply(req, 200, statusAt64);
+ }
+ }
+ if (
+ req.method !== "POST" ||
+ (path !== createPath && path !== depositPath)
+ )
+ return;
+ const deposits = JSON.parse(req.requestBody!.toString()).deposits;
+ if (posts.length) {
+ t.assertTrue(!actualFull);
+ t.assertTrue(
+ readPurseAfterPost,
+ "another batch was sent before checking the purse balance",
+ );
+ t.assertTrue(posts[0].every((pub) => histories.has(pub)));
+ }
+ posts.push(deposits.map((d: { coin_pub: string }) => d.coin_pub));
+ // Present the same authentic, contract-bound aggregate to both copies.
+ reply(req, 200, path === createPath ? createReceipt : depositReceipt);
+ },
+ async modifyResponse(resp) {
+ const path = new URL(resp.request.requestUrl).pathname;
+ const history = /^\/coins\/([^/]+)\/history$/.exec(path);
+ if (history && resp.statusCode === 200 && posts.length)
+ histories.add(history[1]);
+ },
+ });
+ await copy.walletClient.call(Op.ResumeTransaction, { transactionId });
+ if (actualFull) {
+ // Stop after the receipt, before any matching coin history can be committed.
+ await readingHistory.promise;
+ try {
+ const pending = await copy.walletClient.call(Op.GetTransactionById, {
+ transactionId,
+ });
+ t.assertTrue(
+ pending.type === TransactionType.PeerPushDebit && !pending.talerUri,
+ );
+ await stopWallet(copy);
+ } finally {
+ releaseHistory.resolve();
+ }
+ copy = await start();
+ }
+ await waitReady(copy.walletClient, transactionId);
+ t.assertDeepEqual(
+ posts.map((batch) => batch.length),
+ actualFull ? [64] : [64, 1],
+ );
+ t.assertDeepEqual(new Set(posts.flat()).size, actualFull ? 64 : 65);
+ t.assertDeepEqual(histories.size, 65);
+ t.assertDeepEqual(deletes, 0);
+ if (actualFull) {
+ await copy.walletClient.call(Op.TestingWaitRefreshesFinal, {});
+ await stopWallet(copy);
+ copy = await start();
+ await waitReady(copy.walletClient, transactionId);
+ await copy.walletClient.call(Op.TestingWaitRefreshesFinal, {});
+ t.assertAmountEquals(
+ (await copy.walletClient.call(Op.GetBalances, {})).balances[0]
+ .available,
+ "TESTKUDOS:1",
+ );
+ t.assertDeepEqual(recoveries.size, 1);
+ t.assertDeepEqual(posts.length, 1);
+ }
+ await stopWallet(copy);
+ exchange.faultProxy.clearAllFaults();
+ }
+}
+runPeerPushBatchProofTest.suites = ["wallet"];
+runPeerPushBatchProofTest.timeoutMs = 120000;
diff --git a/packages/taler-harness/src/integrationtests/test-peer-push-recovery.ts b/packages/taler-harness/src/integrationtests/test-peer-push-recovery.ts
@@ -0,0 +1,546 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import {
+ AbsoluteTime,
+ Duration,
+ RefreshReason,
+ NotificationType,
+ ObservabilityEventType,
+ TransactionType,
+ TransactionMajorState as Major,
+ TransactionMinorState as Minor,
+ TalerErrorCode,
+ openPromise,
+} from "@gnu-taler/taler-util";
+import {
+ makeIdbRunner,
+ makeSqliteRunner,
+ TaskRunResultType,
+ WalletApiOperation as Op,
+} from "@gnu-taler/taler-wallet-core";
+import { makeLargeCoinTestConfig } from "../harness/denomStructures.js";
+import {
+ createSimpleTestkudosEnvironmentV3,
+ createWalletDaemonWithClient,
+ withdrawViaBankV4,
+} from "../harness/environments.js";
+import {
+ GlobalTestState,
+ WalletClient,
+ harnessHttpLib,
+} from "../harness/harness.js";
+import { readyUri } from "./test-peer-spent-coin.js";
+
+export async function runPeerSpentCoinSuspendedChangeTest(t: GlobalTestState) {
+ t.allowLog({
+ file: "exchange-httpd-testexchange-1-stderr.log",
+ level: "WARNING",
+ message:
+ /^Coin [0-9A-Z]+ has insufficient balance for purse deposit of amount TESTKUDOS:8$/,
+ maxOccurrences: 1,
+ justification:
+ "the restored wallet submits eight units from a coin with only six remaining",
+ });
+ const [one] = makeLargeCoinTestConfig();
+ const {
+ walletClient: original,
+ exchange,
+ bank,
+ } = await createSimpleTestkudosEnvironmentV3(t, [
+ one,
+ { ...one, name: "ten", value: "TESTKUDOS:10" },
+ ]);
+ const withdrawal = await withdrawViaBankV4(t, {
+ walletClient: original,
+ bank,
+ exchange,
+ amount: "TESTKUDOS:10",
+ });
+ await withdrawal.withdrawalFinishedCond;
+ let changeTask: string | undefined;
+ let residualTask: string | undefined;
+ let changeWokeResidual = false;
+ const residualSteps: string[] = [];
+ const startSender = () =>
+ createWalletDaemonWithClient(t, {
+ name: "restored",
+ persistent: true,
+ config: {
+ testing: {
+ devModeActive: true,
+ skipDefaults: true,
+ emitObservabilityEvents: true,
+ },
+ },
+ handleNotification(n) {
+ if (n.type !== NotificationType.TaskObservabilityEvent) return;
+ const e = n.event;
+ if (
+ n.taskId === changeTask &&
+ e.type === ObservabilityEventType.TaskStart &&
+ e.taskId === residualTask
+ )
+ changeWokeResidual = true;
+ if (n.taskId !== residualTask) return;
+ if (e.type === ObservabilityEventType.HttpFetchStart) {
+ const path = new URL(e.url).pathname;
+ if (path.endsWith("/history")) residualSteps.push("history");
+ if (path.endsWith("/melt")) residualSteps.push("melt");
+ } else if (
+ e.type === ObservabilityEventType.ShepherdTaskResult &&
+ e.resultType === TaskRunResultType.Backoff
+ ) {
+ residualSteps.push("backoff");
+ }
+ },
+ });
+ let sender = await startSender();
+ await sender.walletClient.call(Op.ImportDb, {
+ dump: await original.call(Op.ExportDb, {}),
+ });
+ const [coin] = (await original.call(Op.DumpCoins, {})).coins;
+ await original.call(Op.ForceRefresh, {
+ refreshCoinSpecs: [{ coinPub: coin.coinPub, amount: "TESTKUDOS:4" }],
+ });
+ await original.call(Op.TestingWaitRefreshesFinal, {});
+
+ // The restored wallet allocates eight to the purse and two to change.
+ await sender.walletClient.call(Op.ApplyDevExperiment, {
+ devExperimentUri: "taler://dev-experiment/start-block-refresh",
+ });
+ const { transactionId } = await sender.walletClient.call(
+ Op.InitiatePeerPushDebit,
+ {
+ exchangeBaseUrl: exchange.baseUrl,
+ partialContractTerms: {
+ summary: "replace a coin while its change is suspended",
+ amount: "TESTKUDOS:8",
+ },
+ },
+ );
+ const refreshes = async () =>
+ (
+ await sender.walletClient.call(Op.GetTransactions, {
+ includeRefreshes: true,
+ })
+ ).transactions.filter(
+ (tx) =>
+ tx.type === TransactionType.Refresh &&
+ tx.originatingTransactionId === transactionId,
+ );
+ const change = (await refreshes()).find(
+ (tx) =>
+ tx.type === TransactionType.Refresh &&
+ tx.refreshReason === RefreshReason.PayPeerPush,
+ );
+ t.assertTrue(!!change);
+ await sender.walletClient.call(Op.SuspendTransaction, {
+ transactionId: change.transactionId,
+ });
+ await sender.walletClient.call(Op.ApplyDevExperiment, {
+ devExperimentUri: "taler://dev-experiment/stop-block-refresh",
+ });
+ const topup = await withdrawViaBankV4(t, {
+ walletClient: sender.walletClient,
+ bank,
+ exchange,
+ amount: "TESTKUDOS:8",
+ });
+ await topup.withdrawalFinishedCond;
+ const talerUri = await readyUri(sender.walletClient, transactionId);
+ const { walletClient: recipient } = await createWalletDaemonWithClient(t, {
+ name: "recipient",
+ });
+ const credit = await recipient.call(Op.PreparePeerPushCredit, { talerUri });
+ await recipient.call(Op.ConfirmPeerPushCredit, {
+ transactionId: credit.transactionId,
+ });
+ await sender.walletClient.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Done },
+ });
+ await recipient.call(Op.TestingWaitTransactionState, {
+ transactionId: credit.transactionId,
+ txState: { major: Major.Done },
+ });
+ t.assertAmountEquals(
+ (await recipient.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:8",
+ );
+
+ const residual = (await refreshes()).find(
+ (tx) =>
+ tx.type === TransactionType.Refresh &&
+ tx.refreshReason === RefreshReason.AbortPeerPushDebit,
+ );
+ t.assertTrue(residual?.type === TransactionType.Refresh);
+ t.assertAmountEquals(residual.refreshOutputAmount, "TESTKUDOS:0");
+ t.assertDeepEqual(residual.txState.major, Major.Pending);
+
+ sender.walletClient.remoteWallet?.close();
+ await sender.walletService.stop();
+ changeTask = change.transactionId.slice("txn:".length);
+ residualTask = residual.transactionId.slice("txn:".length);
+ sender = await startSender();
+ await sender.walletClient.call(Op.ResumeTransaction, {
+ transactionId: change.transactionId,
+ });
+ await sender.walletClient.call(Op.TestingWaitRefreshesFinal, {});
+ t.assertTrue(changeWokeResidual);
+ const historyStep = residualSteps.indexOf("history");
+ t.assertTrue(historyStep >= 0);
+ t.assertDeepEqual(residualSteps.slice(historyStep, historyStep + 2), [
+ "history",
+ "melt",
+ ]);
+ const settled = await sender.walletClient.call(Op.GetTransactionById, {
+ transactionId: residual.transactionId,
+ });
+ t.assertTrue(settled.type === TransactionType.Refresh);
+ t.assertAmountEquals(settled.refreshInputAmount, "TESTKUDOS:4");
+ t.assertAmountEquals(settled.refreshOutputAmount, "TESTKUDOS:4");
+ const payment = await sender.walletClient.call(Op.GetTransactionById, {
+ transactionId,
+ });
+ t.assertAmountEquals(payment.amountEffectiveFinal!, "TESTKUDOS:12");
+ t.assertAmountEquals(
+ (await sender.walletClient.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:6",
+ );
+}
+runPeerSpentCoinSuspendedChangeTest.suites = ["wallet"];
+
+export async function runPeerPushRestoredPurseTest(t: GlobalTestState) {
+ t.allowLog({
+ file: "exchange-httpd-testexchange-1-stderr.log",
+ level: "WARNING",
+ message:
+ /^Coin [0-9A-Z]+ has insufficient balance for purse deposit of amount TESTKUDOS:1$/,
+ maxOccurrences: 2,
+ justification: "both copies initially submit the same spent coin",
+ });
+ const {
+ walletClient: source,
+ bank,
+ faultyExchange: exchange,
+ } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig(), {
+ faultInjection: true,
+ });
+ const { walletClient: first } = await createWalletDaemonWithClient(t, {
+ name: "first",
+ });
+ const { walletClient: second } = await createWalletDaemonWithClient(t, {
+ name: "second",
+ });
+ const { walletClient: recipient } = await createWalletDaemonWithClient(t, {
+ name: "recipient",
+ });
+ const withdraw = async (walletClient: WalletClient) => {
+ await (
+ await withdrawViaBankV4(t, {
+ walletClient,
+ exchange,
+ bank,
+ amount: "TESTKUDOS:1",
+ })
+ ).withdrawalFinishedCond;
+ };
+ await withdraw(source);
+ await first.call(Op.ImportDb, { dump: await source.call(Op.ExportDb, {}) });
+ const [coin] = (await source.call(Op.DumpCoins, {})).coins;
+ await source.call(Op.ForceRefresh, {
+ refreshCoinSpecs: [{ coinPub: coin.coinPub }],
+ });
+ await source.call(Op.TestingWaitRefreshesFinal, {});
+ await first.call(Op.HintNetworkAvailability, { isNetworkAvailable: false });
+ const { transactionId, pursePub } = await first.call(
+ Op.InitiatePeerPushDebit,
+ {
+ exchangeBaseUrl: exchange.baseUrl,
+ partialContractTerms: {
+ summary: "resume a restored push payment",
+ amount: "TESTKUDOS:1",
+ },
+ },
+ );
+ await first.call(Op.SuspendTransaction, { transactionId });
+ await first.call(Op.HintNetworkAvailability, { isNetworkAvailable: true });
+ await first.call(Op.TestingWaitRefreshesFinal, {});
+ const saved = await first.call(Op.ExportDb, {});
+ // Stage a different replacement in each copy. Pause the second after its
+ // selection is durable and before the exchange receives its replacement.
+ const replacementSubmitted = openPromise<void>();
+ let holdReplacement = true;
+ let staleSubmissions = 0;
+ exchange.faultProxy.addFault({
+ async modifyRequest(req) {
+ if (
+ !holdReplacement ||
+ req.method !== "POST" ||
+ !new URL(req.requestUrl).pathname.endsWith("/create")
+ )
+ return;
+ const [deposit] = JSON.parse(req.requestBody!.toString()).deposits;
+ if (deposit.coin_pub === coin.coinPub) {
+ staleSubmissions++;
+ return;
+ }
+ req.dropRequest = true;
+ req.substituteResponseStatusCode = 503;
+ req.substituteResponseHeaders = { "content-type": "application/json" };
+ req.substituteResponseBody = Buffer.from(JSON.stringify({ code: 1 }));
+ replacementSubmitted.resolve();
+ },
+ async modifyResponse(resp) {
+ if (
+ holdReplacement &&
+ staleSubmissions === 1 &&
+ resp.statusCode === 409 &&
+ new URL(resp.request.requestUrl).pathname.endsWith("/create")
+ ) {
+ // Lose the original rejection. The staged coin's history now proves
+ // it cannot pay, even though the wallet never learned that from the POST.
+ resp.statusCode = 503;
+ resp.responseBody = Buffer.from(JSON.stringify({ code: 1 }));
+ }
+ },
+ });
+ await second.call(Op.ImportDb, { dump: saved });
+ await withdraw(second);
+ await second.call(Op.ResumeTransaction, { transactionId });
+ await replacementSubmitted.promise;
+ t.assertDeepEqual(staleSubmissions, 1);
+ await second.call(Op.SuspendTransaction, { transactionId });
+ holdReplacement = false;
+
+ await withdraw(first);
+ await first.call(Op.ResumeTransaction, { transactionId });
+ const talerUri = await readyUri(first, transactionId);
+ const missingEvidence = second.waitForNotificationCond(
+ (n) =>
+ n.type === NotificationType.TransactionStateTransition &&
+ n.transactionId === transactionId &&
+ n.errorInfo?.code ===
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ );
+ await second.call(Op.ResumeTransaction, { transactionId });
+ await missingEvidence;
+ const pending = await second.call(Op.GetTransactionById, { transactionId });
+ t.assertDeepEqual(pending.txState.major, Major.Pending);
+ t.assertTrue(pending.txState.minor !== Minor.Ready);
+ const status = await harnessHttpLib.fetch(
+ new URL(`purses/${pursePub}/merge`, exchange.baseUrl).href,
+ {},
+ );
+ t.assertAmountEquals((await status.json()).balance, "TESTKUDOS:1");
+ const credit = await recipient.call(Op.PreparePeerPushCredit, { talerUri });
+ await recipient.call(Op.ConfirmPeerPushCredit, {
+ transactionId: credit.transactionId,
+ });
+ await recipient.call(Op.TestingWaitTransactionState, {
+ transactionId: credit.transactionId,
+ txState: { major: Major.Done },
+ });
+ t.assertAmountEquals(
+ (await recipient.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:1",
+ );
+ // The other copy's recipient has merged. Cancellation returns the unused coin.
+ await second.call(Op.AbortTransaction, { transactionId });
+ await second.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Aborted },
+ });
+ await second.call(Op.TestingWaitRefreshesFinal, {});
+ t.assertAmountEquals(
+ (await second.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:1",
+ );
+}
+
+runPeerPushRestoredPurseTest.suites = ["wallet"];
+
+export async function runPeerPushRefundedDuringRepairTest(t: GlobalTestState) {
+ t.allowLog({
+ file: "exchange-httpd-testexchange-1-stderr.log",
+ level: "WARNING",
+ message:
+ /^Coin [0-9A-Z]+ has insufficient balance for purse deposit of amount TESTKUDOS:1$/,
+ maxOccurrences: 1,
+ justification: "the last coin of the restored selection was already spent",
+ });
+ const {
+ walletClient: original,
+ bank,
+ faultyExchange: exchange,
+ } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig(), {
+ faultInjection: true,
+ });
+ const { walletClient: sender } = await createWalletDaemonWithClient(t, {
+ name: "sender",
+ });
+ const { walletClient: copy } = await createWalletDaemonWithClient(t, {
+ name: "copy",
+ });
+ await (
+ await withdrawViaBankV4(t, {
+ walletClient: original,
+ bank,
+ exchange,
+ amount: "TESTKUDOS:65",
+ })
+ ).withdrawalFinishedCond;
+ await sender.call(Op.ImportDb, {
+ dump: await original.call(Op.ExportDb, {}),
+ });
+
+ // The first batch funds 64 units. Spending the final coin in the original
+ // wallet makes the restored sender wait for one unit of replacement funding.
+ let spentLastCoin = false;
+ exchange.faultProxy.addFault({
+ async modifyRequest(req) {
+ if (
+ spentLastCoin ||
+ req.method !== "POST" ||
+ !new URL(req.requestUrl).pathname.endsWith("/deposit")
+ )
+ return;
+ const { deposits } = JSON.parse(req.requestBody!.toString());
+ t.assertDeepEqual(deposits.length, 1);
+ spentLastCoin = true;
+ await original.call(Op.ForceRefresh, {
+ refreshCoinSpecs: [{ coinPub: deposits[0].coin_pub }],
+ });
+ await original.call(Op.TestingWaitRefreshesFinal, {});
+ },
+ });
+ const needsFunds = sender.waitForNotificationCond(
+ (n) =>
+ n.type === NotificationType.TransactionStateTransition &&
+ n.errorInfo?.code ===
+ TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
+ );
+ const { transactionId } = await sender.call(Op.InitiatePeerPushDebit, {
+ exchangeBaseUrl: exchange.baseUrl,
+ partialContractTerms: {
+ summary: "abort a partly funded push payment from a copy",
+ amount: "TESTKUDOS:65",
+ },
+ });
+ await needsFunds;
+ await sender.call(Op.SuspendTransaction, { transactionId });
+ await copy.call(Op.ImportDb, { dump: await sender.call(Op.ExportDb, {}) });
+ await copy.call(Op.AbortTransaction, { transactionId });
+ await copy.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Aborted },
+ });
+ await copy.call(Op.TestingWaitRefreshesFinal, {});
+ t.assertAmountEquals(
+ (await copy.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:64",
+ );
+
+ await sender.call(Op.ResumeTransaction, { transactionId });
+ await sender.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Aborted },
+ });
+ await sender.call(Op.TestingWaitRefreshesFinal, {});
+ t.assertAmountEquals(
+ (await sender.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:0",
+ );
+}
+runPeerPushRefundedDuringRepairTest.suites = ["wallet"];
+
+/** A restored selection disagrees with the signed contribution already on its purse. */
+export async function runPeerPushConflictingHistoryTest(t: GlobalTestState) {
+ const {
+ walletClient: original,
+ exchange,
+ bank,
+ } = await createSimpleTestkudosEnvironmentV3(t, makeLargeCoinTestConfig());
+ const { walletClient: copy } = await createWalletDaemonWithClient(t, {
+ name: "copy",
+ });
+ const withdrawal = await withdrawViaBankV4(t, {
+ walletClient: original,
+ exchange,
+ bank,
+ amount: "TESTKUDOS:1",
+ });
+ await withdrawal.withdrawalFinishedCond;
+ await original.call(Op.HintNetworkAvailability, {
+ isNetworkAvailable: false,
+ });
+ const { pursePub, transactionId } = await original.call(
+ Op.InitiatePeerPushDebit,
+ {
+ exchangeBaseUrl: exchange.baseUrl,
+ partialContractTerms: {
+ summary: "different restored contribution",
+ amount: "TESTKUDOS:1",
+ },
+ },
+ );
+ await original.call(Op.SuspendTransaction, { transactionId });
+ await original.call(Op.HintNetworkAvailability, { isNetworkAvailable: true });
+ await original.call(Op.TestingWaitRefreshesFinal, {});
+ const dump = await original.call(Op.ExportDb, {});
+ const db = await (dump.databases ? makeIdbRunner() : makeSqliteRunner());
+ try {
+ await db.importDatabase(dump, async () => {});
+ await db.runReadWriteTx(async (tx) => {
+ const rec = await tx.getPeerPushDebit(pursePub);
+ if (!rec?.coinSel) throw Error("missing original selection");
+ rec.coinSel.contributions[0] = "TESTKUDOS:0.5";
+ await tx.upsertPeerPushDebit(rec);
+ });
+ await copy.call(Op.ImportDb, { dump: await db.exportDatabase() });
+ } finally {
+ await db.close();
+ }
+ await original.call(Op.ResumeTransaction, { transactionId });
+ await readyUri(original, transactionId);
+ await original.call(Op.SuspendTransaction, { transactionId });
+ // The unchanged snapshot can recover from the same purse using its matching coin history.
+ const { walletClient: matching } = await createWalletDaemonWithClient(t, {
+ name: "matching",
+ });
+ await matching.call(Op.ImportDb, { dump });
+ await matching.call(Op.ResumeTransaction, { transactionId });
+ await readyUri(matching, transactionId);
+ // Only the conflicting copy should claim the eventual refund.
+ await matching.call(Op.SuspendTransaction, { transactionId });
+ await copy.call(Op.ResumeTransaction, { transactionId });
+ await copy.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Failed },
+ });
+ const failed = await copy.call(Op.GetTransactionById, { transactionId });
+ t.assertDeepEqual(
+ failed.failReason?.code,
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ );
+ await copy.call(Op.TestingWaitRefreshesFinal, {});
+ t.assertAmountEquals(
+ (await copy.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:1",
+ );
+}
+runPeerPushConflictingHistoryTest.suites = ["wallet"];
diff --git a/packages/taler-harness/src/integrationtests/test-peer-repair.ts b/packages/taler-harness/src/integrationtests/test-peer-repair.ts
@@ -274,6 +274,13 @@ export async function runPeerRepairTest(t: GlobalTestState) {
transactionId: initResp2.transactionId,
txState: { major: TransactionMajorState.Done },
});
+ await wallet1.call(WalletApiOperation.TestingWaitRefreshesFinal, {});
+ const settled = await wallet1.call(WalletApiOperation.GetTransactionById, {
+ transactionId: initResp2.transactionId,
+ });
+ t.assertAmountEquals(settled.amountRaw, "TESTKUDOS:3");
+ t.assertAmountEquals(settled.amountEffective, "TESTKUDOS:3.15");
+ t.assertAmountEquals(settled.amountEffectiveFinal!, "TESTKUDOS:7.15");
}
runPeerRepairTest.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
@@ -51,7 +51,7 @@ export async function readyUri(
return tx.talerUri;
}
-export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
+async function testPeerResidual(t: GlobalTestState, kind: "push" | "pull") {
const one = makeLargeCoinTestConfig()[0];
const {
walletClient: original,
@@ -62,6 +62,9 @@ export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
[one, { ...one, name: "two", value: "TESTKUDOS:2" }],
{
faultInjection: true,
+ // A two-unit replacement can fund this existing purse, but cannot create one.
+ exchangeConfig:
+ kind === "push" ? { overridePurseFee: "TESTKUDOS:3" } : undefined,
},
);
const w = await withdrawViaBankV4(t, {
@@ -89,10 +92,24 @@ export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
const residualMeltAccepted = openPromise<void>();
const releaseMelt = openPromise<void>();
const recoverySeeds = new Set<string>();
+ const repairSubmissions: { endpoint: string; coinPubs: string[] }[] = [];
exchange.faultProxy.addFault({
async modifyRequest(req) {
const path = new URL(req.requestUrl).pathname;
if (
+ kind === "push" &&
+ rejected &&
+ req.method === "POST" &&
+ /\/(create|deposit)$/.test(path)
+ ) {
+ repairSubmissions.push({
+ endpoint: path.split("/").pop()!,
+ coinPubs: JSON.parse(req.requestBody!.toString()).deposits.map(
+ (d: { coin_pub: string }) => d.coin_pub,
+ ),
+ });
+ }
+ if (
!firstBatchAccepted ||
stale ||
req.method !== "POST" ||
@@ -147,19 +164,30 @@ export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
),
),
};
- 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,
- });
+ let debit: TransactionIdStr;
+ let credit: TransactionIdStr;
+ if (kind === "push") {
+ debit = (
+ await sender.walletClient.call(Op.InitiatePeerPushDebit, {
+ partialContractTerms,
+ exchangeBaseUrl: exchange.baseUrl,
+ })
+ ).transactionId;
+ } else {
+ credit = (
+ await recipient.call(Op.InitiatePeerPullCredit, {
+ partialContractTerms,
+ exchangeBaseUrl: exchange.baseUrl,
+ })
+ ).transactionId;
+ const talerUri = await readyUri(recipient, credit);
+ 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;
@@ -178,8 +206,19 @@ export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
amount: "TESTKUDOS:2",
});
await topup.withdrawalFinishedCond;
+ if (kind === "push") {
+ const talerUri = await readyUri(sender.walletClient, debit);
+ t.assertDeepEqual(
+ repairSubmissions.map((s) => [s.endpoint, s.coinPubs.length]),
+ [["deposit", 1]],
+ );
+ t.assertTrue(!repairSubmissions[0].coinPubs.includes(stale!));
+ credit = (await recipient.call(Op.PreparePeerPushCredit, { talerUri }))
+ .transactionId;
+ await recipient.call(Op.ConfirmPeerPushCredit, { transactionId: credit });
+ }
await recipient.call(Op.TestingWaitTransactionState, {
- transactionId: credit,
+ transactionId: credit!,
txState: { major: Major.Done },
});
await sender.walletClient.call(Op.TestingWaitTransactionState, {
@@ -201,5 +240,149 @@ export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
t.assertAmountEquals(settled.amountEffectiveFinal!, "TESTKUDOS:131");
t.assertDeepEqual(recoverySeeds.size, 1);
}
-runPeerPullSpentCoinTest.suites = ["wallet"];
-runPeerPullSpentCoinTest.timeoutMs = 120000;
+export async function runPeerPushSpentCoinTest(t: GlobalTestState) {
+ await testPeerResidual(t, "push");
+}
+export async function runPeerPullSpentCoinTest(t: GlobalTestState) {
+ await testPeerResidual(t, "pull");
+}
+runPeerPushSpentCoinTest.suites = runPeerPullSpentCoinTest.suites = ["wallet"];
+runPeerPushSpentCoinTest.timeoutMs =
+ runPeerPullSpentCoinTest.timeoutMs = 120000;
+
+export async function runPeerSpentCoinHistoryTest(t: GlobalTestState) {
+ const [one] = makeLargeCoinTestConfig();
+ const {
+ walletClient: sender,
+ bank,
+ faultyExchange: exchange,
+ } = await createSimpleTestkudosEnvironmentV3(
+ t,
+ [one, { ...one, name: "two", value: "TESTKUDOS:2" }],
+ { faultInjection: true },
+ );
+ const withdrawal = await withdrawViaBankV4(t, {
+ walletClient: sender,
+ bank,
+ exchange,
+ amount: "TESTKUDOS:2",
+ });
+ await withdrawal.withdrawalFinishedCond;
+ const [coin] = (await sender.call(Op.DumpCoins, {})).coins;
+ t.assertDeepEqual(coin.denomValue, "TESTKUDOS:2");
+ const { walletClient: recipient } = await createWalletDaemonWithClient(t, {
+ name: "recipient",
+ });
+ const revealing = openPromise<void>();
+ const releaseReveal = openPromise<void>();
+ const pushSubmissions: string[] = [];
+ const pullSubmissions: string[] = [];
+ let pushHistoryRead = false;
+ let pullCoinUnknown = false;
+ exchange.faultProxy.addFault({
+ async modifyRequest(req) {
+ const path = new URL(req.requestUrl).pathname;
+ if (path === "/reveal-melt") {
+ revealing.resolve();
+ await releaseReveal.promise;
+ return;
+ }
+ if (
+ req.method !== "POST" ||
+ !/^\/purses\/[^/]+\/(create|deposit)$/.test(path)
+ )
+ return;
+ const [submitted] = JSON.parse(req.requestBody!.toString()).deposits;
+ if (path.endsWith("/create")) {
+ pushSubmissions.push(submitted.coin_pub);
+ if (pushSubmissions.length > 1) return;
+ // The coin now has one unit of confirmed change and one for the purse.
+ await revealing.promise;
+ } else {
+ pullSubmissions.push(submitted.coin_pub);
+ }
+ req.dropRequest = true;
+ req.substituteResponseStatusCode = 409;
+ req.substituteResponseHeaders = { "content-type": "application/json" };
+ req.substituteResponseBody = Buffer.from(
+ JSON.stringify({
+ code: TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS,
+ coin_pub: submitted.coin_pub,
+ hint: "insufficient funds",
+ }),
+ );
+ },
+ async modifyResponse(resp) {
+ const path = new URL(resp.request.requestUrl).pathname;
+ if (
+ path === `/coins/${coin.coinPub}/history` &&
+ pushSubmissions.length === 1 &&
+ resp.statusCode === 200
+ ) {
+ t.assertAmountEquals(
+ JSON.parse(resp.responseBody!.toString()).balance,
+ "TESTKUDOS:1",
+ );
+ pushHistoryRead = true;
+ }
+ if (
+ path === `/coins/${pullSubmissions[0]}/history` &&
+ resp.statusCode === 404
+ ) {
+ t.assertDeepEqual(
+ JSON.parse(resp.responseBody!.toString()).code,
+ TalerErrorCode.EXCHANGE_GENERIC_COIN_UNKNOWN,
+ );
+ pullCoinUnknown = true;
+ }
+ },
+ });
+ const request = {
+ exchangeBaseUrl: exchange.baseUrl,
+ partialContractTerms: {
+ purse_expiration: AbsoluteTime.toProtocolTimestamp(
+ AbsoluteTime.addDuration(
+ AbsoluteTime.now(),
+ Duration.fromSpec({ minutes: 10 }),
+ ),
+ ),
+ summary: "check rejected coin history",
+ amount: "TESTKUDOS:1" as const,
+ },
+ };
+ try {
+ const push = await sender.call(Op.InitiatePeerPushDebit, request);
+ await readyUri(sender, push.transactionId);
+ t.assertTrue(pushHistoryRead);
+ t.assertDeepEqual(pushSubmissions, [coin.coinPub, coin.coinPub]);
+ } finally {
+ releaseReveal.resolve();
+ }
+ await sender.call(Op.TestingWaitRefreshesFinal, {});
+
+ // The new change coin has never been spent. The exchange really does
+ // return COIN_UNKNOWN when the wallet checks the injected rejection.
+ const invoice = await recipient.call(Op.InitiatePeerPullCredit, request);
+ const talerUri = await readyUri(recipient, invoice.transactionId);
+ const { transactionId } = await sender.call(Op.PreparePeerPullDebit, {
+ talerUri,
+ });
+ await sender.call(Op.ConfirmPeerPullDebit, { transactionId });
+ await sender.call(Op.TestingWaitTransactionState, {
+ transactionId,
+ txState: { major: Major.Failed },
+ });
+ await sender.call(Op.TestingWaitRefreshesFinal, {});
+ const failed = await sender.call(Op.GetTransactionById, { transactionId });
+ t.assertDeepEqual(
+ failed.failReason?.code,
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ );
+ t.assertTrue(pullCoinUnknown);
+ t.assertDeepEqual(pullSubmissions.length, 1);
+ t.assertAmountEquals(
+ (await sender.call(Op.GetBalances, {})).balances[0].available,
+ "TESTKUDOS:1",
+ );
+}
+runPeerSpentCoinHistoryTest.suites = ["wallet"];
diff --git a/packages/taler-harness/src/integrationtests/testrunner.ts b/packages/taler-harness/src/integrationtests/testrunner.ts
@@ -189,9 +189,21 @@ import {
} from "./test-peer-pull-recovery.js";
import {
runPeerPullSpentCoinTest,
+ runPeerPushSpentCoinTest,
+ runPeerSpentCoinHistoryTest,
} from "./test-peer-spent-coin.js";
import { runPeerPullTest } from "./test-peer-pull.js";
import { runPeerPushLargeTest } from "./test-peer-push-large.js";
+import {
+ runPeerSpentCoinSuspendedChangeTest,
+ runPeerPushRestoredPurseTest,
+ runPeerPushRefundedDuringRepairTest,
+ runPeerPushConflictingHistoryTest,
+} from "./test-peer-push-recovery.js";
+import {
+ runPeerPushBatchProofTest,
+ runPeerPushPartialFundingTest,
+} from "./test-peer-push-funding.js";
import { runPeerPushTest } from "./test-peer-push.js";
import { runPeerRepairTest } from "./test-peer-repair.js";
import { runPreparedTransferTest } from "./test-prepared-transfer.js";
@@ -415,6 +427,8 @@ const allTests: TestMainFunction[] = [
runPeerPendingChangeAbortTest,
runPeerUnmeltedChangeAbortTest,
runPeerPullSpentCoinTest,
+ runPeerPushSpentCoinTest,
+ runPeerSpentCoinHistoryTest,
withWalletDbBackend(runPeerPullRecordedDepositRepairTest, "default"),
withWalletDbBackend(runPeerPullRecordedDepositRepairTest, "indexeddb"),
runPeerPullReplayedBatchTest,
@@ -423,6 +437,14 @@ const allTests: TestMainFunction[] = [
runPeerAbortBeforeCreateTest,
runTransactionFinalAmountsTest,
runPeerPullDebitPurseGoneTest,
+ runPeerSpentCoinSuspendedChangeTest,
+ runPeerPushRestoredPurseTest,
+ runPeerPushRefundedDuringRepairTest,
+ runPeerPushConflictingHistoryTest,
+ withWalletDbBackend(runPeerPushBatchProofTest, "default"),
+ withWalletDbBackend(runPeerPushBatchProofTest, "indexeddb"),
+ withWalletDbBackend(runPeerPushPartialFundingTest, "default"),
+ withWalletDbBackend(runPeerPushPartialFundingTest, "indexeddb"),
withWalletDbBackend(runPeerPullTest, "default"),
withWalletDbBackend(runPeerPullTest, "indexeddb"),
withWalletDbBackend(runPeerPushTest, "default"),
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -2572,7 +2572,17 @@ export interface PurseDepositSelection {
}[];
}
-export type DbPeerPushPaymentCoinSelection = PurseDepositSelection;
+export interface DbPeerPushPaymentCoinSelection extends PurseDepositSelection {
+ /**
+ * End of the last staged batch in coinPubs/contributions. The leading
+ * knownDepositCount coins have been verified in coin history and their net
+ * value is balanceAtSelection. Coins between the two counts may be in flight.
+ * Older selections have no submittedCoinCount and must be reconciled first.
+ */
+ submittedCoinCount?: number;
+ /** Retained contributions need a replacement before another purse submission. */
+ needsRepair?: boolean;
+}
export interface PeerPullPaymentCoinSelection extends PurseDepositSelection {
/** Only confirmed or history-recorded deposits remain; select fresh funding for the remainder. */
diff --git a/packages/taler-wallet-core/src/pay-peer-push-debit.ts b/packages/taler-wallet-core/src/pay-peer-push-debit.ts
@@ -21,10 +21,10 @@ import {
CheckPeerPushDebitOkResponse,
CheckPeerPushDebitRequest,
CheckPeerPushDebitResponse,
- CoinRefreshRequest,
ContractTermsUtil,
Duration,
- ExchangePurseDeposits,
+ PurseDeposit,
+ ExchangePurseStatus,
HostPortPath,
HttpStatusCode,
InitiatePeerPushDebitRequest,
@@ -65,12 +65,7 @@ import {
stringToBytes,
throwUnexpectedResponse,
} from "@gnu-taler/taler-util";
-import {
- PreviousPayCoins,
- coinsAddedByRepair,
- selectPeerCoins,
- selectPeerCoinsInTx,
-} from "./coinSelection.js";
+import { selectPeerCoins, selectPeerCoinsInTx } from "./coinSelection.js";
import {
PendingTaskType,
RecordHandle,
@@ -81,8 +76,10 @@ import {
getGenericRecordHandle,
spendCoins,
} from "./common.js";
+import { SpendCoinDetails } from "./crypto/cryptoImplementation.js";
import { EncryptContractRequest } from "./crypto/cryptoTypes.js";
import {
+ DbPeerPushPaymentCoinSelection,
PeerPushDebitStatus,
WalletPeerPushDebit,
timestampPreciseFromDb,
@@ -108,12 +105,14 @@ import {
getTotalPeerPaymentCostInTx,
isPurseGoneByExpiration,
isPurseMerged,
+ netPurseDeposits,
queryCoinInfosForSelection,
requirePurseExpirationWithinLimit,
} from "./pay-peer-common.js";
import { runWithMaybeProgressContext } from "./progress.js";
import { createRefreshGroup } from "./refresh.js";
import {
+ BalanceEffect,
constructTransactionIdentifier,
isUnsuccessfulTransaction,
} from "./transactions.js";
@@ -123,12 +122,23 @@ import {
walletExchangeClient,
} from "./wallet.js";
import { updateWithdrawalDenomsForCurrency } from "./withdraw.js";
-import { reconcilePurseDeposits } from "./purse-deposit-reconciliation.js";
+import {
+ inspectPurseCoinHistories,
+ inspectPurseFunding,
+ applyPurseFundingInTx,
+ observedPurseCoinPubs,
+ purseSelectionCoins,
+ reconcilePurseDeposits,
+ samePurseSelection,
+ resolvePurseDepositConflict,
+ SubmittedPurseCoin,
+} from "./purse-deposit-reconciliation.js";
const logger = new Logger("pay-peer-push-debit.ts");
export class PeerPushDebitTransactionContext implements TransactionContext {
readonly transactionId: TransactionIdStr;
+ readonly matchesFunding = samePushFunding;
readonly taskId: TaskIdStr;
constructor(
@@ -264,6 +274,16 @@ export class PeerPushDebitTransactionContext implements TransactionContext {
await h.update(undefined, "delete");
}
+ async handleGoneDuringCreation(): Promise<TaskRunResult> {
+ await this.wex.runWalletDbTx(async (tx) => {
+ const [rec, h] = await this.getRecordHandle(tx);
+ if (rec?.status !== PeerPushDebitStatus.PendingCreatePurse) return;
+ rec.status = purseGoneStatus(rec);
+ await h.update(rec, "create-purse-gone");
+ });
+ return TaskRunResult.progress();
+ }
+
async userSuspendTransaction(): Promise<void> {
await this.wex.runWalletDbTx(async (tx) => {
const [rec, h] = await this.getRecordHandle(tx);
@@ -399,11 +419,15 @@ export class PeerPushDebitTransactionContext implements TransactionContext {
async failTransaction(
fromSt: PeerPushDebitStatus,
reason?: TalerErrorDetail,
+ expectedFunding?: WalletPeerPushDebit,
): Promise<void> {
const { wex } = this;
await wex.runWalletDbTx(async (tx) => {
const [rec, h] = await this.getRecordHandle(tx);
- if (rec?.status != fromSt) {
+ if (
+ rec?.status != fromSt ||
+ (expectedFunding && !samePushFunding(rec, expectedFunding))
+ ) {
return;
}
rec.failReason = reason;
@@ -706,99 +730,34 @@ export function requirePositivePeerPushDebitAmount(amount: AmountJson): void {
}
}
-async function handlePurseCreationConflict(
- wex: WalletExecutionContext,
+async function handlePushDepositConflict(
+ ctx: PeerPushDebitTransactionContext,
peerPushInitiation: WalletPeerPushDebit,
conflict: PurseConflict,
+ batch: readonly SubmittedPurseCoin[],
): Promise<TaskRunResult> {
- const pursePub = peerPushInitiation.pursePub;
- const ctx = new PeerPushDebitTransactionContext(wex, pursePub);
- if (conflict.code !== TalerErrorCode.EXCHANGE_GENERIC_INSUFFICIENT_FUNDS) {
- await ctx.failTransaction(peerPushInitiation.status, { ...conflict });
- return TaskRunResult.finished();
- }
-
- const brokenCoinPub = conflict.coin_pub;
- logger.trace(`excluded broken coin pub=${brokenCoinPub}`);
-
- const instructedAmount = Amounts.parseOrThrow(peerPushInitiation.amount);
- const currency = instructedAmount.currency;
- const sel = peerPushInitiation.coinSel;
- const exchangeBaseUrl = peerPushInitiation.exchangeBaseUrl;
-
- checkDbInvariant(
- !!sel,
- `no coin selected for peer push initiation ${peerPushInitiation.pursePub}`,
+ const { wex } = ctx;
+ const resolution = await resolvePurseDepositConflict(
+ ctx,
+ peerPushInitiation,
+ conflict,
+ batch,
);
-
- const repair: PreviousPayCoins = [];
-
- for (let i = 0; i < sel.coinPubs.length; i++) {
- if (sel.coinPubs[i] != brokenCoinPub) {
- repair.push({
- coinPub: sel.coinPubs[i],
- contribution: Amounts.parseOrThrow(sel.contributions[i]),
- });
- }
- }
-
- // FIXME: We don't handle the case where we would
- // have sufficient funds at another exchange,
- // but not at the one selected first. Tricky!
- const coinSelRes = await selectPeerCoins(wex, {
- instructedAmount,
- restrictScope: {
- type: ScopeType.Exchange,
- currency,
- url: exchangeBaseUrl,
- },
- repair,
- feesCoveredByCounterparty: false,
- });
-
- switch (coinSelRes.type) {
- case "failure":
- throw Error(
- "insufficient balance to re-select coins to repair double spending",
- );
- case "success":
- break;
- default:
- assertUnreachable(coinSelRes);
+ if (resolution.type === "retry") return resolution.result;
+ if (resolution.type === "failure") {
+ await ctx.failTransaction(
+ peerPushInitiation.status,
+ resolution.reason,
+ peerPushInitiation,
+ );
+ return TaskRunResult.progress();
}
-
- const totalAmount = await getTotalPeerPaymentCost(
- ctx.wex,
- coinSelRes.result.coins,
- );
-
- await ctx.wex.runWalletDbTx(async (tx) => {
+ await wex.runWalletDbTx(async (tx) => {
const [rec, h] = await ctx.getRecordHandle(tx);
- if (!rec) {
- return;
- }
- switch (rec.status) {
- case PeerPushDebitStatus.PendingCreatePurse:
- case PeerPushDebitStatus.SuspendedCreatePurse: {
- const sel = coinSelRes.result;
- rec.coinSel = {
- coinPubs: sel.coins.map((x) => x.coinPub),
- contributions: sel.coins.map((x) => x.contribution),
- };
- // The replacement coins come with their own fees.
- rec.totalCost = Amounts.stringify(totalAmount);
- // 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, sel.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.PayPeerPush,
- });
- await h.update(rec, "purse-conflict-repair");
- }
- }
+ if (!rec?.coinSel || !samePushFunding(rec, peerPushInitiation)) return;
+ // Reconcile this allocation along with the rest, against a fresh purse status.
+ rec.coinSel.needsRepair = true;
+ await h.update(rec, "purse-conflict");
});
return TaskRunResult.progress();
}
@@ -846,301 +805,409 @@ function peerPushDebitExpired(rec: WalletPeerPushDebit): boolean {
return isPurseGoneByExpiration(timestampProtocolFromDb(rec.purseExpiration));
}
-async function processPeerPushDebitCreateReserve(
- wex: WalletExecutionContext,
- peerPushInitiation: WalletPeerPushDebit,
-): Promise<TaskRunResult> {
- const { pursePub, purseExpiration, contractTermsHash, exchangeBaseUrl } =
- peerPushInitiation;
- const ctx = new PeerPushDebitTransactionContext(wex, pursePub);
+function samePushFunding(
+ current: WalletPeerPushDebit,
+ expected: WalletPeerPushDebit,
+): boolean {
+ const sel = current.coinSel;
+ const previous = expected.coinSel;
+ return (
+ current.status === expected.status &&
+ samePurseSelection(sel, previous) &&
+ sel?.knownDepositCount === previous?.knownDepositCount &&
+ sel?.submittedCoinCount === previous?.submittedCoinCount &&
+ sel?.balanceAtSelection === previous?.balanceAtSelection &&
+ sel?.needsRepair === previous?.needsRepair
+ );
+}
- logger.trace(`processing ${ctx.transactionId} pending(create-reserve)`);
+/** A history scan interrupted before its checkpoint may have seen later deposits. */
+function hasUnconfirmedPushDeposit(
+ selection: DbPeerPushPaymentCoinSelection,
+ start: number,
+): boolean {
+ const seen = observedPurseCoinPubs(selection);
+ return selection.coinPubs.some((pub, i) => i >= start && seen.has(pub));
+}
- if (peerPushDebitExpired(peerPushInitiation)) {
- await beginPeerPushDebitExpirationCleanup(
- wex,
- peerPushInitiation,
- "create-purse-expired",
+async function selectPeerPushDebitFunding(
+ ctx: PeerPushDebitTransactionContext,
+ payment: WalletPeerPushDebit,
+ purse: ExchangePurseStatus | undefined,
+ known = 0,
+): Promise<TaskRunResult> {
+ const { wex } = ctx;
+ const { exchangeBaseUrl } = payment;
+ const inspected = await inspectPurseFunding(ctx, payment, known);
+ if (inspected.type === "unresolved") {
+ return TaskRunResult.error(
+ makeErrorDetail(
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ {},
+ "A previously observed deposit is missing or refunded while the purse still appears active",
+ ),
+ );
+ }
+ if (inspected.type === "conflict") {
+ await ctx.failTransaction(
+ payment.status,
+ makeErrorDetail(
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ {},
+ "Purse repair found conflicting deposit histories",
+ ),
+ payment,
);
return TaskRunResult.progress();
}
-
- const contractTermsRecord = await wex.runWalletDbTx(async (tx) => {
- return tx.getContractTerms(contractTermsHash);
- });
-
- if (!contractTermsRecord) {
- throw Error(
- `db invariant failed, contract terms for ${ctx.transactionId} missing`,
+ const balance = purse?.balance ?? Amounts.zeroOfAmount(payment.amount);
+ const localComparedToPurse = Amounts.cmp(inspected.depositedAmount, balance);
+ if (localComparedToPurse > 0) return TaskRunResult.backoff();
+ const remainder = Amounts.sub(payment.amount, balance).amount;
+ const funded = Amounts.isZero(remainder);
+ // Funding a gap left by another copy would still leave this wallet without
+ // the evidence it needs to share the purse.
+ if (
+ (localComparedToPurse < 0 || (purse && isPurseMerged(purse))) &&
+ Amounts.cmp(inspected.depositedAmount, payment.amount) < 0
+ ) {
+ return TaskRunResult.error(
+ makeErrorDetail(
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ {},
+ `Verified local deposits total ${Amounts.stringify(inspected.depositedAmount)} for a purse with balance ${Amounts.stringify(balance)} and target ${payment.amount}`,
+ ),
);
}
+ return wex.runWalletDbTx(async (tx) => {
+ const [rec, h] = await ctx.getRecordHandle(tx);
+ if (!rec || !samePushFunding(rec, payment) || peerPushDebitExpired(rec)) {
+ return TaskRunResult.progress();
+ }
+ if (rec.coinSel) {
+ const deposited = new Set(
+ inspected.inputs
+ .filter((i) => i.disposition === "deposited")
+ .map((i) => i.coin.coinPub),
+ );
+ const seen = observedPurseCoinPubs(rec.coinSel);
+ if (
+ rec.coinSel.coinPubs.some((pub) => seen.has(pub) && !deposited.has(pub))
+ ) {
+ // Another history read observed this allocation after our inspection.
+ return TaskRunResult.progress();
+ }
+ }
+ const {
+ selection: next,
+ totalCost,
+ insufficient,
+ refreshGroupId,
+ } = await applyPurseFundingInTx(wex, tx, {
+ inputs: inspected.inputs,
+ previousSelection: rec.coinSel,
+ balanceAtSelection: Amounts.stringify(inspected.depositedAmount),
+ remainder,
+ exchangeBaseUrl,
+ transactionId: ctx.transactionId,
+ reason: RefreshReason.PayPeerPush,
+ });
+ if (refreshGroupId) rec.abortRefreshGroupId = refreshGroupId;
+ rec.coinSel = { ...next, submittedCoinCount: next.knownDepositCount };
+ rec.totalCost = totalCost;
+ if (funded)
+ rec.status =
+ purse && isPurseMerged(purse)
+ ? PeerPushDebitStatus.Done
+ : PeerPushDebitStatus.PendingReady;
+ await h.update(rec, funded ? "purse-already-funded" : "select-coins");
+ return insufficient
+ ? TaskRunResult.error(
+ makeErrorDetail(
+ TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
+ { insufficientBalanceDetails: insufficient },
+ ),
+ )
+ : TaskRunResult.progress();
+ });
+}
- const instructedAmount = Amounts.parseOrThrow(peerPushInitiation.amount);
- const currency = instructedAmount.currency;
+const maxPushDepositBatchSize = 64;
- if (!peerPushInitiation.coinSel) {
- const coinSelRes = await selectPeerCoins(wex, {
- instructedAmount,
- restrictScope: {
- type: ScopeType.Exchange,
- currency,
- url: exchangeBaseUrl,
- },
- feesCoveredByCounterparty: false,
- });
+async function processPeerPushDebitCreatePurse(
+ wex: WalletExecutionContext,
+ peerPushInitiation: WalletPeerPushDebit,
+): Promise<TaskRunResult> {
+ const { pursePub, exchangeBaseUrl } = peerPushInitiation;
+ const ctx = new PeerPushDebitTransactionContext(wex, pursePub);
- switch (coinSelRes.type) {
- case "failure":
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
- {
- insufficientBalanceDetails: coinSelRes.insufficientBalanceDetails,
- },
- );
- case "success":
- break;
- default:
- assertUnreachable(coinSelRes);
- }
+ logger.trace(`processing ${ctx.transactionId} pending(create-purse)`);
- return await wex.runWalletDbTx(async (tx) => {
- const [rec, h] = await ctx.getRecordHandle(tx);
- if (!rec) {
- return TaskRunResult.backoff();
- }
- if (rec.coinSel != null) {
- return TaskRunResult.backoff();
- }
- rec.coinSel = {
- coinPubs: coinSelRes.result.coins.map((x) => x.coinPub),
- contributions: coinSelRes.result.coins.map((x) => x.contribution),
- };
- // FIXME: Instead of directly doing a spendCoin here,
- // we might want to mark the coins as used and spend them
- // after we've been able to create the purse.
- 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.PayPeerPush,
+ // A saved selection can predate deposits from another copy of the wallet.
+ const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex);
+ const status = await exchangeClient.getPurseStatusAtMerge(pursePub);
+ let purse: ExchangePurseStatus | undefined;
+ switch (status.case) {
+ case "ok":
+ await requireValidExchangePurseStatus(wex, exchangeBaseUrl, status.body);
+ purse = status.body;
+ break;
+ case HttpStatusCode.Gone:
+ return ctx.handleGoneDuringCreation();
+ case HttpStatusCode.NotFound:
+ if (status.detail?.code !== TalerErrorCode.EXCHANGE_GENERIC_PURSE_UNKNOWN)
+ throwUnexpectedResponse(status);
+ break;
+ default:
+ assertUnreachable(status);
+ }
+ const selection = peerPushInitiation.coinSel;
+ const purseAmount = peerPushInitiation.amount;
+ const known = selection?.knownDepositCount;
+ const submitted = selection?.submittedCoinCount;
+ const localAmount = selection?.balanceAtSelection;
+ if (
+ !selection ||
+ known === undefined ||
+ submitted === undefined ||
+ localAmount === undefined
+ ) {
+ // Older wallets could have sent any of their selected coins.
+ return selectPeerPushDebitFunding(ctx, peerPushInitiation, purse);
+ }
+ checkDbInvariant(
+ Number.isSafeInteger(known) &&
+ Number.isSafeInteger(submitted) &&
+ 0 <= known &&
+ known <= submitted &&
+ submitted - known <= maxPushDepositBatchSize &&
+ submitted <= selection.coinPubs.length &&
+ selection.contributions.length === selection.coinPubs.length &&
+ new Set(selection.coinPubs).size === selection.coinPubs.length,
+ "invalid push purse funding checkpoint",
+ );
+ const balance = purse?.balance ?? Amounts.zeroOfAmount(purseAmount);
+ if (
+ selection.needsRepair ||
+ (purse && isPurseMerged(purse)) ||
+ Amounts.cmp(balance, purseAmount) >= 0 ||
+ known === selection.coinPubs.length ||
+ hasUnconfirmedPushDeposit(selection, submitted)
+ ) {
+ return selectPeerPushDebitFunding(ctx, peerPushInitiation, purse, known);
+ }
+ const end =
+ submitted > known
+ ? submitted
+ : Math.min(known + maxPushDepositBatchSize, selection.coinPubs.length);
+ const batchSelection = {
+ coinPubs: selection.coinPubs.slice(known, end),
+ contributions: selection.contributions.slice(known, end),
+ };
+ if (submitted > known) {
+ // A lost response and a successful receipt both require the same coin evidence.
+ const inspected = await inspectPurseCoinHistories(
+ ctx,
+ peerPushInitiation,
+ purseSelectionCoins(batchSelection),
+ );
+ if (inspected.every((c) => c.authorization === "committed")) {
+ const credit = netPurseDeposits(
+ Amounts.currencyOf(purseAmount),
+ inspected,
+ );
+ await wex.runWalletDbTx(async (tx) => {
+ const [current, handle] = await ctx.getRecordHandle(tx);
+ if (!current?.coinSel || !samePushFunding(current, peerPushInitiation))
+ return;
+ current.coinSel.knownDepositCount = submitted;
+ current.coinSel.balanceAtSelection = Amounts.stringify(
+ Amounts.add(localAmount, credit).amount,
+ );
+ await handle.update(
+ current,
+ "confirm-purse-deposits",
+ BalanceEffect.None,
+ );
});
- await h.update(rec, "select-coins");
return TaskRunResult.progress();
- });
+ }
+ const seen = observedPurseCoinPubs(selection);
+ if (
+ inspected.some(
+ (c) =>
+ c.authorization !== "absent" ||
+ !c.canUseAllocation ||
+ seen.has(c.coinPub),
+ )
+ ) {
+ // The exchange may have accepted only part of the batch, or another
+ // payment may have spent one of its coins while the reply was lost.
+ return selectPeerPushDebitFunding(ctx, peerPushInitiation, purse, known);
+ }
}
+ if (Amounts.cmp(balance, localAmount) !== 0)
+ return selectPeerPushDebitFunding(ctx, peerPushInitiation, purse, known);
+ const batchCoins = await queryCoinInfosForSelection(wex, batchSelection);
+ const net = netPurseDeposits(Amounts.currencyOf(purseAmount), batchCoins);
+ if (
+ Amounts.isZero(net) ||
+ Amounts.cmp(net, Amounts.sub(purseAmount, balance).amount) > 0
+ )
+ return selectPeerPushDebitFunding(ctx, peerPushInitiation, purse, known);
+
+ return submitPeerPushDebitBatch(
+ ctx,
+ peerPushInitiation,
+ end,
+ batchCoins,
+ !purse,
+ );
+}
- const purseAmount = peerPushInitiation.amount;
-
- const purseSigResp = await wex.cryptoApi.signPurseCreation({
+async function makePushPurseCreateRequest(
+ ctx: PeerPushDebitTransactionContext,
+ payment: WalletPeerPushDebit,
+ deposits: PurseDeposit[],
+) {
+ const { wex, pursePub } = ctx;
+ const { pursePriv, mergePriv, contractTermsHash, contractPriv, contractPub } =
+ payment;
+ const terms = await wex.runWalletDbTx((tx) =>
+ tx.getContractTerms(contractTermsHash),
+ );
+ checkDbInvariant(!!terms, `contract terms for ${ctx.transactionId} missing`);
+ const purseExpiration = timestampProtocolFromDb(payment.purseExpiration);
+ const { sig } = await wex.cryptoApi.signPurseCreation({
hContractTerms: contractTermsHash,
- mergePub: peerPushInitiation.mergePub,
+ mergePub: payment.mergePub,
minAge: 0,
- purseAmount,
- purseExpiration: timestampProtocolFromDb(purseExpiration),
- pursePriv: peerPushInitiation.pursePriv,
+ purseAmount: payment.amount,
+ purseExpiration,
+ pursePriv,
});
-
- const coins = await queryCoinInfosForSelection(
- wex,
- peerPushInitiation.coinSel,
- );
-
const encryptContractRequest: EncryptContractRequest = {
- contractTerms: contractTermsRecord.contractTermsRaw,
- mergePriv: peerPushInitiation.mergePriv,
- pursePriv: peerPushInitiation.pursePriv,
- pursePub: peerPushInitiation.pursePub,
- contractPriv: peerPushInitiation.contractPriv,
- contractPub: peerPushInitiation.contractPub,
- nonce: peerPushInitiation.contractEncNonce,
+ contractTerms: terms.contractTermsRaw,
+ mergePriv,
+ pursePriv,
+ pursePub,
+ contractPriv,
+ contractPub,
+ nonce: payment.contractEncNonce,
};
-
- const econtractResp = await wex.cryptoApi.encryptContractForMerge(
+ const { econtract } = await wex.cryptoApi.encryptContractForMerge(
encryptContractRequest,
);
+ return {
+ amount: payment.amount,
+ merge_pub: payment.mergePub,
+ purse_sig: sig,
+ h_contract_terms: contractTermsHash,
+ purse_expiration: purseExpiration,
+ deposits,
+ min_age: 0,
+ econtract,
+ };
+}
- const maxBatchSize = 64;
- const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex);
+async function submitPeerPushDebitBatch(
+ ctx: PeerPushDebitTransactionContext,
+ payment: WalletPeerPushDebit,
+ end: number,
+ batchCoins: SpendCoinDetails[],
+ createPurse: boolean,
+): Promise<TaskRunResult> {
+ const { wex, pursePub } = ctx;
+ const { exchangeBaseUrl } = payment;
+ const { deposits } = await wex.cryptoApi.signPurseDeposits({
+ exchangeBaseUrl,
+ pursePub,
+ coins: batchCoins,
+ });
+ const createRequest = createPurse
+ ? await makePushPurseCreateRequest(ctx, payment, deposits)
+ : undefined;
+ await requireExchangeCoinUseConfirmedOrThrow(wex, exchangeBaseUrl);
+ // Persist exactly the authorizations about to leave the wallet. A concurrent
+ // suspend, abort or repair can invalidate the request while it is being signed.
+ const staged = await wex.runWalletDbTx(async (tx) => {
+ const [current, handle] = await ctx.getRecordHandle(tx);
+ if (!current?.coinSel || !samePushFunding(current, payment)) return;
+ if (
+ hasUnconfirmedPushDeposit(
+ current.coinSel,
+ current.coinSel.knownDepositCount ?? 0,
+ )
+ )
+ return;
+ if (peerPushDebitExpired(current)) {
+ current.status = PeerPushDebitStatus.ExpiredDeletePurse;
+ await handle.update(current, "deposit-purse-expired");
+ return;
+ }
+ if (current.coinSel.submittedCoinCount !== end) {
+ current.coinSel.submittedCoinCount = end;
+ await handle.update(current, "stage-purse-deposits", BalanceEffect.None);
+ }
+ return current;
+ });
+ if (!staged) return TaskRunResult.progress();
- for (let i = 0; i < coins.length; i += maxBatchSize) {
- if (peerPushDebitExpired(peerPushInitiation)) {
- await beginPeerPushDebitExpirationCleanup(
- wex,
- peerPushInitiation,
- "deposit-purse-expired",
- );
+ const exchangeClient = walletExchangeClient(exchangeBaseUrl, wex);
+ const confirmation = {
+ exchangeBaseUrl,
+ pursePub,
+ contractTermsHash: payment.contractTermsHash,
+ purseValueAfterFees: payment.amount,
+ purseExpiration: timestampProtocolFromDb(payment.purseExpiration),
+ };
+ // A signed aggregate can include replays. Only coin history advances the batch.
+ let rejection;
+ if (createRequest) {
+ const resp = await exchangeClient.createPurseFromDeposit(
+ pursePub,
+ createRequest,
+ );
+ if (resp.case === "ok") {
+ await requireValidExchangePurseCreateConfirmation(wex, {
+ ...confirmation,
+ response: resp.body,
+ });
return TaskRunResult.progress();
}
- const batchSize = Math.min(maxBatchSize, coins.length - i);
- const batchCoins = coins.slice(i, i + batchSize);
-
- const depositSigsResp = await wex.cryptoApi.signPurseDeposits({
- exchangeBaseUrl: peerPushInitiation.exchangeBaseUrl,
- pursePub: peerPushInitiation.pursePub,
- coins: batchCoins,
- });
-
- if (i == 0) {
- // First batch creates the purse!
-
- const reqBody = {
- // Older wallets do not have amountPurse
- amount: purseAmount,
- merge_pub: peerPushInitiation.mergePub,
- purse_sig: purseSigResp.sig,
- h_contract_terms: contractTermsHash,
- purse_expiration: timestampProtocolFromDb(purseExpiration),
- deposits: depositSigsResp.deposits,
- min_age: 0,
- econtract: econtractResp.econtract,
- };
-
- await requireExchangeCoinUseConfirmedOrThrow(wex, exchangeBaseUrl);
- const resp = await exchangeClient.createPurseFromDeposit(
- peerPushInitiation.pursePub,
- reqBody,
- );
- switch (resp.case) {
- case "ok":
- await requireValidExchangePurseCreateConfirmation(wex, {
- exchangeBaseUrl,
- pursePub: peerPushInitiation.pursePub,
- contractTermsHash,
- purseValueAfterFees: purseAmount,
- purseExpiration: timestampProtocolFromDb(purseExpiration),
- response: resp.body,
- });
- // Possibly on to the next batch.
- continue;
- case HttpStatusCode.Forbidden:
- case HttpStatusCode.NotFound:
- await ctx.failTransaction(peerPushInitiation.status, resp.detail);
- return TaskRunResult.finished();
- case HttpStatusCode.Conflict:
- return handlePurseCreationConflict(
- wex,
- peerPushInitiation,
- resp.body,
- );
- case HttpStatusCode.TooEarly:
- return TaskRunResult.backoff();
- case TalerErrorCode.EXCHANGE_PURSE_CREATE_EXPIRATION_BEFORE_NOW:
- await beginPeerPushDebitExpirationCleanup(
- wex,
- peerPushInitiation,
- "create-purse-expiration-rejected",
- );
- return TaskRunResult.progress();
- case TalerErrorCode.EXCHANGE_PURSE_CREATE_EXPIRATION_IS_NEVER:
- await ctx.failTransaction(peerPushInitiation.status, resp.detail);
- return TaskRunResult.finished();
- default:
- assertUnreachable(resp);
- }
- } else {
- const depositPayload: ExchangePurseDeposits = {
- deposits: depositSigsResp.deposits,
- };
- await requireExchangeCoinUseConfirmedOrThrow(wex, exchangeBaseUrl);
- const resp = await exchangeClient.depositIntoPurse(
- peerPushInitiation.pursePub,
- depositPayload,
- );
- switch (resp.case) {
- case "ok":
- await requireValidExchangePurseDepositConfirmation(wex, {
- exchangeBaseUrl,
- pursePub: peerPushInitiation.pursePub,
- contractTermsHash,
- purseValueAfterFees: purseAmount,
- purseExpiration: timestampProtocolFromDb(purseExpiration),
- response: resp.body,
- });
- // Possibly on to the next batch.
- continue;
- case HttpStatusCode.Gone:
- await wex.runWalletDbTx(async (tx) => {
- const [rec, h] = await ctx.getRecordHandle(tx);
- if (!rec) {
- return;
- }
- switch (rec.status) {
- case PeerPushDebitStatus.PendingCreatePurse:
- rec.status = purseGoneStatus(rec);
- break;
- default:
- // Do nothing
- return;
- }
- await h.update(rec, "deposit-purse-gone");
- });
- return TaskRunResult.progress();
- case HttpStatusCode.Conflict:
- // Handle double-spending
- return handlePurseCreationConflict(
- wex,
- peerPushInitiation,
- resp.body,
- );
- case HttpStatusCode.Forbidden:
- case HttpStatusCode.NotFound:
- await ctx.failTransaction(peerPushInitiation.status, resp.detail);
- return TaskRunResult.finished();
- default:
- assertUnreachable(resp);
- }
+ rejection = resp;
+ } else {
+ const resp = await exchangeClient.depositIntoPurse(pursePub, { deposits });
+ if (resp.case === "ok") {
+ await requireValidExchangePurseDepositConfirmation(wex, {
+ ...confirmation,
+ response: resp.body,
+ });
+ return TaskRunResult.progress();
}
+ rejection = resp;
}
-
- // All batches done!
- const resp = await exchangeClient.getPurseStatusAtDeposit(pursePub);
- switch (resp.case) {
- case "ok":
- await requireValidExchangePurseStatus(
+ switch (rejection.case) {
+ case HttpStatusCode.Conflict:
+ return handlePushDepositConflict(ctx, staged, rejection.body, batchCoins);
+ case HttpStatusCode.Gone:
+ return ctx.handleGoneDuringCreation();
+ case HttpStatusCode.TooEarly:
+ return TaskRunResult.backoff();
+ case TalerErrorCode.EXCHANGE_PURSE_CREATE_EXPIRATION_BEFORE_NOW:
+ await beginPeerPushDebitExpirationCleanup(
wex,
- peerPushInitiation.exchangeBaseUrl,
- resp.body,
+ staged,
+ "create-purse-expiration-rejected",
);
- await wex.runWalletDbTx(async (tx) => {
- const [rec, h] = await ctx.getRecordHandle(tx);
- if (!rec) {
- return;
- }
- switch (rec.status) {
- case PeerPushDebitStatus.PendingCreatePurse:
- rec.status = PeerPushDebitStatus.PendingReady;
- break;
- default:
- // Do nothing
- return;
- }
- await h.update(rec, "create-purse");
- });
- return TaskRunResult.progress();
- case HttpStatusCode.Gone:
- await wex.runWalletDbTx(async (tx) => {
- const [rec, h] = await ctx.getRecordHandle(tx);
- if (!rec) {
- return;
- }
- switch (rec.status) {
- case PeerPushDebitStatus.PendingCreatePurse:
- rec.status = purseGoneStatus(rec);
- break;
- default:
- // Do nothing
- return;
- }
- await h.update(rec, "create-purse-gone");
- });
return TaskRunResult.progress();
+ case HttpStatusCode.Forbidden:
case HttpStatusCode.NotFound:
- await ctx.failTransaction(peerPushInitiation.status, resp.detail);
- return TaskRunResult.finished();
+ case TalerErrorCode.EXCHANGE_PURSE_CREATE_EXPIRATION_IS_NEVER:
+ await ctx.failTransaction(staged.status, rejection.detail, staged);
+ return TaskRunResult.progress();
default:
- assertUnreachable(resp);
+ assertUnreachable(rejection);
}
}
@@ -1316,46 +1383,15 @@ async function processPeerPushDebitReady(
}
}
case HttpStatusCode.Gone:
- // The exchange answers the merge long-poll with "gone" only when the
- // purse expired. Nobody aborted here, so the transaction is expired
- // and not aborted, but the coins still have to come back to us.
- logger.info(`purse ${pursePub} expired, refreshing peer-push-debit`);
- await wex.runWalletDbTx(async (tx) => {
- const [rec, h] = await ctx.getRecordHandle(tx);
- if (!rec) {
- return;
- }
- if (rec.status !== PeerPushDebitStatus.PendingReady) {
- return;
- }
- const currency = Amounts.currencyOf(rec.amount);
- const coinPubs: CoinRefreshRequest[] = [];
-
- if (rec.coinSel) {
- for (let i = 0; i < rec.coinSel.coinPubs.length; i++) {
- coinPubs.push({
- amount: rec.coinSel.contributions[i],
- coinPub: rec.coinSel.coinPubs[i],
- });
- }
-
- const refresh = await createRefreshGroup(
- wex,
- tx,
- currency,
- coinPubs,
- RefreshReason.AbortPeerPushDebit,
- ctx.transactionId,
- );
-
- rec.abortRefreshGroupId = refresh.refreshGroupId;
- }
- rec.status = PeerPushDebitStatus.Expired;
- await h.update(rec, "ready-expired");
- });
- return TaskRunResult.backoff();
+ await beginPeerPushDebitExpirationCleanup(
+ wex,
+ peerPushInitiation,
+ "ready-expired",
+ );
+ return TaskRunResult.progress();
case HttpStatusCode.NotFound:
- throw Error("peer push credit disappeared");
+ await ctx.failTransaction(peerPushInitiation.status, resp.detail);
+ return TaskRunResult.progress();
default:
assertUnreachable(resp);
}
@@ -1418,7 +1454,7 @@ export async function processPeerPushDebit(
switch (peerPushInitiation.status) {
case PeerPushDebitStatus.PendingCreatePurse:
- return processPeerPushDebitCreateReserve(wex, peerPushInitiation);
+ return processPeerPushDebitCreatePurse(wex, peerPushInitiation);
case PeerPushDebitStatus.PendingReady:
return processPeerPushDebitReady(wex, peerPushInitiation);
case PeerPushDebitStatus.AbortingDeletePurse:
@@ -1659,6 +1695,9 @@ export async function initiatePeerPushDebit(
ppi.coinSel = {
coinPubs: coinSelRes.result.coins.map((x) => x.coinPub),
contributions: coinSelRes.result.coins.map((x) => x.contribution),
+ knownDepositCount: 0,
+ submittedCoinCount: 0,
+ balanceAtSelection: Amounts.stringify(Amounts.zeroOfCurrency(currency)),
};
// FIXME: Instead of directly doing a spendCoin here,
// we might want to mark the coins as used and spend them