commit 98a3a1c2ab7d6ba246df62c81cbdb0e7d4d39f9e
parent afa3675ff648d982645878e969ff36f26aff8823
Author: Florian Dold <dold@taler.net>
Date: Tue, 17 Nov 2026 19:00:09 +0100
wallet withdrawals: keep the original planchets on retry
Persist each batch before sending it. For older withdrawals, use signed
reserve history to identify accepted batches. Deduct their cost before
selecting replacement denominations.
Diffstat:
6 files changed, 1036 insertions(+), 139 deletions(-)
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -305,6 +305,8 @@ export type KycAuthTransferOptionRaw = TransferOptionRaw & {
* in the same transaction that inserts the WalletRecoupGroup.
*/
export interface WalletRecoupGroup {
+ /** Actual credited value per coin; zero also records an already spent coin. */
+ recoveredAmounts?: Record<string, AmountString>;
/** Durable reason for a permanent failure. */
failReason?: TalerErrorDetail;
@@ -648,6 +650,17 @@ export type WgInfo =
| WgInfoBankPeerPush
| WgInfoBankRecoup;
+/** Immutable request membership, persisted before a batch can reach the exchange. */
+export interface WalletWithdrawalBatch {
+ coinIndices: number[];
+ hPlanchets: string;
+ /**
+ * Complete means the exchange accepted the request, even if signatures
+ * still need storing. Unresolved blocks legacy requests with unknown membership.
+ */
+ state: "submitted" | "rejected" | "complete" | "unresolved";
+}
+
/**
* Group of withdrawal operations that need to be executed.
* (Either for a normal withdrawal or from a reward.)
@@ -656,6 +669,7 @@ export type WgInfo =
* the coin selection we want to withdraw.
*/
export interface WalletWithdrawalGroup {
+ batches?: WalletWithdrawalBatch[];
transactionAmounts?: WalletTransactionAmounts;
/**
* Unique identifier for the withdrawal group.
@@ -774,7 +788,10 @@ export interface WalletWithdrawalGroup {
/**
* Denominations selected for withdrawal.
*/
- denomsSel?: DenomSelectionState;
+ denomsSel?: DenomSelectionState & {
+ /** Legacy replacements must be reselected after replaying a recovered debit. */
+ requiresReselection?: boolean;
+ };
abortReason?: TalerErrorDetail;
failReason?: TalerErrorDetail;
@@ -1534,6 +1551,12 @@ export interface WalletBankAccount {
}
export interface WalletWithdrawCoinSource {
+ /** Original signed output batch, retained even after deleting its transaction. */
+ recoupBatch?: {
+ commitment: string;
+ coinIndex: number;
+ envelopeHashes: string[];
+ };
type: CoinSourceType.Withdraw;
/**
@@ -1562,6 +1585,12 @@ export interface WalletWithdrawCoinSource {
}
export interface WalletRefreshCoinSource {
+ /** Original signed output batch, retained even after deleting its transaction. */
+ recoupBatch?: {
+ commitment: string;
+ coinIndex: number;
+ envelopeHashes: string[];
+ };
type: CoinSourceType.Refresh;
refreshGroupId: string;
oldCoinPub: string;
@@ -1581,6 +1610,8 @@ export interface WalletRewardCoinSource {
* of the wallet database.
*/
export interface WalletCoin {
+ /** A completed recoup reconciliation; retained when its history is deleted. */
+ recoupGroupId?: string;
/**
* Where did the coin come from? Used for recouping coins.
*/
diff --git a/packages/taler-wallet-core/src/db/sqlite/schema.ts b/packages/taler-wallet-core/src/db/sqlite/schema.ts
@@ -85,7 +85,7 @@
*
* Bump this when adding a migration to {@link schemaMigrations}.
*/
-export const SQLITE_SCHEMA_VERSION = 26;
+export const SQLITE_SCHEMA_VERSION = 27;
/**
* Tables of the IndexedDB emulation, children before parents.
@@ -1536,6 +1536,15 @@ export const schemaMigrations: SchemaMigration[] = [
"ALTER TABLE exchange_details ADD COLUMN max_peer_push_expiration TEXT",
],
},
+ {
+ version: 27,
+ name: "withdrawal-batch-identities",
+ statements: [
+ "ALTER TABLE withdrawal_groups ADD COLUMN batches TEXT",
+ "ALTER TABLE recoup_groups ADD COLUMN recovered_amounts TEXT",
+ "ALTER TABLE coins ADD COLUMN recoup_group_id TEXT",
+ ],
+ },
];
/** Native tables that contain wallet records (not schema bookkeeping). */
diff --git a/packages/taler-wallet-core/src/db/sqlite/transaction.ts b/packages/taler-wallet-core/src/db/sqlite/transaction.ts
@@ -1169,6 +1169,9 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
private rowToCoin(row: ResultRow): WalletCoin {
return {
+ ...(row.recoup_group_id == null
+ ? {}
+ : { recoupGroupId: str(row.recoup_group_id) }),
coinPub: dbToCrock(row.coin_pub),
coinPriv: dbToCrock(row.coin_priv),
exchangeBaseUrl: str(row.exchange_base_url),
@@ -1206,16 +1209,17 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
async upsertCoin(coin: WalletCoin): Promise<void> {
await this.run(
- `INSERT INTO coins (
+ `INSERT INTO coins (recoup_group_id,
coin_pub, coin_priv, exchange_base_url, exchange_master_pub,
denom_pub_hash, denom_sig,
blinding_key, exchange_withdraw_values, coin_ev_hash, status, visible, max_age,
age_commitment_proof, coin_source, source_transaction_id
) VALUES (
- $pub, $priv, $url, $emp, $dph, $sig, $bk, $ewv, $ceh, $status, $visible,
+ $recoup, $pub, $priv, $url, $emp, $dph, $sig, $bk, $ewv, $ceh, $status, $visible,
$age, $acp, $source, $stid
)
ON CONFLICT(coin_pub) DO UPDATE SET
+ recoup_group_id = excluded.recoup_group_id,
coin_priv = excluded.coin_priv,
exchange_base_url = excluded.exchange_base_url,
exchange_master_pub = excluded.exchange_master_pub,
@@ -1231,6 +1235,7 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
coin_source = excluded.coin_source,
source_transaction_id = excluded.source_transaction_id`,
{
+ recoup: coin.recoupGroupId ?? null,
pub: crockToDb(coin.coinPub),
priv: crockToDb(coin.coinPriv),
url: coin.exchangeBaseUrl,
@@ -2402,6 +2407,7 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
...(row.transaction_amounts == null
? {}
: { transactionAmounts: dbToJson(row.transaction_amounts) }),
+ ...(row.batches == null ? {} : { batches: dbToJson(row.batches) }),
withdrawalGroupId: str(row.withdrawal_group_id),
...(dbToBool(row.legacy) ? { legacy: true } : undefined),
wgInfo: this.rowToWgInfo(row),
@@ -2487,7 +2493,7 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
async upsertWithdrawalGroup(rec: WalletWithdrawalGroup): Promise<void> {
const wg = this.wgInfoToCols(rec.wgInfo);
await this.run(
- `INSERT INTO withdrawal_groups (transaction_amounts,
+ `INSERT INTO withdrawal_groups (batches, transaction_amounts,
withdrawal_group_id, withdrawal_type, taler_withdraw_uri,
contract_priv, bank_info, exchange_credit_accounts,
is_foreign_account, kyc_payto_hash, kyc_access_token,
@@ -2498,13 +2504,14 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
instructed_amount, reserve_balance_amount, raw_withdrawal_amount,
effective_withdrawal_amount, denoms_sel, abort_reason, fail_reason,
legacy
- ) VALUES ($transactionAmounts,
+ ) VALUES ($batches, $transactionAmounts,
$id, $wtype, $uri, $cpriv, $binfo, $eca, $ifa, $kph, $kat, $klcs,
$klcc, $klrg, $klar, $kld, $kwd, $seed, $rpub, $rpriv, $url,
$tstart, $tfinish, $status, $age, $ia, $rba, $rwa, $ewa, $ds,
$abort, $fail, $legacy
)
ON CONFLICT(withdrawal_group_id) DO UPDATE SET
+ batches = excluded.batches,
transaction_amounts = excluded.transaction_amounts,
withdrawal_type = excluded.withdrawal_type,
taler_withdraw_uri = excluded.taler_withdraw_uri,
@@ -2537,6 +2544,7 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
fail_reason = excluded.fail_reason,
legacy = excluded.legacy`,
{
+ batches: rec.batches === undefined ? null : jsonToDb(rec.batches),
transactionAmounts:
rec.transactionAmounts === undefined
? null
@@ -5524,6 +5532,9 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
private rowToRecoupGroup(row: ResultRow): WalletRecoupGroup {
return {
+ ...(row.recovered_amounts == null
+ ? {}
+ : { recoveredAmounts: dbToJson(row.recovered_amounts) }),
...(row.fail_reason == null
? {}
: { failReason: dbToJson(row.fail_reason) }),
@@ -5566,13 +5577,14 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
async upsertRecoupGroup(rec: WalletRecoupGroup): Promise<void> {
await this.run(
- `INSERT INTO recoup_groups (
+ `INSERT INTO recoup_groups (recovered_amounts,
recoup_group_id, exchange_base_url, operation_status,
timestamp_started, timestamp_finished, coin_pubs,
recoup_finished_per_coin, failed_coin_pubs, successful_coin_pubs,
schedule_refresh_coins, fail_reason
- ) VALUES ($id, $url, $status, $started, $finished, $pubs, $fin, $failed, $success, $sched, $fail_reason)
+ ) VALUES ($amounts, $id, $url, $status, $started, $finished, $pubs, $fin, $failed, $success, $sched, $fail_reason)
ON CONFLICT(recoup_group_id) DO UPDATE SET
+ recovered_amounts = excluded.recovered_amounts,
exchange_base_url = excluded.exchange_base_url,
operation_status = excluded.operation_status,
timestamp_started = excluded.timestamp_started,
@@ -5584,6 +5596,8 @@ export class SqliteWalletTransaction implements WalletDbTransaction {
schedule_refresh_coins = excluded.schedule_refresh_coins,
fail_reason = excluded.fail_reason`,
{
+ amounts:
+ rec.recoveredAmounts == null ? null : jsonToDb(rec.recoveredAmounts),
fail_reason: rec.failReason == null ? null : jsonToDb(rec.failReason),
id: rec.recoupGroupId,
url: rec.exchangeBaseUrl,
diff --git a/packages/taler-wallet-core/src/db/testing/conformance-cases.ts b/packages/taler-wallet-core/src/db/testing/conformance-cases.ts
@@ -235,6 +235,11 @@ function makeCoin(coinPub: string): WalletCoin {
withdrawalGroupId: "wg-default",
coinIndex: 0,
reservePub: ck("rp-default"),
+ recoupBatch: {
+ commitment: ckh("batch"),
+ coinIndex: 0,
+ envelopeHashes: [ckh(`evh-${coinPub}`)],
+ },
},
};
return coin;
@@ -398,6 +403,9 @@ function makeWithdrawalGroup(withdrawalGroupId: string): WalletWithdrawalGroup {
reservePriv: ck(`rpriv-${withdrawalGroupId}`),
timestampStart: tsPrecise(1000),
status: WithdrawalGroupStatus.PendingRegisteringBank,
+ batches: [
+ { coinIndices: [0, 1], hPlanchets: ckh("batch"), state: "submitted" },
+ ],
};
return wg;
}
@@ -780,6 +788,23 @@ function makeRefundItem(
};
}
+/** Inject a failure after earlier writes have reached the actual backend. */
+function interruptBefore(
+ tx: WalletDbTransaction,
+ method: keyof WalletDbTransaction,
+) {
+ return new Proxy(tx, {
+ get(target, prop) {
+ if (prop === method)
+ return async () => {
+ throw Error("interrupted between writes");
+ };
+ const value = Reflect.get(target, prop);
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+}
+
export const conformanceCases: ConformanceCase[] = [
{
name: "permanent recoup and refund reasons survive storage and replacement",
@@ -1947,6 +1972,7 @@ export const conformanceCases: ConformanceCase[] = [
name: "coin: round trips with age commitment proof absent",
async run(t, runner) {
const coin = makeCoin("cp-1");
+ coin.recoupGroupId = "completed-recoup";
await runner.runReadWriteTx((tx) => tx.upsertCoin(coin));
const got = await runner.runReadWriteTx((tx) => tx.getCoin(ck("cp-1")));
t.ok(got, "coin should exist");
@@ -2907,6 +2933,81 @@ export const conformanceCases: ConformanceCase[] = [
// -------------------------------------------------- withdrawal groups
{
+ name: "withdrawal group: rejection and planchet error commit or roll back together",
+ async run(t, runner) {
+ const { recordWithdrawalBatchError } = await import("../../withdraw.js");
+ const group = makeWithdrawalGroup("rejected-batch");
+ const planchet = makePlanchet(
+ "rejected-coin",
+ group.withdrawalGroupId,
+ 0,
+ );
+ const error = {
+ code: TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED,
+ };
+ await runner.runReadWriteTx(async (tx) => {
+ await tx.upsertWithdrawalGroup(group);
+ await tx.upsertPlanchet(planchet);
+ });
+ try {
+ await runner.runReadWriteTx((tx) =>
+ recordWithdrawalBatchError(
+ interruptBefore(tx, "upsertPlanchet"),
+ group.withdrawalGroupId,
+ group.batches![0].hPlanchets,
+ 0,
+ error,
+ ),
+ );
+ t.fail("expected interruption");
+ } catch (e) {
+ t.equal((e as Error).message, "interrupted between writes");
+ }
+ await runner.runReadWriteTx(async (tx) => {
+ t.equal(
+ (await tx.getWithdrawalGroup(group.withdrawalGroupId))?.batches?.[0]
+ .state,
+ "submitted",
+ );
+ t.equal(
+ (await tx.getPlanchetByGroupAndIndex(group.withdrawalGroupId, 0))
+ ?.lastError,
+ undefined,
+ );
+ await recordWithdrawalBatchError(
+ tx,
+ group.withdrawalGroupId,
+ group.batches![0].hPlanchets,
+ 0,
+ error,
+ );
+ });
+ await runner.runReadWriteTx(async (tx) => {
+ const stored = (await tx.getWithdrawalGroup(group.withdrawalGroupId))!;
+ t.equal(stored.batches?.[0].state, "rejected");
+ t.equal(
+ (await tx.getPlanchetByGroupAndIndex(group.withdrawalGroupId, 0))
+ ?.lastError?.code,
+ error.code,
+ );
+ stored.batches![0].state = "complete";
+ await tx.upsertWithdrawalGroup(stored);
+ await recordWithdrawalBatchError(
+ tx,
+ group.withdrawalGroupId,
+ group.batches![0].hPlanchets,
+ 0,
+ error,
+ );
+ t.equal(
+ (await tx.getWithdrawalGroup(group.withdrawalGroupId))?.batches?.[0]
+ .state,
+ "complete",
+ );
+ });
+ },
+ },
+ {
name: "withdrawal group: bank-integrated wgInfo round trips whole",
async run(t, runner) {
const wg = makeWithdrawalGroup("wg-bi");
@@ -4028,6 +4129,7 @@ export const conformanceCases: ConformanceCase[] = [
name: "recoup group: round trip, by exchange and active range",
async run(t, runner) {
const rc = makeRecoupGroup("rc-1", "https://rex/");
+ rc.recoveredAmounts = { [ck("recoup-coin")]: "TESTKUDOS:0.3" };
await runner.runReadWriteTx((tx) => tx.upsertRecoupGroup(rc));
const got = await runner.runReadWriteTx((tx) =>
tx.getRecoupGroup("rc-1"),
diff --git a/packages/taler-wallet-core/src/withdraw.test.ts b/packages/taler-wallet-core/src/withdraw.test.ts
@@ -571,7 +571,11 @@ test("withdrawal selection bug repro", (t) => {
assert.ok(Amounts.cmp(res.totalWithdrawCost, amount) <= 0);
});
-test("withdrawal denomination selection is documented greedy best effort", () => {
+function makeWithdrawalDenom(
+ denomPubHash: string,
+ value: AmountString,
+ feeWithdraw: AmountString,
+): WalletDenomination {
const now = AbsoluteTime.now();
const stampStart = timestampProtocolToDb(
AbsoluteTime.toProtocolTimestamp(
@@ -589,36 +593,33 @@ test("withdrawal denomination selection is documented greedy best effort", () =>
),
);
const zero = "KUDOS:0" as AmountString;
- const makeDenom = (
- denomPubHash: string,
- value: AmountString,
- feeWithdraw: AmountString,
- ): WalletDenomination =>
- ({
- denomPubHash,
- value,
- currency: "KUDOS",
- fees: {
- feeWithdraw,
- feeDeposit: zero,
- feeRefresh: zero,
- feeRefund: zero,
- },
- verificationStatus: DenominationVerificationStatus.VerifiedGood,
- isOffered: true,
- isRevoked: false,
- isLost: false,
- stampStart,
- stampExpireWithdraw,
- stampExpireDeposit,
- denomPub: { cipher: DenomKeyType.Rsa, age_mask: 0 },
- }) as WalletDenomination;
+ return {
+ denomPubHash,
+ value,
+ currency: "KUDOS",
+ fees: {
+ feeWithdraw,
+ feeDeposit: zero,
+ feeRefresh: zero,
+ feeRefund: zero,
+ },
+ verificationStatus: DenominationVerificationStatus.VerifiedGood,
+ isOffered: true,
+ isRevoked: false,
+ isLost: false,
+ stampStart,
+ stampExpireWithdraw,
+ stampExpireDeposit,
+ denomPub: { cipher: DenomKeyType.Rsa, age_mask: 0 },
+ } as WalletDenomination;
+}
+test("withdrawal denomination selection is documented greedy best effort", () => {
const selection = selectWithdrawalDenominations(
Amounts.parseOrThrow("KUDOS:15"),
[
- makeDenom("cost-eleven", "KUDOS:10", "KUDOS:1"),
- makeDenom("cost-five", "KUDOS:5", zero),
+ makeWithdrawalDenom("cost-eleven", "KUDOS:10", "KUDOS:1"),
+ makeWithdrawalDenom("cost-five", "KUDOS:5", "KUDOS:0"),
],
);
@@ -631,3 +632,304 @@ test("withdrawal denomination selection is documented greedy best effort", () =>
assert.strictEqual(selection.totalWithdrawCost, "KUDOS:11");
assert.strictEqual(selection.totalCoinValue, "KUDOS:10");
});
+
+test("redenomination spends only authorized funding left after accepted debits", async (t) => {
+ const { redenominateWithdrawal } = await import("./withdraw.js");
+ const { PlanchetStatus } = await import("./db/records.js");
+ const old = makeWithdrawalDenom("old", "KUDOS:8", "KUDOS:1");
+ const replacement = makeWithdrawalDenom("new", "KUDOS:9", "KUDOS:1");
+ for (const d of [old, replacement]) d.exchangeMasterPub = "master";
+ t.mock.method(
+ WithdrawTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ for (const [funding, accepted, total] of [
+ ["KUDOS:30", false, "KUDOS:10"],
+ ["KUDOS:30", true, "KUDOS:9"],
+ ["KUDOS:9", false, "KUDOS:0"],
+ ] as const) {
+ const group = {
+ withdrawalGroupId: "wg",
+ exchangeBaseUrl: "https://exchange/",
+ status: WithdrawalGroupStatus.PendingRedenominate,
+ reserveBalanceAmount: funding,
+ instructedAmount: "KUDOS:10",
+ batches: [
+ {
+ coinIndices: [0],
+ state: accepted ? "complete" : "rejected",
+ hPlanchets: "hash",
+ },
+ ],
+ denomsSel: {
+ selectedDenoms: [{ denomPubHash: old.denomPubHash, count: 1 }],
+ totalWithdrawCost: "KUDOS:9",
+ totalCoinValue: "KUDOS:8",
+ requiresReselection: accepted,
+ },
+ } as WalletWithdrawalGroup;
+ const tx = {
+ getWithdrawalGroup: async () => group,
+ upsertWithdrawalGroup: async () => {},
+ notify: () => {},
+ getExchange: async () => undefined,
+ getExchangeDetails: async () => ({ masterPublicKey: "master" }),
+ getDenominationsByRefs: async () => [old],
+ getDenominationFamiliesByExchange: async () => [
+ { denominationFamilySerial: 1, familyParams: replacement },
+ ],
+ findDenominationByFamilyFromExpiry: async () => replacement,
+ getPlanchetsByGroup: async () => [
+ {
+ coinIdx: 0,
+ planchetStatus: accepted
+ ? PlanchetStatus.WithdrawalDone
+ : PlanchetStatus.Pending,
+ },
+ ],
+ upsertPlanchet: async () => {},
+ };
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ } as WalletExecutionContext;
+ await redenominateWithdrawal(wex, group.exchangeBaseUrl!, "wg");
+ assert.equal(group.denomsSel?.totalWithdrawCost, total);
+ assert.equal(group.denomsSel?.requiresReselection, undefined);
+ assert.equal(group.status, WithdrawalGroupStatus.PendingReady);
+ }
+});
+
+test("redenomination does not append replacements to a previously signed partial batch", async () => {
+ const { extendWithdrawalBatches } = await import("./withdraw.js");
+ const { PlanchetStatus } = await import("./db/records.js");
+ const { encodeCrock } = await import("@gnu-taler/taler-util");
+ const plan = (i: number) =>
+ ({
+ coinIdx: i,
+ coinPub: `coin-${i}`,
+ planchetStatus: PlanchetStatus.Pending,
+ denomPubHash: encodeCrock(new Uint8Array(64).fill(1)),
+ coinEv: {
+ cipher: DenomKeyType.Rsa,
+ rsa_blinded_planchet: encodeCrock(new Uint8Array(64).fill(i + 2)),
+ },
+ }) as import("./db/records.js").WalletPlanchet;
+ const original = Array.from({ length: 65 }, (_, i) => plan(i));
+ original[1].planchetStatus = PlanchetStatus.WithdrawalDone;
+ const mixed = extendWithdrawalBatches([], original);
+ assert.equal(mixed[0].state, "complete");
+ assert.deepEqual(
+ mixed[0].coinIndices,
+ original.slice(0, 64).map((p) => p.coinIdx),
+ );
+ original[1].planchetStatus = PlanchetStatus.Pending;
+ const first = extendWithdrawalBatches([], original);
+ first[0].state = "rejected";
+ first[1].state = "complete";
+ original
+ .slice(0, 64)
+ .forEach((p) => (p.planchetStatus = PlanchetStatus.AbortedReplaced));
+ original[64].planchetStatus = PlanchetStatus.WithdrawalDone;
+ const replacement = [
+ ...original,
+ ...Array.from({ length: 64 }, (_, i) => plan(i + 65)),
+ ];
+ const resumed = extendWithdrawalBatches(structuredClone(first), replacement);
+ assert.deepStrictEqual(resumed.slice(0, 2), first);
+ assert.deepStrictEqual(
+ resumed[2].coinIndices,
+ Array.from({ length: 64 }, (_, i) => i + 65),
+ );
+ assert.deepStrictEqual(
+ extendWithdrawalBatches(resumed, replacement),
+ resumed,
+ );
+ assert.equal(
+ resumed.flatMap((b) => b.coinIndices).filter((i) => i === 64).length,
+ 1,
+ );
+});
+
+for (const { tampered, field, unresolved } of [
+ ...[false, true].flatMap((tampered) =>
+ ["h_planchets", "planchets_h"].map((field) => ({
+ tampered,
+ field,
+ unresolved: true,
+ })),
+ ),
+ { tampered: false, field: "planchets_h", unresolved: false },
+]) {
+ test(`legacy batch recovery authenticates reserve history (${field}, tampered=${tampered}, unresolved=${unresolved})`, async (t) => {
+ const U = await import("@gnu-taler/taler-util");
+ const R = await import("./db/records.js");
+ const { nativeCrypto } = await import("./crypto/cryptoImplementation.js");
+ const { restoreWithdrawalBatches, hashWithdrawalPlanchets } =
+ await import("./withdraw.js");
+ const key = (n: number, len = 32) =>
+ U.encodeCrock(new Uint8Array(len).fill(n));
+ const plans = [0, 1, 2].map((i) => ({
+ coinIdx: i,
+ coinPub: key(1 + i),
+ denomPubHash: key(3, 64),
+ coinEv: { cipher: DenomKeyType.Rsa, rsa_blinded_planchet: key(4 + i) },
+ planchetStatus:
+ i === 0 ? R.PlanchetStatus.AbortedReplaced : R.PlanchetStatus.Pending,
+ })) as import("./db/records.js").WalletPlanchet[];
+ plans[2].denomPubHash = key(5, 64);
+ if (!unresolved) plans[1].planchetStatus = R.PlanchetStatus.AbortedReplaced;
+ let group = {
+ withdrawalGroupId: "legacy",
+ status: WithdrawalGroupStatus.PendingReady,
+ effectiveWithdrawalAmount: "TESTKUDOS:1",
+ reservePub: U.encodeCrock(U.eddsaGetPublic(U.decodeCrock(key(7)))),
+ reservePriv: key(7),
+ secretSeed: key(8),
+ exchangeBaseUrl: "https://exchange.example/",
+ instructedAmount: "TESTKUDOS:1",
+ denomsSel: {
+ totalCoinValue: "TESTKUDOS:1",
+ selectedDenoms: [
+ { denomPubHash: key(3, 64), count: 1, skip: 1 },
+ { denomPubHash: key(3, 64), count: 1, skip: unresolved ? 0 : 1 },
+ // The wallet stopped after generating only index 2 of this entry.
+ { denomPubHash: key(5, 64), count: 2 },
+ ],
+ },
+ } as WalletWithdrawalGroup;
+ const h = hashWithdrawalPlanchets(
+ [plans[0].coinEv],
+ [plans[0].denomPubHash],
+ );
+ const sig = await nativeCrypto.signWithdrawal({
+ amount: "TESTKUDOS:1",
+ fee: "TESTKUDOS:0",
+ reservePriv: group.reservePriv,
+ coinEvs: [plans[0].coinEv],
+ denomsPubHashes: [plans[0].denomPubHash],
+ });
+ const entry = {
+ type: "WITHDRAW",
+ history_offset: 1,
+ [field]: h,
+ reserve_sig: tampered ? key(9, 64) : sig.sig,
+ };
+ const posted: { coin_evs: unknown[] }[] = [];
+ t.mock.method(
+ WithdrawTransactionContext.prototype,
+ "updateTransactionMeta",
+ async () => {},
+ );
+ const tx = {
+ notify: () => {},
+ getExchangeBaseUrlFixup: async () => undefined,
+ getExchange: async () => ({
+ detailsPointer: { masterPublicKey: key(10), currency: "TESTKUDOS" },
+ }),
+ getExchangeDetailsByPointer: async () => ({
+ currency: "TESTKUDOS",
+ wireInfo: { accounts: [] },
+ }),
+ getCoinAvailabilityByExchange: async () => [],
+ getPlanchetByGroupAndIndex: async (_id: string, i: number) =>
+ structuredClone(plans[i]),
+ getPlanchetsByGroup: async () => structuredClone(plans),
+ getWithdrawalGroup: async () => structuredClone(group),
+ upsertWithdrawalGroup: async (g: WalletWithdrawalGroup) => {
+ group = structuredClone(g);
+ },
+ upsertPlanchet: async (p: import("./db/records.js").WalletPlanchet) => {
+ plans[p.coinIdx] = structuredClone(p);
+ },
+ getExchangeDetails: async () => ({ masterPublicKey: key(10) }),
+ };
+ const wex = {
+ runWalletDbTx: async (f: any) => f(tx),
+ cancellationToken: U.CancellationToken.CONTINUE,
+ cryptoApi: {
+ signReserveHistoryReq: nativeCrypto.signReserveHistoryReq,
+ signWithdrawal: nativeCrypto.signWithdrawal,
+ },
+ ws: {
+ networkAvailable: true,
+ exchangeCache: { get: () => ({ protocolVersionRange: "42:0:8" }) },
+ denomInfoCache: {
+ getOrPut: async () => ({
+ value: "TESTKUDOS:1",
+ feeWithdraw: "TESTKUDOS:0",
+ }),
+ },
+ },
+ http: {
+ fetch: async (url: string, opts: { body: { coin_evs: unknown[] } }) => {
+ if (url.endsWith("/withdraw")) {
+ posted.push(opts.body);
+ throw Error("lost replay response");
+ }
+ return {
+ status: url.includes("start=1") ? 204 : 200,
+ headers: { get: () => undefined },
+ requestUrl: url,
+ requestMethod: "GET",
+ json: async () => ({ balance: "TESTKUDOS:0", history: [entry] }),
+ };
+ },
+ },
+ } as unknown as WalletExecutionContext;
+ if (tampered) {
+ await assert.rejects(
+ restoreWithdrawalBatches(wex, structuredClone(group)),
+ /invalid withdrawal authorization/,
+ );
+ assert.equal(group.batches, undefined);
+ assert.equal(plans[0].planchetStatus, R.PlanchetStatus.AbortedReplaced);
+ } else {
+ await restoreWithdrawalBatches(wex, structuredClone(group));
+ assert.deepStrictEqual(group.batches, [
+ { coinIndices: [0], hPlanchets: h, state: "complete" },
+ ...(unresolved
+ ? [{ coinIndices: [1], hPlanchets: "", state: "unresolved" }]
+ : []),
+ ]);
+ assert.equal(plans[0].planchetStatus, R.PlanchetStatus.Pending);
+ assert.equal(group.denomsSel?.requiresReselection, true);
+ const { processWithdrawalGroup } = await import("./withdraw.js");
+ const replay = processWithdrawalGroup(wex, group.withdrawalGroupId);
+ if (unresolved) await assert.rejects(replay, /cannot yet be verified/);
+ else await replay;
+ assert.deepEqual(
+ posted.map((body) => body.coin_evs),
+ [[plans[0].coinEv]],
+ );
+ // A restart after generating the last replacement must not turn the
+ // new planchets into another ambiguous legacy request.
+ plans.push({
+ ...plans[2],
+ coinIdx: 3,
+ coinPub: key(6),
+ coinEv: { cipher: DenomKeyType.Rsa, rsa_blinded_planchet: key(7) },
+ });
+ const before = structuredClone(group.batches);
+ await restoreWithdrawalBatches(wex, structuredClone(group));
+ assert.deepStrictEqual(group.batches, before);
+ }
+ });
+}
+
+test("rejected withdrawal batches survive a missing legacy error without repeating redenomination", async () => {
+ const { withdrawalNeedsRedenomination } = await import("./withdraw.js");
+ const { PlanchetStatus } = await import("./db/records.js");
+ const batches = [
+ { coinIndices: [0], hPlanchets: "hash", state: "rejected" as const },
+ ];
+ const planchet = {
+ coinIdx: 0,
+ planchetStatus: PlanchetStatus.Pending,
+ } as import("./db/records.js").WalletPlanchet;
+ assert.equal(withdrawalNeedsRedenomination(batches, [planchet]), true);
+ planchet.planchetStatus = PlanchetStatus.AbortedReplaced;
+ assert.equal(withdrawalNeedsRedenomination(batches, [planchet]), false);
+ planchet.planchetStatus = PlanchetStatus.WithdrawalDone;
+ assert.equal(withdrawalNeedsRedenomination(batches, [planchet]), false);
+});
diff --git a/packages/taler-wallet-core/src/withdraw.ts b/packages/taler-wallet-core/src/withdraw.ts
@@ -109,6 +109,7 @@ import {
encodeCrock,
getErrorDetailFromException,
getRandomBytes,
+ hash,
hashCoinEv,
hashCoinPub,
j2s,
@@ -150,6 +151,8 @@ import {
WalletOperationRetry,
WalletPlanchet,
WalletWithdrawalGroup,
+ WalletWithdrawalBatch,
+ WalletWithdrawCoinSource,
WgInfo,
WithdrawalGroupStatus,
WithdrawalRecordType,
@@ -1190,30 +1193,40 @@ async function processWithdrawalGroupRedenominate(
if (!exchangeBaseUrl) {
throw Error("invalid state (no exchange base URL)");
}
- await fetchFreshExchange(wex, exchangeBaseUrl, {
+ const exchange = await fetchFreshExchange(wex, exchangeBaseUrl, {
// Redenomination is entered after the exchange rejected denomination
// keys. A previous update can have completed while the exchange still
// had no replacement keys, so its otherwise-fresh cache is not enough.
forceUpdate: true,
noBail: true,
});
- await redenominateWithdrawal(
+ if (
+ (LibtoolVersion.parseVersion(exchange.protocolVersionRange)?.current ??
+ 0) >= 26
+ ) {
+ await restoreWithdrawalBatches(wex, withdrawalGroup);
+ }
+ const ambiguous = await wex.runWalletDbTx(async (tx) =>
+ withdrawalBatchesNeedReplay(
+ withdrawalGroup.batches ?? [],
+ await tx.getPlanchetsByGroup(withdrawalGroup.withdrawalGroupId),
+ ),
+ );
+ if (ambiguous) {
+ return wex.runWalletDbTx(async (tx) => {
+ const [rec, h] = await ctx.getRecordHandle(tx);
+ if (rec?.status === WithdrawalGroupStatus.PendingRedenominate) {
+ rec.status = WithdrawalGroupStatus.PendingReady;
+ await h.update(rec, "replay-ambiguous-batches");
+ }
+ return TaskRunResult.backoff();
+ });
+ }
+ return redenominateWithdrawal(
wex,
exchangeBaseUrl,
withdrawalGroup.withdrawalGroupId,
);
- return await ctx.wex.runWalletDbTx(async (tx) => {
- const [rec, h] = await ctx.getRecordHandle(tx);
- switch (rec?.status) {
- case WithdrawalGroupStatus.PendingRedenominate:
- break;
- default:
- return TaskRunResult.backoff();
- }
- rec.status = WithdrawalGroupStatus.PendingReady;
- await h.update(rec, "redenominate-done");
- return TaskRunResult.progress();
- });
}
async function processWithdrawalGroupBalanceKyc(
@@ -1801,6 +1814,7 @@ async function processPlanchetGenerate(
}
interface WithdrawalRequestBatchArgs {
+ coinIndices?: number[];
coinStartIndex: number;
batchSize: number;
@@ -1810,6 +1824,7 @@ interface WithdrawalBatchResult {
coinIdxs: number[];
batchResp: ExchangeWithdrawResponse;
hPlanchets?: string;
+ envelopeHashes?: string[];
}
export function hashWithdrawalPlanchets(
@@ -2081,6 +2096,37 @@ async function processPlanchetExchangeLegacyBatchRequest(
}
}
+/** Persist the batch outcome and its diagnostic in the caller's transaction. */
+export async function recordWithdrawalBatchError(
+ tx: WalletDbTransaction,
+ withdrawalGroupId: string,
+ hPlanchets: string,
+ coinIndex: number,
+ error: TalerErrorDetail,
+): Promise<void> {
+ const wg = await tx.getWithdrawalGroup(withdrawalGroupId);
+ const batch = wg?.batches?.find((b) => b.hPlanchets === hPlanchets);
+ checkDbInvariant(!!wg && !!batch, "withdrawal batch was not persisted");
+ const planchet = await tx.getPlanchetByGroupAndIndex(
+ withdrawalGroupId,
+ coinIndex,
+ );
+ checkDbInvariant(!!planchet, "withdrawal planchet disappeared");
+ if (
+ batch.state !== "complete" &&
+ [
+ TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED,
+ TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED,
+ TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN,
+ ].includes(error.code)
+ ) {
+ batch.state = "rejected";
+ await tx.upsertWithdrawalGroup(wg);
+ }
+ planchet.lastError = error;
+ await tx.upsertPlanchet(planchet);
+}
+
/**
* Send the withdrawal request for a generated planchet to the exchange.
*
@@ -2113,12 +2159,18 @@ async function processPlanchetExchangeBatchRequest(
let accAmount = Amounts.zeroOfAmount(withdrawalGroup.instructedAmount);
let accFee = Amounts.zeroOfAmount(withdrawalGroup.instructedAmount);
await wex.runWalletDbTx(async (tx) => {
- for (
- let coinIdx = args.coinStartIndex;
- coinIdx < args.coinStartIndex + args.batchSize &&
- coinIdx < wgContext.numPlanchets;
- coinIdx++
- ) {
+ const indices =
+ args.coinIndices ??
+ Array.from(
+ {
+ length: Math.min(
+ args.batchSize,
+ wgContext.numPlanchets - args.coinStartIndex,
+ ),
+ },
+ (_, i) => args.coinStartIndex + i,
+ );
+ for (const coinIdx of indices) {
const planchet = await tx.getPlanchetByGroupAndIndex(
withdrawalGroup.withdrawalGroupId,
coinIdx,
@@ -2182,17 +2234,15 @@ async function processPlanchetExchangeBatchRequest(
coinIdx: number,
): Promise<void> {
logger.trace(`withdrawal request failed: ${j2s(errDetail)}`);
- await wex.runWalletDbTx(async (tx) => {
- const planchet = await tx.getPlanchetByGroupAndIndex(
+ await wex.runWalletDbTx((tx) =>
+ recordWithdrawalBatchError(
+ tx,
withdrawalGroup.withdrawalGroupId,
+ hashWithdrawalPlanchets(coinEvs, denomHashes),
coinIdx,
- );
- if (!planchet) {
- return;
- }
- planchet.lastError = errDetail;
- await tx.upsertPlanchet(planchet);
- });
+ errDetail,
+ ),
+ );
}
// FIXME: handle individual error codes better!
@@ -2215,6 +2265,34 @@ async function processPlanchetExchangeBatchRequest(
});
const hPlanchets = hashWithdrawalPlanchets(coinEvs, denomHashes);
+ const updateBatch = async (state: WalletWithdrawalBatch["state"]) => {
+ await wex.runWalletDbTx(async (tx) => {
+ const wg = await tx.getWithdrawalGroup(withdrawalGroup.withdrawalGroupId);
+ const batch = wg?.batches?.find((b) => b.hPlanchets === hPlanchets);
+ checkDbInvariant(!!wg && !!batch, "withdrawal batch was not persisted");
+ // Once acceptance was observed, a contradictory later error cannot
+ // make it safe to discard the outputs or authorize another debit.
+ if (batch.state === "complete" && state === "rejected") return;
+ batch.state = state;
+ await tx.upsertWithdrawalGroup(wg);
+ });
+ };
+
+ await wex.runWalletDbTx(async (tx) => {
+ const group = await tx.getWithdrawalGroup(
+ withdrawalGroup.withdrawalGroupId,
+ );
+ checkDbInvariant(
+ !!group?.batches?.some(
+ (b) =>
+ b.hPlanchets === hPlanchets &&
+ b.state !== "rejected" &&
+ JSON.stringify(b.coinIndices) === JSON.stringify(requestCoinIdxs),
+ ),
+ "withdrawal request no longer matches its durable batch",
+ );
+ });
+
const batchReq: ExchangeWithdrawRequest = {
cipher: "ED25519",
reserve_pub: withdrawalGroup.reservePub,
@@ -2242,6 +2320,7 @@ async function processPlanchetExchangeBatchRequest(
const resp = await exchangeClient.withdraw({ body: batchReq });
switch (resp.case) {
case "ok":
+ await updateBatch("complete");
break;
case HttpStatusCode.UnavailableForLegalReasons: {
await transitionKycRequired(
@@ -2279,6 +2358,9 @@ async function processPlanchetExchangeBatchRequest(
coinIdxs: requestCoinIdxs,
batchResp: resp.body,
hPlanchets,
+ envelopeHashes: coinEvs.map((ev, i) =>
+ encodeCrock(hashCoinEv(ev, denomHashes[i])),
+ ),
};
} catch (e) {
// Network error or unexpected response.
@@ -2309,6 +2391,7 @@ async function verifyPlanchetSignature(
coinIdx: number,
resp: BlindedDenominationSignature,
hPlanchets?: string,
+ recoupBatch?: WalletWithdrawCoinSource["recoupBatch"],
): Promise<PlanchetVerification> {
const withdrawalGroup = wgContext.wgRecord;
checkDbInvariant(
@@ -2396,6 +2479,7 @@ async function verifyPlanchetSignature(
reservePub: withdrawalGroup.reservePub,
withdrawalGroupId: withdrawalGroup.withdrawalGroupId,
hPlanchets,
+ recoupBatch,
nonce:
planchet.coinEv.cipher === DenomKeyType.ClauseSchnorr
? planchet.coinEv.cs_nonce
@@ -2652,14 +2736,15 @@ async function processFundedReserve(
let denomsSel = withdrawalGroup.denomsSel;
let instructedAmount = withdrawalGroup.instructedAmount;
if (denomsSel === undefined) {
- const selectionAmount = bankConfirmation?.amount ?? reserveBalance;
+ const selectionAmount =
+ instructedAmount ?? bankConfirmation?.amount ?? reserveBalance;
denomsSel = await getInitialDenomsSelection(
wex,
exchangeBaseUrl,
Amounts.parseOrThrow(selectionAmount),
undefined,
);
- instructedAmount = denomsSel.totalWithdrawCost;
+ instructedAmount ??= selectionAmount;
}
checkDbInvariant(
@@ -2727,7 +2812,7 @@ async function processFundedReserve(
currency,
);
const denomsSel = selectWithdrawalDenominations(
- Amounts.parseOrThrow(reserveStatus.balance),
+ Amounts.min(reserveStatus.balance, instructedAmount),
candidates,
);
wg.denomsSel = denomsSel;
@@ -3054,18 +3139,19 @@ export function classifyWithdrawalKycHardLimitRecovery(
* Necessary when denominations expired or got revoked
* before the withdrawal could complete.
*/
-async function redenominateWithdrawal(
+export async function redenominateWithdrawal(
wex: WalletExecutionContext,
exchangeBaseUrl: string,
withdrawalGroupId: string,
-): Promise<void> {
+): Promise<TaskRunResult> {
await updateWithdrawalDenomsForExchange(wex, exchangeBaseUrl);
logger.trace(`redenominating withdrawal group ${withdrawalGroupId}`);
- await wex.runWalletDbTx(async (tx) => {
- const wg = await tx.getWithdrawalGroup(withdrawalGroupId);
- if (!wg) {
- return;
+ const ctx = new WithdrawTransactionContext(wex, withdrawalGroupId);
+ return wex.runWalletDbTx(async (tx) => {
+ const [wg, handle] = await ctx.getRecordHandle(tx);
+ if (wg?.status !== WithdrawalGroupStatus.PendingRedenominate) {
+ return TaskRunResult.backoff();
}
checkDbInvariant(
wg.exchangeBaseUrl !== undefined,
@@ -3080,8 +3166,14 @@ async function redenominateWithdrawal(
throw Error("reserve amount not known yet");
}
- const currency = Amounts.currencyOf(wg.denomsSel.totalWithdrawCost);
- let remaining = Amount.from(wg.reserveBalanceAmount);
+ checkDbInvariant(
+ !!wg.instructedAmount,
+ "missing authorized withdrawal amount",
+ );
+ const currency = Amounts.currencyOf(wg.instructedAmount);
+ let remaining = Amount.from(
+ Amounts.min(wg.reserveBalanceAmount, wg.instructedAmount),
+ );
const zero = Amount.zeroOfCurrency(currency);
const exchangeBaseUrl = wg.exchangeBaseUrl;
@@ -3131,7 +3223,11 @@ async function redenominateWithdrawal(
let denomOkay: boolean = false;
if (denom != null) {
- denomOkay = isWithdrawableDenom(denom);
+ // A rejected batch is atomic: even its still-valid denominations
+ // must be replaced with fresh planchets. Reusing only some members
+ // would keep them assigned to the rejected request forever.
+ // Submitted batches have been replayed before entering this function.
+ denomOkay = wg.batches === undefined && isWithdrawableDenom(denom);
const numCoins = sel.count - (sel.skip ?? 0);
const denomValue = Amount.from(denom.value).mult(numCoins);
@@ -3188,11 +3284,16 @@ async function redenominateWithdrawal(
p.planchetStatus = PlanchetStatus.AbortedReplaced;
await tx.upsertPlanchet(p);
}
- if (numDone > 0 && denom != null) {
+ if (numDone > 0) {
+ checkDbInvariant(
+ !!denom,
+ "missing denomination for an accepted withdrawal",
+ );
const doneValue = Amount.from(denom.value).mult(numDone);
const doneFee = Amount.from(denom.fees.feeWithdraw).mult(numDone);
remaining = remaining.sub(doneValue).sub(doneFee);
prevTotalCoinValue = prevTotalCoinValue.add(doneValue);
+ prevHasDenomWithAgeRestriction ||= denom.denomPub.age_mask > 0;
prevTotalWithdrawalCost = prevTotalWithdrawalCost.add(
doneValue,
doneFee,
@@ -3203,7 +3304,7 @@ async function redenominateWithdrawal(
coinIndex += sel.count;
}
- if (candidates.length === 0) {
+ if (!remaining.isZero() && candidates.length === 0) {
throw TalerError.fromDetail(
TalerErrorCode.WALLET_EXCHANGE_DENOMINATIONS_INSUFFICIENT,
{ exchangeBaseUrl },
@@ -3235,10 +3336,288 @@ async function redenominateWithdrawal(
if (logger.shouldLogTrace()) {
logger.trace(`merged denom sel: ${j2s(mergedSel)}`);
}
- await tx.upsertWithdrawalGroup(wg);
+ wg.status = WithdrawalGroupStatus.PendingReady;
+ await handle.update(wg, "redenominate-done");
+ return TaskRunResult.progress();
});
}
+/** Match all requested commitments in one scan of the original and active lists. */
+function findWithdrawalBatches(
+ planchets: WalletPlanchet[],
+ commitments: ReadonlySet<string>,
+): Map<string, WalletPlanchet[]> {
+ const matches = new Map<string, WalletPlanchet[]>();
+ if (!commitments.size) return matches;
+ const ordered = [...planchets]
+ .sort((a, b) => a.coinIdx - b.coinIdx)
+ .map((planchet, index) => ({
+ planchet,
+ index,
+ envelopeHash: hashCoinEv(planchet.coinEv, planchet.denomPubHash),
+ }));
+ const active = ordered.filter(
+ ({ planchet }) =>
+ planchet.planchetStatus !== PlanchetStatus.AbortedReplaced,
+ );
+ for (const candidates of active.length === ordered.length
+ ? [ordered]
+ : [ordered, active]) {
+ // A batch commitment hashes consecutive 64-byte envelope hashes.
+ const packed = new Uint8Array(candidates.length * 64);
+ candidates.forEach((p, i) => packed.set(p.envelopeHash, i * 64));
+ for (let start = 0; start < candidates.length; start++) {
+ for (
+ let end = start + 1;
+ end <= Math.min(start + 64, candidates.length);
+ end++
+ ) {
+ // The first scan already covered active slices that contain no gap.
+ if (
+ candidates === active &&
+ candidates[end - 1].index - candidates[start].index ===
+ end - start - 1
+ )
+ continue;
+ const commitment = encodeCrock(
+ hash(packed.subarray(start * 64, end * 64)),
+ );
+ if (commitments.has(commitment)) {
+ matches.set(
+ commitment,
+ candidates.slice(start, end).map((c) => c.planchet),
+ );
+ if (matches.size === commitments.size) return matches;
+ }
+ }
+ }
+ }
+ return matches;
+}
+
+/** Upgrade old worklists without guessing a possibly already debited request. */
+export async function restoreWithdrawalBatches(
+ wex: WalletExecutionContext,
+ group: WalletWithdrawalGroup,
+): Promise<void> {
+ if (group.batches && !group.batches.some((b) => b.state === "unresolved"))
+ return;
+ const plans = await wex.runWalletDbTx((tx) =>
+ tx.getPlanchetsByGroup(group.withdrawalGroupId),
+ );
+ let batches: WalletWithdrawalBatch[];
+ if (!group.denomsSel?.selectedDenoms.some((d) => d.skip)) {
+ // Before any redenomination the original grouping is unambiguous.
+ // A partially generated worklist has never been submitted by the old worker.
+ const count = group.denomsSel?.selectedDenoms.reduce(
+ (n, d) => n + d.count,
+ 0,
+ );
+ batches = plans.length === count ? extendWithdrawalBatches([], plans) : [];
+ } else {
+ checkDbInvariant(
+ !!group.exchangeBaseUrl && !!group.instructedAmount,
+ "uninitialized legacy withdrawal",
+ );
+ batches = (group.batches ?? []).filter((b) => b.state !== "unresolved");
+ const client = walletExchangeClient(group.exchangeBaseUrl, wex);
+ const authorizations = new Map<string, string | undefined>();
+ let startOffset = 0;
+ for (;;) {
+ const signature = await wex.cryptoApi.signReserveHistoryReq({
+ reservePriv: group.reservePriv,
+ startOffset,
+ });
+ const result = await client.getReserveHistory(
+ group.reservePub,
+ signature.sig,
+ startOffset,
+ );
+ if (
+ result.case === HttpStatusCode.NoContent ||
+ result.case === HttpStatusCode.NotModified
+ )
+ break;
+ const history = succeedOrThrow(result);
+ if (history.history.length === 0) break;
+ let nextOffset = startOffset;
+ for (const entry of history.history) {
+ checkProtocolInvariant(
+ Number.isSafeInteger(entry.history_offset) &&
+ entry.history_offset > nextOffset,
+ "invalid reserve history offset during withdrawal recovery",
+ );
+ nextOffset = entry.history_offset;
+ if (entry.type !== "WITHDRAW") continue;
+ const detail = entry as unknown as {
+ h_planchets?: string;
+ planchets_h?: string;
+ reserve_sig?: string;
+ };
+ // Current exchanges use planchets_h; older histories/documentation
+ // used h_planchets. The authorization below authenticates either form.
+ const commitment = detail.planchets_h ?? detail.h_planchets;
+ if (!commitment || batches.some((b) => b.hPlanchets === commitment))
+ continue;
+ authorizations.set(commitment, detail.reserve_sig);
+ }
+ startOffset = nextOffset;
+ }
+ for (const [commitment, batch] of findWithdrawalBatches(
+ plans,
+ new Set(authorizations.keys()),
+ )) {
+ let amount = Amounts.zeroOfAmount(group.instructedAmount);
+ let fee = amount;
+ await wex.runWalletDbTx(async (tx) => {
+ const exchangeMasterPub = await getWithdrawalMasterPub(
+ tx,
+ group.exchangeBaseUrl!,
+ );
+ for (const p of batch) {
+ const denom = await getDenomInfo(wex, tx, {
+ exchangeMasterPub,
+ denomPubHash: p.denomPubHash,
+ });
+ checkDbInvariant(
+ !!denom,
+ "missing denomination during withdrawal recovery",
+ );
+ amount = Amounts.add(amount, denom.value).amount;
+ fee = Amounts.add(fee, denom.feeWithdraw).amount;
+ }
+ });
+ const signed = await wex.cryptoApi.signWithdrawal({
+ amount: Amounts.stringify(amount),
+ fee: Amounts.stringify(fee),
+ reservePriv: group.reservePriv,
+ coinEvs: batch.map((p) => p.coinEv),
+ denomsPubHashes: batch.map((p) => p.denomPubHash),
+ blindingSeed:
+ batch[0].coinEv.cipher === DenomKeyType.ClauseSchnorr
+ ? encodeCrock(
+ deriveCsWithdrawBlindingSeed(
+ decodeCrock(group.secretSeed),
+ batch[0].coinIdx,
+ ),
+ )
+ : undefined,
+ });
+ checkProtocolInvariant(
+ signed.sig === authorizations.get(commitment),
+ "invalid withdrawal authorization in reserve history",
+ );
+ batches.push({
+ coinIndices: batch.map((p) => p.coinIdx),
+ hPlanchets: commitment,
+ state: "complete",
+ });
+ }
+ const assigned = new Set(batches.flatMap((b) => b.coinIndices));
+ // The old worker generated every active planchet before its first POST.
+ // If an entry in the selection is only partly generated, none of that
+ // entry could have been submitted. Older entries may still be ambiguous.
+ const plansByIndex = new Map(plans.map((p) => [p.coinIdx, p]));
+ const previous = group.batches?.find((b) => b.state === "unresolved");
+ const unresolved: number[] = [];
+ let start = 0;
+ for (const d of group.denomsSel.selectedDenoms) {
+ const indices = Array.from(
+ { length: d.count - (d.skip ?? 0) },
+ (_, i) => start + i,
+ );
+ start += d.count;
+ if (!indices.every((i) => plansByIndex.has(i))) continue;
+ for (const i of indices) {
+ const p = plansByIndex.get(i)!;
+ if (
+ !assigned.has(i) &&
+ (!previous || previous.coinIndices.includes(i)) &&
+ p.planchetStatus !== PlanchetStatus.AbortedReplaced &&
+ p.planchetStatus !== PlanchetStatus.WithdrawalDone
+ )
+ unresolved.push(i);
+ }
+ }
+ if (unresolved.length)
+ batches.push({
+ coinIndices: unresolved,
+ hPlanchets: "",
+ state: "unresolved",
+ });
+ }
+ await wex.runWalletDbTx(async (tx) => {
+ const current = await tx.getWithdrawalGroup(group.withdrawalGroupId);
+ checkDbInvariant(!!current, "withdrawal disappeared during batch recovery");
+ const accepted = new Set(
+ batches
+ .filter((b) => b.state === "complete")
+ .flatMap((b) => b.coinIndices),
+ );
+ for (const p of plans) {
+ if (
+ accepted.has(p.coinIdx) &&
+ p.planchetStatus === PlanchetStatus.AbortedReplaced
+ ) {
+ // The legacy selection spent this debit again on replacement outputs.
+ // Replay existing batches before selecting against the corrected budget.
+ checkDbInvariant(!!current.denomsSel, "missing withdrawal selection");
+ current.denomsSel.requiresReselection = true;
+ p.planchetStatus = PlanchetStatus.Pending;
+ p.lastError = undefined;
+ await tx.upsertPlanchet(p);
+ }
+ }
+ current.batches = batches;
+ await tx.upsertWithdrawalGroup(current);
+ group.batches = batches;
+ group.denomsSel = current.denomsSel;
+ });
+}
+
+/** Extend the worklist without changing any previously persisted request. */
+export function extendWithdrawalBatches(
+ previous: WalletWithdrawalBatch[],
+ planchets: WalletPlanchet[],
+): WalletWithdrawalBatch[] {
+ const result = previous.map((b) => ({
+ ...b,
+ coinIndices: [...b.coinIndices],
+ }));
+ const assigned = new Set(previous.flatMap((b) => b.coinIndices));
+ const pending = planchets
+ .filter(
+ (p) =>
+ !assigned.has(p.coinIdx) &&
+ p.planchetStatus !== PlanchetStatus.AbortedReplaced,
+ )
+ .sort((a, b) => a.coinIdx - b.coinIdx);
+ while (pending.length) {
+ const batch = [pending.shift()!];
+ if (batch[0].coinEv.cipher !== DenomKeyType.ClauseSchnorr) {
+ while (
+ batch.length < 64 &&
+ pending.length &&
+ pending[0].coinEv.cipher !== DenomKeyType.ClauseSchnorr
+ )
+ batch.push(pending.shift()!);
+ }
+ result.push({
+ coinIndices: batch.map((p) => p.coinIdx),
+ hPlanchets: hashWithdrawalPlanchets(
+ batch.map((p) => p.coinEv),
+ batch.map((p) => p.denomPubHash),
+ ),
+ state: batch.some(
+ (p) => p.planchetStatus === PlanchetStatus.WithdrawalDone,
+ )
+ ? "complete"
+ : "submitted",
+ });
+ }
+ return result;
+}
+
async function processWithdrawalGroupPendingReady(
wex: WalletExecutionContext,
withdrawalGroup: WalletWithdrawalGroup,
@@ -3331,9 +3710,17 @@ async function processWithdrawalGroupPendingReady(
}
});
+ if (
+ (LibtoolVersion.parseVersion(exch.protocolVersionRange)?.current ?? 0) >= 26
+ ) {
+ await restoreWithdrawalBatches(wex, withdrawalGroup);
+ }
+ const replayOnly =
+ withdrawalGroup.denomsSel.requiresReselection ||
+ withdrawalGroup.batches?.some((b) => b.state === "unresolved");
// We sequentially generate planchets, so that
// large withdrawal groups don't make the wallet unresponsive.
- for (let i = 0; i < numTotalCoins; i++) {
+ for (let i = 0; !replayOnly && i < numTotalCoins; i++) {
const res = await processPlanchetGenerate(wex, withdrawalGroup, i);
if (res.badDenom) {
logger.warn(
@@ -3362,42 +3749,52 @@ async function processWithdrawalGroupPendingReady(
logger.trace(`withdrawing ${numTotalCoins} coins`);
- const generatedPlanchets = await wex.runWalletDbTx(async (tx) =>
- tx.getPlanchetsByGroup(withdrawalGroupId),
- );
- const planchetByIndex = new Map(
- generatedPlanchets.map((p) => [p.coinIdx, p]),
- );
+ const batches =
+ exchangeVer.current >= 26
+ ? await wex.runWalletDbTx(async (tx) => {
+ const wg = await tx.getWithdrawalGroup(withdrawalGroupId);
+ checkDbInvariant(!!wg, "withdrawal disappeared");
+ if (replayOnly) return wg.batches ?? [];
+ // A stored signature can prove acceptance only for its original
+ // membership. Never include a paid legacy output in a fresh batch.
+ const planchets = await tx.getPlanchetsByGroup(withdrawalGroupId);
+ wg.batches = extendWithdrawalBatches(
+ wg.batches ?? [],
+ planchets.filter(
+ (p) => p.planchetStatus !== PlanchetStatus.WithdrawalDone,
+ ),
+ );
+ await tx.upsertWithdrawalGroup(wg);
+ return wg.batches;
+ })
+ : Array.from(
+ { length: Math.ceil(numTotalCoins / maxBatchSize) },
+ (_, i) => ({
+ coinIndices: Array.from(
+ {
+ length: Math.min(
+ maxBatchSize,
+ numTotalCoins - i * maxBatchSize,
+ ),
+ },
+ (_, j) => i * maxBatchSize + j,
+ ),
+ hPlanchets: "",
+ state: "submitted" as const,
+ }),
+ );
- for (let i = 0; i < numTotalCoins; ) {
- let resp: WithdrawalBatchResult;
- if (exchangeVer.current >= 26) {
- let batchSize = maxBatchSize;
- const firstPlanchet = planchetByIndex.get(i);
- if (firstPlanchet?.coinEv.cipher === DenomKeyType.ClauseSchnorr) {
- batchSize = 1;
- } else {
- for (let j = i + 1; j < i + maxBatchSize && j < numTotalCoins; j++) {
- if (
- planchetByIndex.get(j)?.coinEv.cipher === DenomKeyType.ClauseSchnorr
- ) {
- batchSize = j - i;
- break;
- }
- }
- }
- resp = await processPlanchetExchangeBatchRequest(wex, wgContext, {
- batchSize,
- coinStartIndex: i,
- });
- i += batchSize;
- } else {
- resp = await processPlanchetExchangeLegacyBatchRequest(wex, wgContext, {
- batchSize: maxBatchSize,
- coinStartIndex: i,
- });
- i += maxBatchSize;
- }
+ for (const batch of batches) {
+ if (batch.state === "rejected" || batch.state === "unresolved") continue;
+ const args = {
+ coinStartIndex: batch.coinIndices[0],
+ batchSize: batch.coinIndices.length,
+ coinIndices: batch.coinIndices,
+ };
+ const resp =
+ exchangeVer.current >= 26
+ ? await processPlanchetExchangeBatchRequest(wex, wgContext, args)
+ : await processPlanchetExchangeLegacyBatchRequest(wex, wgContext, args);
const work: Promise<PlanchetVerification>[] = [];
for (let j = 0; j < resp.coinIdxs.length; j++) {
@@ -3412,35 +3809,33 @@ async function processWithdrawalGroupPendingReady(
resp.coinIdxs[j],
resp.batchResp.ev_sigs[j],
resp.hPlanchets,
+ resp.hPlanchets && resp.envelopeHashes
+ ? {
+ commitment: resp.hPlanchets,
+ coinIndex: j,
+ envelopeHashes: resp.envelopeHashes,
+ }
+ : undefined,
),
);
}
await storeVerifiedPlanchets(wex, wgContext, await Promise.all(work));
}
- let redenomRequired = false;
-
- await wex.runWalletDbTx(async (tx) => {
+ if (batches.some((b) => b.state === "unresolved")) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ {},
+ "Original withdrawal batches cannot yet be verified from reserve history; recovery material retained",
+ );
+ }
+ const redenomRequired = await wex.runWalletDbTx(async (tx) => {
const planchets = await tx.getPlanchetsByGroup(withdrawalGroupId);
- for (const p of planchets) {
- if (
- p.planchetStatus !== PlanchetStatus.Pending &&
- p.planchetStatus !== PlanchetStatus.KycRequired
- ) {
- continue;
- }
- if (!p.lastError) {
- continue;
- }
- switch (p.lastError.code) {
- case TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED:
- case TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED:
- case TalerErrorCode.EXCHANGE_GENERIC_KEYS_MISSING:
- case TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN:
- redenomRequired = true;
- return;
- }
+ const wg = await tx.getWithdrawalGroup(withdrawalGroupId);
+ if (wg?.denomsSel?.requiresReselection) {
+ return !withdrawalBatchesNeedReplay(wg.batches ?? [], planchets);
}
+ return withdrawalNeedsRedenomination(wg?.batches, planchets);
});
if (redenomRequired) {
@@ -3514,6 +3909,46 @@ async function processWithdrawalGroupPendingReady(
return TaskRunResult.backoff();
}
+function withdrawalBatchesNeedReplay(
+ batches: WalletWithdrawalBatch[],
+ planchets: WalletPlanchet[],
+): boolean {
+ const finished = new Set(
+ planchets
+ .filter((p) => p.planchetStatus === PlanchetStatus.WithdrawalDone)
+ .map((p) => p.coinIdx),
+ );
+ return batches.some(
+ (b) =>
+ b.state !== "rejected" && b.coinIndices.some((i) => !finished.has(i)),
+ );
+}
+
+/** Rejected batches remain actionable even if an older wallet lost their error. */
+export function withdrawalNeedsRedenomination(
+ batches: WalletWithdrawalBatch[] | undefined,
+ planchets: WalletPlanchet[],
+): boolean {
+ const rejected = new Set(
+ batches
+ ?.filter((b) => b.state === "rejected")
+ .flatMap((b) => b.coinIndices),
+ );
+ return planchets.some(
+ (p) =>
+ (p.planchetStatus === PlanchetStatus.Pending ||
+ p.planchetStatus === PlanchetStatus.KycRequired) &&
+ (rejected.has(p.coinIdx) ||
+ (p.lastError &&
+ [
+ TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_EXPIRED,
+ TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_REVOKED,
+ TalerErrorCode.EXCHANGE_GENERIC_KEYS_MISSING,
+ TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN,
+ ].includes(p.lastError.code))),
+ );
+}
+
async function startRedenomination(
ctx: WithdrawTransactionContext,
exchangeBaseUrl: string,
@@ -4169,7 +4604,10 @@ async function processConfirmedBankWithdrawal(
if (!status.amount) {
throw Error("bank did not provide amount");
}
- const instructedAmount = Amounts.parseOrThrow(status.amount);
+ const instructedAmount = Amounts.min(
+ status.amount,
+ withdrawalGroup.instructedAmount ?? status.amount,
+ );
denomSel = await getInitialDenomsSelection(
wex,
exchangeBaseUrl,
@@ -4201,7 +4639,7 @@ async function processConfirmedBankWithdrawal(
r.denomsSel = denomSel;
r.rawWithdrawalAmount = denomSel.totalWithdrawCost;
r.effectiveWithdrawalAmount = denomSel.totalCoinValue;
- r.instructedAmount = denomSel.totalWithdrawCost;
+ r.instructedAmount ??= status.amount;
}
await h.update(r, "reserve-bank-status");
return TaskRunResult.progress();
@@ -4454,6 +4892,7 @@ export async function internalPrepareCreateWithdrawalGroup(
}
const withdrawalGroup: WalletWithdrawalGroup = {
+ batches: [],
// next fields will be undefined if exchange or amount is not specified
denomsSel: initialDenomSel,
exchangeBaseUrl: exchangeBaseUrl,
@@ -4528,7 +4967,7 @@ export async function internalPerformCreateWithdrawalGroup(
});
}
- wex.taskScheduler.startShepherdTask(ctx.taskId);
+ tx.scheduleOnCommit(() => wex.taskScheduler.startShepherdTask(ctx.taskId));
if (prep.creationInfo) {
await internalPerformExchangeWasUsed(