commit d1a46891d4df0d213569542b180c2e28897159a5 parent 89f5316f7b6d2e91006f21f1e0b70747a5c110d1 Author: Florian Dold <dold@taler.net> Date: Tue, 17 Nov 2026 23:20:28 +0100 wallet-core: return an expiry flag for each balance GetBalances used to include the full renewal report. Flag balances with coins at risk and use their deposit deadlines to schedule the next check. Diffstat:
13 files changed, 453 insertions(+), 813 deletions(-)
diff --git a/packages/taler-harness/src/integrationtests/test-exchange-denom-storage.ts b/packages/taler-harness/src/integrationtests/test-exchange-denom-storage.ts @@ -115,10 +115,7 @@ export async function runExchangeDenomStorageTest( ); // Refresh estimates can change as keys are verified and time advances. // Compare the monetary balance and scope without that background status. - t.assertDeepEqual( - balanceAfter.balances.map(({ refreshInfo, ...balance }) => balance), - balanceBefore.balances.map(({ refreshInfo, ...balance }) => balance), - ); + t.assertDeepEqual(balanceAfter.balances, balanceBefore.balances); const txs = await walletClient.call(WalletApiOperation.GetTransactions, { sort: "stable-ascending", diff --git a/packages/taler-harness/src/integrationtests/test-exchange-keys-cherrypick.ts b/packages/taler-harness/src/integrationtests/test-exchange-keys-cherrypick.ts @@ -287,10 +287,7 @@ export async function runExchangeKeysCherrypickTest( ); // Refresh estimates can change as keys are verified and time advances. // Compare the monetary balance and scope without that background status. - t.assertDeepEqual( - balanceAfter.balances.map(({ refreshInfo, ...balance }) => balance), - balanceBefore.balances.map(({ refreshInfo, ...balance }) => balance), - ); + t.assertDeepEqual(balanceAfter.balances, balanceBefore.balances); const txs = await walletClient.call(WalletApiOperation.GetTransactions, { sort: "stable-ascending", diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -474,7 +474,9 @@ export interface WalletRefreshInfo { } export interface WalletBalance { - /** DD71 expiry information and conditional cost of keeping this balance. */ + /** True when this scope contains funds at risk of expiration. */ + hasExpirationRisk?: boolean; + /** Kept for clients that also support earlier core versions. */ refreshInfo?: WalletRefreshInfo; scopeInfo: ScopeInfo; available: AmountString; diff --git a/packages/taler-wallet-core/src/autoRefresh.test.ts b/packages/taler-wallet-core/src/autoRefresh.test.ts @@ -33,6 +33,7 @@ import { computeAnnualRefreshBoundAsync, DAY_MS as day, evaluateAutoRefresh, + expirationRisk, refreshLifetime, selectAutoRefreshOutputs, } from "./autoRefresh.js"; @@ -110,6 +111,24 @@ test("adaptive emergency threshold prevents repeated short-lived emergency refre assert.equal(evaluate(output, [output]).rule, undefined); }); +test("balance risk begins after the emergency threshold and ends at deposit expiry", () => { + const old = denom("old", 10); + old.stampExpireWithdraw = stamp(nowMs - 30 * day); + const deposit = nowMs + 10 * day; + assert.deepEqual(expirationRisk(old, nowMs), { + atRisk: false, + nextCheck: nowMs + 1, + }); + assert.deepEqual(expirationRisk(old, nowMs + 1), { + atRisk: true, + nextCheck: deposit, + }); + assert.deepEqual(expirationRisk(old, deposit), { + atRisk: false, + nextCheck: Infinity, + }); +}); + test("rule 2 requires actual zero total loss and confirmed external power", () => { const old = denom("old", 179), output = denom("output", 400); diff --git a/packages/taler-wallet-core/src/autoRefresh.ts b/packages/taler-wallet-core/src/autoRefresh.ts @@ -54,6 +54,21 @@ export function refreshLifetime( return { deposit, emergency, urgent: deposit - emergency / 10 }; } +/** A malformed lifetime warrants a warning until the deposit deadline passes. */ +export function expirationRisk( + denom: WalletDenomination, + now: number, +): { atRisk: boolean; nextCheck: number } { + const deposit = stampMs(denom, "stampExpireDeposit"); + if (deposit <= now) return { atRisk: false, nextCheck: Infinity }; + const life = refreshLifetime(denom); + if (life) { + const start = Math.floor(deposit - life.emergency) + 1; + if (now < start) return { atRisk: false, nextCheck: start }; + } + return { atRisk: true, nextCheck: deposit }; +} + export interface AutoRefreshOutputPlan extends DenomSelectionState { minOutputExpiry: number; nextRelevantDate: number; diff --git a/packages/taler-wallet-core/src/balance.ts b/packages/taler-wallet-core/src/balance.ts @@ -64,7 +64,7 @@ import { watchForCacheInvalidation, WalletCacheInvalidation, } from "./db/shared.js"; -import { readRefreshBalanceInfo } from "./refreshBalance.js"; +import { readExpirationRiskFlags } from "./refreshBalance.js"; import { AmountJson, AmountLike, @@ -611,7 +611,7 @@ class BalancesStore { export async function getBalancesInsideTransaction( wex: Pick<WalletExecutionContext, "ws">, tx: WalletDbTransaction, - includeRefreshInfo = true, + includeExpirationRisk = true, ): Promise<BalancesResponse> { const scopeResolver = await BalanceScopeResolver.load(tx); const balanceStore: BalancesStore = new BalancesStore(wex, scopeResolver); @@ -1001,59 +1001,15 @@ export async function getBalancesInsideTransaction( } const response = balanceStore.toBalancesResponse(haveProdBalance); - if (includeRefreshInfo) await readRefreshBalanceInfo(tx, response); - const scenario = wex.ws.devExperimentState.refreshScenario; - if (wex.ws.config?.testing?.devModeActive && scenario) { - const b = response.balances[0]; - if (b) { - const date = Math.floor(Date.now() / 1000); - const amount = b.available; - b.refreshInfo = { - risks: - scenario === "risk" - ? [ - { - exchangeBaseUrl: "https://exchange.example/", - exchangeMasterPub: "demo", - amount, - earliestDepositExpiration: { t_s: date + 7 * 86400 }, - reason: "no-replacement", - }, - ] - : [], - recoveries: - scenario === "recovered" - ? [ - { - warningId: "dd71-experiment", - exchangeBaseUrl: "https://exchange.example/", - exchangeMasterPub: "demo", - amount, - oldDepositExpiration: { t_s: date + 7 * 86400 }, - newDepositExpiration: { t_s: date + 740 * 86400 }, - nextRelevantDate: { t_s: date + 650 * 86400 }, - }, - ] - : [], - annualCostBound: - scenario === "cost-unavailable" - ? { - status: "unavailable", - horizonDays: 365, - projection: "stable-current-offerings", - reasons: ["unrefreshable-denomination"], - } - : { - status: "available", - horizonDays: 365, - projection: "stable-current-offerings", - amount: Amounts.stringify( - Amounts.zeroOfCurrency(b.scopeInfo.currency), - ), - }, - }; - } - } + if (includeExpirationRisk) await readExpirationRiskFlags(tx, response); + if ( + wex.ws.config?.testing?.devModeActive && + wex.ws.devExperimentState.refreshScenario && + response.balances[0] && + includeExpirationRisk + ) + response.balances[0].hasExpirationRisk = + wex.ws.devExperimentState.refreshScenario === "risk"; return response; } diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -2206,6 +2206,7 @@ export enum ConfigRecordKey { CoinAvailabilityVersion = "coinAvailabilityVersion", DonauConfig = "donauConfig", RefreshBalanceGeneration = "refreshBalanceGeneration", + RefreshReportGenerations = "refreshReportGenerations", RefreshBalance = "refreshBalance", } @@ -2245,7 +2246,7 @@ export interface WalletBackupConfState { * the wallet. */ /** Persisted derived data. Generation changes atomically with its inputs. */ -export interface WalletRefreshBalance { +export interface LegacyRefreshBalance { version: 1; generation: string; computedAt: number; @@ -2259,6 +2260,27 @@ export interface WalletRefreshBalance { >; } +export interface ExpirationRiskCache { + version: 2; + generation: string; + computedAt: number; + nextCheck: number; + relevantMasters: string[]; + riskScopes: string[]; +} +export type WalletRefreshBalance = LegacyRefreshBalance | ExpirationRiskCache; + +export function expirationRiskScopes( + cache: WalletRefreshBalance | undefined, +): string[] { + if (!cache) return []; + if (cache.version === 2) return cache.riskScopes; + return Object.entries(cache.scopes) + .filter(([, scope]) => scope.info.risks.length > 0) + .map(([key]) => key) + .sort(); +} + export type ConfigRecord = | { key: ConfigRecordKey.WalletBackupState; @@ -2273,6 +2295,10 @@ export type ConfigRecord = | { key: ConfigRecordKey.RecoupRecoveryVersion; value: number } | { key: ConfigRecordKey.DonauConfig; value: DonauConfig } | { key: ConfigRecordKey.RefreshBalanceGeneration; value: string } + | { + key: ConfigRecordKey.RefreshReportGenerations; + value: { general: string; masters: Record<string, string> }; + } | { key: ConfigRecordKey.RefreshBalance; value: WalletRefreshBalance }; export enum RecoupOperationStatus { diff --git a/packages/taler-wallet-core/src/db/shared.ts b/packages/taler-wallet-core/src/db/shared.ts @@ -38,6 +38,7 @@ import { WalletDbTransaction } from "./transaction.js"; import { ConfigRecordKey, ConfigRecord, + expirationRiskScopes, PurchaseStatus, WalletExchangeEntry, WalletOperationRetry, @@ -262,6 +263,7 @@ export interface WalletCacheInvalidation { dirty: boolean; terminalPaymentIds?: Set<string>; refreshBalanceDirty?: boolean; + denominationMasters?: Set<string>; } /** Persist invalidation in the same transaction as the changed inputs. */ @@ -269,11 +271,36 @@ export async function persistRefreshBalanceInvalidation( tx: WalletDbTransaction, flag: WalletCacheInvalidation, ): Promise<void> { - if (flag.refreshBalanceDirty) - await tx.upsertConfig({ - key: ConfigRecordKey.RefreshBalanceGeneration, - value: encodeCrock(getRandomBytes(16)), - }); + if (!flag.refreshBalanceDirty && !flag.denominationMasters?.size) return; + const version = encodeCrock(getRandomBytes(16)); + // Changes to holdings, scope membership and refresh history affect the whole + // report. Verification writes only affect scopes holding that signing key. + let generations = { general: version, masters: {} as Record<string, string> }; + if (!flag.refreshBalanceDirty && flag.denominationMasters?.size) { + const saved = (await tx.getConfig(ConfigRecordKey.RefreshBalance))?.value; + const generation = + (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ?? + ""; + if ( + saved?.version === 2 && + saved.generation === generation && + !saved.relevantMasters.some((m) => flag.denominationMasters!.has(m)) + ) + return; + generations = (await tx.getConfig(ConfigRecordKey.RefreshReportGenerations)) + ?.value ?? { general: generation, masters: {} }; + for (const master of flag.denominationMasters) + generations.masters[master] = version; + flag.refreshBalanceDirty = true; + } + await tx.upsertConfig({ + key: ConfigRecordKey.RefreshReportGenerations, + value: generations, + }); + await tx.upsertConfig({ + key: ConfigRecordKey.RefreshBalanceGeneration, + value: version, + }); } /** Scheduling metadata is not an input to exchange summaries or renewal costs. */ @@ -388,7 +415,16 @@ export function watchForCacheInvalidation<T extends WalletDbTransaction>( } if (prop === "upsertConfig" && balance) { const record = args[0] as ConfigRecord; - return write(record.key === ConfigRecordKey.RefreshBalance || record.key === ConfigRecordKey.RefreshBalanceGeneration); + if (record.key !== ConfigRecordKey.RefreshBalance) + return write(false); + return target + .getConfig(record.key) + .then((old) => + write( + JSON.stringify(expirationRiskScopes(old?.value)) !== + JSON.stringify(expirationRiskScopes(record.value)), + ), + ); } if (prop === "upsertPurchase") { const purchase = args[0] as WalletPurchase; @@ -420,8 +456,13 @@ export function watchForCacheInvalidation<T extends WalletDbTransaction>( if ( typeof prop === "string" && REFRESH_BALANCE_INVALIDATING_METHODS.has(prop) - ) - flag.refreshBalanceDirty = true; + ) { + if (prop === "upsertDenomination" || prop === "deleteDenomination") { + (flag.denominationMasters ??= new Set()).add( + (args[0] as { exchangeMasterPub: string }).exchangeMasterPub, + ); + } else flag.refreshBalanceDirty = true; + } if ( prop === "upsertOperationRetry" || prop === "deleteOperationRetry" diff --git a/packages/taler-wallet-core/src/dev-experiments.ts b/packages/taler-wallet-core/src/dev-experiments.ts @@ -25,7 +25,8 @@ * Imports. */ -import { NotificationType } from "@gnu-taler/taler-util"; +import { getBalancesInsideTransaction } from "./balance.js"; +import { readExpirationRiskFlags } from "./refreshBalance.js"; import { AbsoluteTime, AmountString, @@ -36,6 +37,7 @@ import { Logger, MerchantContractTermsV0, MerchantContractVersion, + NotificationType, PeerContractTerms, parseScopeInfoShort, RefreshReason, @@ -168,9 +170,27 @@ export interface DevExperimentState { }; } -/** - * Apply a dev experiment to the wallet database / state. - */ +export async function setRefreshScenario( + wex: WalletExecutionContext, + scenario: DevExperimentState["refreshScenario"], +) { + await wex.runWalletDbTx(async (tx) => { + const previous = wex.ws.devExperimentState.refreshScenario; + if (previous === scenario) return; + const balances = await getBalancesInsideTransaction(wex, tx, false); + await readExpirationRiskFlags(tx, balances); + const first = balances.balances[0]; + const visibleRisk = (override: DevExperimentState["refreshScenario"]) => + override ? override === "risk" : !!first?.hasExpirationRisk; + tx.scheduleOnCommit(() => { + wex.ws.devExperimentState.refreshScenario = scenario; + wex.ws.observations.invalidate(); + if (first && visibleRisk(previous) !== visibleRisk(scenario)) + wex.ws.notify({ type: NotificationType.BalanceChange }); + }); + }); +} + export async function applyDevExperiment( wex: WalletExecutionContext, uri: string, @@ -192,14 +212,12 @@ export async function applyDevExperiment( case "dd71-cost-unavailable": case "dd71-clear": { const scenario = parsedUri.devExperimentId.slice(5); - wex.ws.devExperimentState.refreshScenario = + await setRefreshScenario( + wex, scenario === "clear" ? undefined - : (scenario as "risk" | "recovered" | "cost-unavailable"); - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: "dd71-experiment", - }); + : (scenario as DevExperimentState["refreshScenario"]), + ); return; } case "start-block-refresh": { diff --git a/packages/taler-wallet-core/src/refreshBalance.test.ts b/packages/taler-wallet-core/src/refreshBalance.test.ts @@ -14,452 +14,241 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; import { AbsoluteTime, - BalancesResponse, - ScopeType, - stringifyScopeInfo, - encodeCrock, + CancellationToken, DenomKeyType, + encodeCrock, NotificationType, + SetTimeoutTimerAPI, + TalerPreciseTimestamp, WalletNotification, } from "@gnu-taler/taler-util"; +import { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronousWorkerFactoryPlain.js"; +import { + InternalWalletState, + getNormalWalletExecutionContext, + applyRunConfigDefaults, +} from "./wallet.js"; +import { runnerFactories } from "./db/testing/runners.js"; import { - ConfigRecordKey, - WalletRefreshBalance, - WalletDenomination, DenominationVerificationStatus, + ExchangeEntryDbRecordStatus, + ExchangeEntryDbUpdateStatus, + timestampPreciseToDb, timestampProtocolToDb, + WalletDenomination, + ConfigRecordKey, } from "./db/records.js"; -import { WalletDbTransaction } from "./db/transaction.js"; -import { runnerFactories } from "./db/testing/runners.js"; -import { - persistRefreshBalanceInvalidation, - watchForCacheInvalidation, - WalletCacheInvalidation, -} from "./db/shared.js"; -import { - publishRefreshBalance, - readRefreshBalanceInfo, - loadRefreshBalanceSnapshot, - processRefreshBalance, -} from "./refreshBalance.js"; -import { addRefreshBalanceInfo } from "./autoRefreshBalance.js"; -import { WalletExecutionContext } from "./wallet.js"; +import { processRefreshBalance } from "./refreshBalance.js"; +import { markExchangeUsed, startUpdateExchangeEntry } from "./exchanges.js"; +import { getBalances } from "./balance.js"; +import { TaskSchedulerImpl } from "./shepherd.js"; -function fixture() { - const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); - const response: BalancesResponse = { - haveProdBalance: true, - balances: [ - { - scopeInfo: { - type: ScopeType.Exchange, - currency: "TEST", - url: "https://exchange/", - }, - available: "TEST:10", - pendingIncoming: "TEST:0", - pendingOutgoing: "TEST:0", - flags: [], - }, - ], - }; - const saved: WalletRefreshBalance = { - version: 1, - generation: "", - computedAt: now, - nextCheck: now + 60_000, - scopes: { - [stringifyScopeInfo(response.balances[0].scopeInfo)]: { - available: "TEST:10", - info: { - risks: [ - { - exchangeBaseUrl: "https://exchange/", - exchangeMasterPub: "master", - amount: "TEST:2", - reason: "pending", - earliestDepositExpiration: { - t_s: Math.floor(now / 1000) + 86400, - }, - }, - ], - recoveries: [], - annualCostBound: { - status: "available", - amount: "TEST:0.1", - horizonDays: 365, - projection: "stable-current-offerings", - }, - }, - }, - }, - }; - return { saved, response }; +class QuietScheduler extends TaskSchedulerImpl { + override startShepherdTask() {} } - for (const makeRunner of runnerFactories) { - test(`${makeRunner.name}: renewal publication notifies only for visible changes`, async () => { - const runner = await makeRunner(); - const notifications: WalletNotification[] = []; - runner.setNotificationSink((n) => notifications.push(n)); - try { - const { saved, response } = fixture(); - const scope = stringifyScopeInfo(response.balances[0].scopeInfo); - // A refreshed generation with no balances has no visible effect. - await runner.runReadWriteTx((tx) => - publishRefreshBalance(tx, { ...saved, scopes: {} }), - ); - notifications.length = 0; - await runner.runReadWriteTx(async (tx) => { - await tx.upsertConfig({ - key: ConfigRecordKey.RefreshBalanceGeneration, - value: "next", - }); - await publishRefreshBalance(tx, { - ...saved, - generation: "next", - scopes: {}, - }); - }); - assert.equal(notifications.length, 0); - - saved.generation = "next"; - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)); - assert.equal(notifications.length, 1); - notifications.length = 0; - // Advancing the cache's scheduling timestamps is not a balance change. - await runner.runReadWriteTx((tx) => - publishRefreshBalance(tx, { - ...saved, - nextCheck: saved.nextCheck + 60000, - }), + test( + makeRunner.name + + ": unrelated denomination validation is silent until the new exchange becomes visible", + { timeout: 15000 }, + async () => { + const runner = await makeRunner(); + const ws = new InternalWalletState( + runner, + () => + ({ + fetch: async () => { + throw Error("unexpected network access"); + }, + }) as import("@gnu-taler/taler-util/http").HttpRequestLibrary, + new SetTimeoutTimerAPI(), + new SynchronousCryptoWorkerFactoryPlain(), ); - assert.equal(notifications.length, 0); - - // Invalidating and restoring the same cost does change the visible - // "checking" status, so the frontend still needs an invalidation. - await runner.runReadWriteTx((tx) => - tx.upsertConfig({ - key: ConfigRecordKey.RefreshBalanceGeneration, - value: "newer", + ws.initWithConfig( + applyRunConfigDefaults({ + lazyTaskLoop: true, + testing: { skipDefaults: true }, }), ); - await runner.runReadWriteTx((tx) => readRefreshBalanceInfo(tx, response)); - assert.equal( - response.balances[0].refreshInfo?.annualCostBound.status, - "unavailable", - ); - saved.generation = "newer"; - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)); - assert.equal(notifications.length, 1); - notifications.length = 0; - await runner.runReadWriteTx((tx) => readRefreshBalanceInfo(tx, response)); - assert.equal( - response.balances[0].refreshInfo?.annualCostBound.status, - "available", + ws.taskScheduler = new QuietScheduler(ws); + const wex = getNormalWalletExecutionContext( + ws, + CancellationToken.CONTINUE, + undefined, + { observe() {} }, ); - - // Warnings can change without any monetary amount changing. - saved.scopes[scope].info.risks = []; - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)); - assert.equal(notifications.length, 1); - assert.equal(notifications[0].type, NotificationType.BalanceChange); - notifications.length = 0; - - // A calculation that still reports "checking" must not notify merely - // because its inputs were invalidated again. - saved.scopes[scope].info.annualCostBound = { - status: "unavailable", - horizonDays: 365, - projection: "stable-current-offerings", - reasons: ["checking"], + const events: WalletNotification[] = []; + ws.addPublicNotificationListener((n) => events.push(n)); + const settle = () => new Promise((resolve) => setTimeout(resolve, 15)); + const changes = () => + events.filter((n) => n.type === NotificationType.BalanceChange); + const now = + Math.floor(AbsoluteTime.toStampMs(AbsoluteTime.now()) / 1000) * 1000; + const day = 86400000; + const stamp = (ms: number) => timestampProtocolToDb({ t_s: ms / 1000 }); + const denom: WalletDenomination = { + exchangeBaseUrl: "https://exchange/", + exchangeMasterPub: encodeCrock(new Uint8Array(32)), + denomPubHash: encodeCrock(new Uint8Array(64)), + denomPub: { + cipher: DenomKeyType.Rsa, + rsa_public_key: "dummy", + age_mask: 0, + }, + currency: "TEST", + value: "TEST:1", + stampStart: stamp(now - 640 * day), + stampExpireWithdraw: stamp(now - 630 * day), + stampExpireDeposit: stamp(now + 120 * day), + stampExpireLegal: stamp(now + 150 * day), + fees: { + feeWithdraw: "TEST:0", + feeRefresh: "TEST:0", + feeDeposit: "TEST:0", + feeRefund: "TEST:0", + }, + isOffered: false, + isLost: false, + isRevoked: false, + masterSig: encodeCrock(new Uint8Array(64)), + verificationStatus: DenominationVerificationStatus.VerifiedGood, }; - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)); - notifications.length = 0; - saved.generation = "again"; - await runner.runReadWriteTx(async (tx) => { - await tx.upsertConfig({ - key: ConfigRecordKey.RefreshBalanceGeneration, - value: saved.generation, - }); - await publishRefreshBalance(tx, saved); - }); - assert.equal(notifications.length, 0); - // Removing the last reported scope also invalidates an existing view. - await runner.runReadWriteTx((tx) => - publishRefreshBalance(tx, { ...saved, scopes: {} }), - ); - assert.equal(notifications.length, 1); - } finally { - await runner.close(); - } - }); - test(`${makeRunner.name}: renewal cache survives reopening; invalidation is atomic and rejects stale publication`, async () => { - const dir = mkdtempSync(join(tmpdir(), "refresh-balance-")); - const file = join(dir, "wallet.sqlite3"); - let runner = await makeRunner(file); - try { - const { saved, response } = fixture(); - const status = () => - response.balances[0].refreshInfo?.annualCostBound.status; - assert.equal( - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)), - true, - ); - await runner.close(); - runner = await makeRunner(file); - await runner.runReadWriteTx((tx) => readRefreshBalanceInfo(tx, response)); - assert.equal(status(), "available"); - await assert.rejects( - runner.runReadWriteTx(async (tx) => { - const flag: WalletCacheInvalidation = { dirty: false }; - await watchForCacheInvalidation(tx, flag).deleteRefreshGroup( - "missing", + try { + const stage = "https://stage.example/"; + const stageMaster = encodeCrock(new Uint8Array(32).fill(4)); + const timestamp = timestampPreciseToDb(TalerPreciseTimestamp.now()); + await wex.runWalletDbTx(async (tx) => { + await tx.upsertDenomination(denom); + await tx.upsertCoinAvailability({ + ...denom, + maxAge: 0, + visibleCoinCount: 20, + freshCoinCount: 20, + hasFreshCoins: 1, + }); + }); + await processRefreshBalance(wex); + const before = await getBalances(wex); + assert.equal(before.balances[0].available, "TEST:20"); + assert.equal(before.balances[0].hasExpirationRisk, false); + assert.ok(!("refreshInfo" in before.balances[0])); + await settle(); + events.length = 0; + await startUpdateExchangeEntry(wex, stage); + await settle(); + assert.deepEqual( + events + .filter((n) => n.type === NotificationType.ExchangeStateTransition) + .map((n) => n.causeHint), + ["creation"], + ); + await wex.runWalletDbTx(async (tx) => { + await tx.upsertExchangeDetails({ + exchangeBaseUrl: stage, + masterPublicKey: stageMaster, + currency: "CHF", + auditors: [], + protocolVersionRange: "34:0:8", + bankComplianceLanguage: undefined, + defaultPeerPushExpiration: undefined, + tinyAmount: "CHF:0.01", + reserveClosingDelay: { d_us: 1 }, + globalFees: [], + wireInfo: { accounts: [], feesForType: {} }, + }); + await tx.upsertExchange({ + baseUrl: stage, + entryStatus: ExchangeEntryDbRecordStatus.Ephemeral, + updateStatus: ExchangeEntryDbUpdateStatus.Ready, + detailsPointer: { + currency: "CHF", + masterPublicKey: stageMaster, + updateClock: timestamp, + }, + tosCurrentEtag: undefined, + tosAcceptedEtag: undefined, + tosAcceptedTimestamp: undefined, + lastUpdate: undefined, + lastKeysEtag: undefined, + nextUpdateStamp: timestamp, + nextRefreshCheckStamp: timestamp, + }); + }); + await processRefreshBalance(wex); + const generation = async () => + wex.runWalletDbTx( + async (tx) => + (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration)) + ?.value, ); - await persistRefreshBalanceInvalidation(tx, flag); - throw Error("rollback changed inputs and generation"); - }), - /rollback/, - ); - await runner.runReadWriteTx((tx) => readRefreshBalanceInfo(tx, response)); - assert.equal(status(), "available"); - await runner.runReadWriteTx(async (tx) => { - const flag: WalletCacheInvalidation = { dirty: false }; - await watchForCacheInvalidation(tx, flag).deleteRefreshGroup("missing"); - await persistRefreshBalanceInvalidation(tx, flag); - }); - assert.equal( - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)), - false, - ); - await runner.runReadWriteTx((tx) => readRefreshBalanceInfo(tx, response)); - assert.equal(status(), "unavailable"); - assert.equal(response.balances[0].refreshInfo?.risks.length, 1); - const generation = await runner.runReadWriteTx( - async (tx) => - (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))!.value, - ); - assert.equal( - await runner.runReadWriteTx((tx) => - publishRefreshBalance(tx, { ...saved, generation }), - ), - true, - ); - await runner.runReadWriteTx((tx) => readRefreshBalanceInfo(tx, response)); - assert.equal(status(), "available"); - } finally { - await runner.close(); - rmSync(dir, { recursive: true, force: true }); - } - }); - - test(`${makeRunner.name}: renewal calculation uses a detached snapshot`, async () => { - const runner = await makeRunner(); - const wex = { - ws: { devExperimentState: {} }, - runWalletDbTx: runner.runReadWriteTx.bind(runner), - } as unknown as WalletExecutionContext; - const now = - Math.floor(AbsoluteTime.toStampMs(AbsoluteTime.now()) / 1000) * 1000; - const day = 86400000; - const stamp = (ms: number) => timestampProtocolToDb({ t_s: ms / 1000 }); - const denom: WalletDenomination = { - exchangeBaseUrl: "https://exchange/", - exchangeMasterPub: encodeCrock(new Uint8Array(32)), - denomPubHash: encodeCrock(new Uint8Array(64)), - denomPub: { - cipher: DenomKeyType.Rsa, - rsa_public_key: "dummy", - age_mask: 0, - }, - currency: "TEST", - value: "TEST:1", - stampStart: stamp(now - 640 * day), - stampExpireWithdraw: stamp(now - 630 * day), - stampExpireDeposit: stamp(now + 90 * day + 5000), - stampExpireLegal: stamp(now + 100 * day), - fees: { - feeWithdraw: "TEST:0", - feeRefresh: "TEST:0", - feeDeposit: "TEST:0", - feeRefund: "TEST:0", - }, - isOffered: false, - isLost: false, - isRevoked: false, - masterSig: encodeCrock(new Uint8Array(64)), - verificationStatus: DenominationVerificationStatus.VerifiedGood, - }; - await runner.runReadWriteTx(async (tx) => { - await tx.upsertDenomination(denom); - await tx.upsertCoinAvailability({ - ...denom, - maxAge: 0, - freshCoinCount: 1, - visibleCoinCount: 1, - hasFreshCoins: 1, - }); - }); - const snapshot = await runner.runReadWriteTx((tx) => - loadRefreshBalanceSnapshot(wex, tx), - ); - assert.equal(snapshot.nextCheck, now + 5001); - await runner.close(); - await addRefreshBalanceInfo( - wex, - snapshot.source, - snapshot.response, - snapshot.exchanges, - snapshot.availability, - snapshot.resolve, - snapshot.now, - ); - assert.equal(snapshot.response.balances[0].available, "TEST:1"); - assert.equal( - snapshot.response.balances[0].refreshInfo?.annualCostBound.status, - "unavailable", - ); - }); -} - -test("cached reporting has fixed reads, with no eager fallback on a miss or expired result", async () => { - const { saved, response } = fixture(); - let record: WalletRefreshBalance | undefined = saved; - const calls: string[] = []; - const tx = new Proxy( - {}, - { - get: (_, method) => { - assert.equal( - method, - "getConfig", - "only persisted cache reads are allowed", + const gen = await generation(); + for (let i = 0; i < 16; i++) { + await wex.runWalletDbTx((tx) => + tx.upsertDenomination({ + ...denom, + exchangeBaseUrl: stage, + exchangeMasterPub: stageMaster, + denomPubHash: encodeCrock(new Uint8Array(64).fill(i + 1)), + currency: "CHF", + value: "CHF:1", + fees: { + feeRefresh: "CHF:0", + feeDeposit: "CHF:0", + feeRefund: "CHF:0", + feeWithdraw: "CHF:0", + }, + }), + ); + } + assert.equal(await generation(), gen); + assert.deepEqual(await getBalances(wex), before); + await settle(); + assert.deepEqual(changes(), []); + await assert.rejects( + wex.runWalletDbTx(async (tx) => { + await markExchangeUsed(tx, stage); + throw Error("rollback"); + }), + /rollback/, ); - return async (key: string) => { - calls.push(key); - return key === ConfigRecordKey.RefreshBalance && record - ? { key, value: record } - : undefined; - }; - }, - }, - ) as WalletDbTransaction; - for (let i = 0; i < 20; i++) await readRefreshBalanceInfo(tx, response); - assert.equal(calls.length, 40); - record = { ...saved, nextCheck: 0 }; - await readRefreshBalanceInfo(tx, response); - assert.equal( - response.balances[0].refreshInfo?.annualCostBound.status, - "unavailable", - ); - assert.equal(response.balances[0].refreshInfo?.risks.length, 1); - record = undefined; - await readRefreshBalanceInfo(tx, response); - assert.deepEqual(response.balances[0].refreshInfo?.risks, []); - assert.equal( - response.balances[0].refreshInfo?.annualCostBound.status, - "unavailable", - ); -}); - -test("a current persisted result lets the background task sleep after restart", async () => { - const { saved } = fixture(); - const tx = new Proxy( - {}, - { - get: (_, method) => { + await wex.runWalletDbTx((tx) => markExchangeUsed(tx, stage)); + await processRefreshBalance(wex); + await settle(); + assert.equal(changes().length, 1); + assert.equal(changes()[0].hintTransactionId, undefined); + const after = await getBalances(wex); + assert.ok(after.haveProdBalance); assert.equal( - method, - "getConfig", - "a current cache needs no snapshot scan", + after.balances.find((b) => b.scopeInfo.currency === "CHF")?.available, + "CHF:0", ); - return async (key: string) => - key === ConfigRecordKey.RefreshBalance - ? { key, value: saved } - : undefined; - }, - }, - ) as WalletDbTransaction; - const wex = { - runWalletDbTx: async (f: (tx: WalletDbTransaction) => unknown) => f(tx), - } as unknown as WalletExecutionContext; - await processRefreshBalance(wex); -}); - -test("cache writes and maintenance retries do not invalidate the renewal report", async () => { - const { saved } = fixture(); - const flag: WalletCacheInvalidation = { dirty: false }; - const tx = watchForCacheInvalidation( - { - upsertConfig: async () => {}, - deleteOperationRetry: async () => {}, - getOperationRetry: async () => undefined, - } as unknown as WalletDbTransaction, - flag, - ); - await tx.upsertConfig({ key: ConfigRecordKey.RefreshBalance, value: saved }); - await tx.deleteOperationRetry("refresh-balance:"); - assert.equal(flag.refreshBalanceDirty, undefined); - await tx.deleteOperationRetry("exchange-auto-refresh:https://exchange/"); - assert.equal(flag.refreshBalanceDirty, undefined); -}); - -for (const makeRunner of runnerFactories) { - test(`${makeRunner.name}: publication notifies when checking finishes, including unchanged results`, async () => { - const runner = await makeRunner(); - const notifications: unknown[] = []; - runner.setNotificationSink((n) => notifications.push(n)); - try { - const { saved, response } = fixture(); - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)); - assert.equal(notifications.length, 1); - await runner.runReadWriteTx((tx) => publishRefreshBalance(tx, saved)); - assert.equal(notifications.length, 1); - await runner.runReadWriteTx(async (tx) => { - await tx.upsertConfig({ - key: ConfigRecordKey.RefreshBalanceGeneration, - value: "changed", - }); - await readRefreshBalanceInfo(tx, response); - }); - assert.equal( - response.balances[0].refreshInfo?.annualCostBound.status, - "unavailable", - ); - await runner.runReadWriteTx(async (tx) => { - assert.equal(await publishRefreshBalance(tx, saved), false); + events.length = 0; + await wex.runWalletDbTx((tx) => + tx.upsertDenomination({ + ...denom, + stampExpireDeposit: stamp(now + 7 * day), + }), + ); + await processRefreshBalance(wex); assert.equal( - await publishRefreshBalance(tx, { ...saved, generation: "changed" }), + (await getBalances(wex)).balances.find( + (b) => b.scopeInfo.currency === "TEST", + )?.hasExpirationRisk, true, ); - await readRefreshBalanceInfo(tx, response); - }); - assert.equal( - response.balances[0].refreshInfo?.annualCostBound.status, - "available", - ); - assert.equal(notifications.length, 2); - await runner.runReadWriteTx((tx) => - publishRefreshBalance(tx, { - ...saved, - generation: "changed", - computedAt: saved.nextCheck, - nextCheck: saved.nextCheck + 60_000, - }), - ); - assert.equal( - notifications.length, - 3, - "time-based recomputation also finishes checking", - ); - } finally { - await runner.close(); - } - }); + await settle(); + assert.equal(changes().length, 1); + events.length = 0; + await wex.runWalletDbTx((tx) => tx.upsertDenomination(denom)); + await processRefreshBalance(wex); + await settle(); + assert.equal(changes().length, 1); + } finally { + await ws.shutdown(); + } + }, + ); } diff --git a/packages/taler-wallet-core/src/refreshBalance.ts b/packages/taler-wallet-core/src/refreshBalance.ts @@ -15,325 +15,108 @@ import { AbsoluteTime, BalancesResponse, - canonicalJson, - NotificationType, + Amounts, stringifyScopeInfo, - WalletRefreshInfo, } from "@gnu-taler/taler-util"; import { ConfigRecordKey, RefreshCoinStatus, RefreshOperationStatus, - WalletRefreshBalance, - timestampAbsoluteFromDb, + ExpirationRiskCache, + expirationRiskScopes, } from "./db/records.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { WalletExecutionContext, denomRefKey } from "./wallet.js"; -import { - BalanceScopeResolver, - getBalancesInsideTransaction, -} from "./balance.js"; -import { - addRefreshBalanceInfo, - RefreshBalanceSource, -} from "./autoRefreshBalance.js"; -import { - DAY_MS, - refreshLifetime, - stampMs, - unavailableAnnualBound, -} from "./autoRefresh.js"; -import { TaskIdentifiers, TaskRunResult } from "./common.js"; - -/** Project the cache exactly as a balance reader would see it. */ -function visibleRefreshInfo( - saved: WalletRefreshBalance | undefined, - generation: string, - now: number, - scopeKey: string, - available: string, -): WalletRefreshInfo { - const current = - saved?.version === 1 && - saved.generation === generation && - saved.computedAt <= now && - saved.nextCheck > now; - const cached = saved?.version === 1 ? saved.scopes[scopeKey] : undefined; - return { - // Retain known warnings during recomputation. Expired coins use the - // ordinary expiry indication, even if the maintenance task is delayed. - risks: - cached?.info.risks.filter( - (r) => - AbsoluteTime.toStampMs( - AbsoluteTime.fromProtocolTimestamp(r.earliestDepositExpiration), - ) > now, - ) ?? [], - recoveries: cached?.info.recoveries ?? [], - annualCostBound: - current && cached?.available === available - ? cached.info.annualCostBound - : unavailableAnnualBound("checking"), - }; -} +import { BalanceScopeResolver } from "./balance.js"; +import { DAY_MS, expirationRisk } from "./autoRefresh.js"; +import { TaskRunResult } from "./common.js"; -/** Balance reads do no denomination selection or history scans. */ -export async function readRefreshBalanceInfo( +/** Keep published risk flags stable while a new snapshot is being calculated. */ +export async function readExpirationRiskFlags( tx: WalletDbTransaction, response: BalancesResponse, ): Promise<void> { const saved = (await tx.getConfig(ConfigRecordKey.RefreshBalance))?.value; - const generation = - (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ?? ""; - const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); + const scopes = new Set(expirationRiskScopes(saved)); for (const balance of response.balances) { - balance.refreshInfo = visibleRefreshInfo( - saved, - generation, - now, + balance.hasExpirationRisk = scopes.has( stringifyScopeInfo(balance.scopeInfo), - balance.available, ); } } -/** Capture database inputs once; all selection and projection runs afterward. */ -export async function loadRefreshBalanceSnapshot( - wex: WalletExecutionContext, - tx: WalletDbTransaction, -) { - const now = AbsoluteTime.now(), - nowMs = AbsoluteTime.toStampMs(now); - const generation = - (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ?? ""; - const response = await getBalancesInsideTransaction(wex, tx, false); - const exchanges = await tx.getExchanges(); - const availability = await tx.getVisibleCoinAvailabilities(); - const groups = await tx.listAllRefreshGroups(); - const pending = groups.filter( - (g) => g.operationStatus !== RefreshOperationStatus.Finished, - ); - const coins = await tx.getCoinsByPubs([ - ...new Set( - pending.flatMap((g) => - g.oldCoinPubs.filter( - (_, i) => g.statusPerCoin[i] !== RefreshCoinStatus.Finished, - ), - ), - ), - ]); - const coinsByPub = new Map(coins.map((c) => [c.coinPub, c])); - const denoms = new Map( - (await tx.getDenominationsByRefs([...availability, ...coins])).map((d) => [ - denomRefKey(d), - d, - ]), - ); - const masters = new Set([...denoms.values()].map((d) => d.exchangeMasterPub)); - const byMaster = new Map( - await Promise.all( - [...masters].map( - async (master) => - [ - master, - exchanges.some((e) => e.detailsPointer?.masterPublicKey === master) - ? await tx.getDenominationsByMasterPub(master) - : [], - ] as const, - ), - ), - ); - for (const ds of byMaster.values()) - for (const d of ds) denoms.set(denomRefKey(d), d); - const retryIds = new Set([ - ...pending.map((g) => `refresh:${g.refreshGroupId}`), - ...exchanges.map((e) => - TaskIdentifiers.forExchangeAutoRefreshFromUrl(e.baseUrl), - ), - ]); - const retries = new Map( - await Promise.all( - [...retryIds].map( - async (id) => [id, await tx.getOperationRetry(id)] as const, - ), - ), - ); - const resolver = await BalanceScopeResolver.load(tx); - const scopeKey = ( - url: string, - currency: string, - master?: string, - hash?: string, - ) => JSON.stringify([url, currency, master, hash]); - const scopes = new Map< - string, - Awaited<ReturnType<BalanceScopeResolver["resolveScope"]>> - >(); - for (const d of [...availability, ...denoms.values()]) { - scopes.set( - scopeKey( - d.exchangeBaseUrl, - d.currency, - d.exchangeMasterPub, - d.denomPubHash, - ), - await resolver.resolveScope( - d.exchangeBaseUrl, - d.currency, - d.exchangeMasterPub, - d.denomPubHash, - ), - ); - } - for (const g of groups) { - const n = g.autoRefresh?.recovery; - if (n) - scopes.set( - scopeKey(n.exchangeBaseUrl, g.currency, n.exchangeMasterPub), - await resolver.resolveScope( - n.exchangeBaseUrl, - g.currency, - n.exchangeMasterPub, - ), - ); - } - const source: RefreshBalanceSource = { - getDenominationsByRefs: async (refs) => - refs.flatMap((r) => { - const d = denoms.get(denomRefKey(r)); - return d ? [d] : []; - }), - getDenominationsByMasterPub: async (master) => byMaster.get(master) ?? [], - getCoinsByPubs: async (pubs) => - pubs.flatMap((p) => { - const c = coinsByPub.get(p); - return c ? [c] : []; - }), - getOperationRetry: async (id) => retries.get(id), - listAllRefreshGroups: async () => groups, - }; - let nextCheck = nowMs + DAY_MS; - const boundary = (at: number) => { - if (at > nowMs) nextCheck = Math.min(nextCheck, at); - }; - for (const e of exchanges) - if (e.lastUpdate != null) - boundary( - AbsoluteTime.toStampMs(timestampAbsoluteFromDb(e.lastUpdate)) + DAY_MS, - ); - for (const d of denoms.values()) { - boundary(stampMs(d, "stampStart")); - boundary(stampMs(d, "stampExpireWithdraw")); - const life = refreshLifetime(d); - if (life) { - boundary(Math.floor(life.deposit - life.emergency) + 1); - boundary(life.deposit); - } - } - return { - generation, - response, - exchanges, - availability, - source, - now, - nextCheck, - resolve: async ( - url: string, - currency: string, - master?: string, - hash?: string, - ) => { - const scope = scopes.get(scopeKey(url, currency, master, hash)); - if (!scope) throw Error("missing scope in refresh balance snapshot"); - return scope; - }, - }; -} - -/** Compare the generation in the publishing transaction to reject stale work. */ -export async function publishRefreshBalance( - tx: WalletDbTransaction, - value: WalletRefreshBalance, -): Promise<boolean> { - const generation = - (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ?? ""; - if (generation !== value.generation) return false; - const previous = (await tx.getConfig(ConfigRecordKey.RefreshBalance))?.value; - const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); - // Generation and scheduling changes alone are not balance changes. Still - // notify when publication replaces a reader's "checking" status, even if - // the newly computed cost equals the previously cached cost. - if ( - canonicalJson(previous?.scopes ?? {}) !== canonicalJson(value.scopes) || - Object.entries(value.scopes).some( - ([key, scope]) => - canonicalJson( - visibleRefreshInfo(previous, generation, now, key, scope.available), - ) !== - canonicalJson( - visibleRefreshInfo(value, generation, now, key, scope.available), - ), - ) - ) { - tx.notify({ - type: NotificationType.BalanceChange, - isInternal: true, - }); - } - await tx.upsertConfig({ key: ConfigRecordKey.RefreshBalance, value }); - return true; -} - +/** The expiry flag depends only on held coins and their deposit lifetimes. */ export async function processRefreshBalance( wex: WalletExecutionContext, ): Promise<TaskRunResult> { - const current = await wex.runWalletDbTx(async (tx) => { + return wex.runWalletDbTx(async (tx) => { + const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); const saved = (await tx.getConfig(ConfigRecordKey.RefreshBalance))?.value; const generation = (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ?? ""; - return saved?.version === 1 && + if ( + saved?.version === 2 && saved.generation === generation && - saved.computedAt <= AbsoluteTime.toStampMs(AbsoluteTime.now()) && - saved.nextCheck > AbsoluteTime.toStampMs(AbsoluteTime.now()) - ? saved - : undefined; - }); - if (current) - return TaskRunResult.runAgainAt( - AbsoluteTime.fromMilliseconds(current.nextCheck), + saved.computedAt <= now && + now < saved.nextCheck + ) + return TaskRunResult.runAgainAt( + AbsoluteTime.fromMilliseconds(saved.nextCheck), + ); + const available = await tx.getVisibleCoinAvailabilities(); + const pending = new Set<string>(); + for (const g of await tx.listAllRefreshGroups()) { + if (g.operationStatus === RefreshOperationStatus.Finished) continue; + g.oldCoinPubs.forEach((pub, i) => { + if ( + g.statusPerCoin[i] !== RefreshCoinStatus.Finished && + !Amounts.isZero(g.inputPerCoin[i]) + ) + pending.add(pub); + }); + } + const coins = await tx.getCoinsByPubs([...pending]); + const denoms = await tx.getDenominationsByRefs([...available, ...coins]); + const masters = [ + ...new Set([...available, ...coins].map((d) => d.exchangeMasterPub)), + ]; + const held = new Set( + [ + ...available.filter( + (a) => a.freshCoinCount > 0 && !Amounts.isZero(a.value), + ), + ...coins, + ].map(denomRefKey), ); - const snapshot = await wex.runWalletDbTx((tx) => - loadRefreshBalanceSnapshot(wex, tx), - ); - // This source contains only detached records and in-memory lookups. The - // expensive calculation does not hold a database transaction open. - await addRefreshBalanceInfo( - wex, - snapshot.source, - snapshot.response, - snapshot.exchanges, - snapshot.availability, - snapshot.resolve, - snapshot.now, - ); - const value: WalletRefreshBalance = { - version: 1, - generation: snapshot.generation, - computedAt: AbsoluteTime.toStampMs(snapshot.now), - nextCheck: snapshot.nextCheck, - scopes: Object.fromEntries( - snapshot.response.balances.map((b) => [ - stringifyScopeInfo(b.scopeInfo), - { available: b.available, info: b.refreshInfo! }, - ]), - ), - }; - const saved = await wex.runWalletDbTx((tx) => - publishRefreshBalance(tx, value), - ); - return saved - ? TaskRunResult.runAgainAt(AbsoluteTime.fromMilliseconds(value.nextCheck)) - : TaskRunResult.runAgainAfter({ seconds: 1 }); + const resolver = await BalanceScopeResolver.load(tx); + const risks = new Set<string>(); + let nextCheck = now + DAY_MS; + for (const d of denoms) { + if (!held.has(denomRefKey(d))) continue; + const risk = expirationRisk(d, now); + nextCheck = Math.min(nextCheck, risk.nextCheck); + if (!risk.atRisk) continue; + risks.add( + stringifyScopeInfo( + await resolver.resolveScope( + d.exchangeBaseUrl, + d.currency, + d.exchangeMasterPub, + d.denomPubHash, + ), + ), + ); + } + const value: ExpirationRiskCache = { + version: 2, + generation, + computedAt: now, + nextCheck, + relevantMasters: masters, + riskScopes: [...risks].sort(), + }; + await tx.upsertConfig({ key: ConfigRecordKey.RefreshBalance, value }); + return TaskRunResult.runAgainAt(AbsoluteTime.fromMilliseconds(nextCheck)); + }); } diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -315,7 +315,7 @@ import { getWalletDbDumpBackend } from "./db/migration/import.js"; import { WalletDbTransaction } from "./db/transaction.js"; import { checkDepositGroup, createDepositGroup } from "./deposits.js"; import { getSerializedWalletDiagnostics } from "./diagnostics.js"; -import { applyDevExperiment } from "./dev-experiments.js"; +import { applyDevExperiment, setRefreshScenario } from "./dev-experiments.js"; import { handleGetDonau, handleGetDonauStatements, @@ -1609,22 +1609,20 @@ export async function handleDismissWalletWarning( wex.ws.config.testing.devModeActive && req.warningId === "dd71-experiment" ) { - wex.ws.devExperimentState.refreshScenario = undefined; - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: "dd71-experiment", - }); + if (wex.ws.devExperimentState.refreshScenario === "recovered") + await setRefreshScenario(wex, undefined); return {}; } await wex.runWalletDbTx(async (tx) => { const group = await tx.getRefreshGroup(req.warningId); - if (!group?.autoRefresh?.recovery || !group.timestampFinished) return; + if ( + !group?.autoRefresh?.recovery || + group.autoRefresh.dismissed || + !group.timestampFinished + ) + return; group.autoRefresh.dismissed = true; await tx.upsertRefreshGroup(group); - tx.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: `refresh:${group.refreshGroupId}`, - }); }); return {}; } diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -101,6 +101,7 @@ import { import { WalletDbHandle } from "./db/handle.js"; import { persistRefreshBalanceInvalidation, + type WalletCacheInvalidation, } from "./db/shared.js"; import { WalletCoinAvailabilityRef, @@ -970,7 +971,7 @@ async function runWalletDbTx<T>( // the wallet's caches stale. Acted on only after a successful commit: a // transaction that rolls back changed nothing, and an attempt that is about // to be retried resets the flag so a discarded write cannot carry over. - const dirty = { + const dirty: WalletCacheInvalidation & { terminalPaymentIds: Set<string> } = { dirty: false, refreshBalanceDirty: false, terminalPaymentIds: new Set<string>(), @@ -981,6 +982,7 @@ async function runWalletDbTx<T>( return await handleTxRetries(wex, async () => { dirty.dirty = false; dirty.refreshBalanceDirty = false; + dirty.denominationMasters?.clear(); dirty.terminalPaymentIds.clear(); const location = getCallerInfo(); wex.oc.observe({ @@ -1882,10 +1884,7 @@ export class InternalWalletState { notify(n: WalletNotification): void { logger.trace(`Notification: ${j2s(n)}`); - if ( - n.type === NotificationType.BalanceChange && - n.hintTransactionId !== "refresh-balance" - ) { + if (n.type === NotificationType.BalanceChange) { for (const id of this.taskScheduler.getActiveTasks()) { if (id.startsWith(`${PendingTaskType.ExchangeAutoRefresh}:`)) this.taskScheduler.startShepherdTask(id);