Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions watcher/src/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { BusyError, DryRunStore, FileStore, type Store } from './store.ts';
import type { Email } from './email.ts';
import type { Network, Telegram } from './telegram.ts';
import { ConfigError, type FetchFn, type Log, errText } from './util.ts';
import { Watcher, parseState } from './watcher.ts';
import { type ChainNow, type ProxyKinds, Watcher, parseState } from './watcher.ts';

type Known = {
delay: string;
Expand Down Expand Up @@ -117,6 +117,8 @@ export class AllWatcher {
calls: PollCalls = { scan: {}, vaults: {}, read: 0 };
private opts: AllOptions;
private probe: Watcher;
/** Shared by every read of this network, across polls: proxy code does not change. */
private proxyKinds: ProxyKinds = new Map();
private store: Store;
private clock: () => number;

Expand All @@ -126,7 +128,7 @@ export class AllWatcher {
this.clock = opts.clock ?? Date.now;
this.store = opts.store ?? (cfg.dryRun ? new DryRunStore(new FileStore(cfg.stateDir)) : new FileStore(cfg.stateDir));
// Reads the chain only. It never loads or saves a state.
this.probe = new Watcher({ ...cfg, dryRun: true }, { fetch: opts.fetch, log: opts.log });
this.probe = new Watcher({ ...cfg, dryRun: true }, { fetch: opts.fetch, log: opts.log, proxyKinds: this.proxyKinds });
this.log = this.probe.log;
}

Expand Down Expand Up @@ -287,24 +289,24 @@ export class AllWatcher {
redact(msg: string): string { return this.probe.redact(msg); }

/** The watcher of one vault: the same code as for a single vault. */
private watcherOf(vault: string, known: Known, rpcCounts?: RpcCounts): Watcher {
private watcherOf(vault: string, known: Known, rpcCounts?: RpcCounts, chain?: ChainNow): Watcher {
return new Watcher({ ...this.cfg, chronobox: vault, delay: known.delay }, {
fetch: this.opts.fetch, telegram: this.opts.telegram, email: this.opts.email, store: this.store, key: vault, where: `The state of ${vault}`,
log: (m) => this.log(`${vault.slice(0, 10)}: ${m}`), rpcCounts,
log: (m) => this.log(`${vault.slice(0, 10)}: ${m}`), rpcCounts, chain, proxyKinds: this.proxyKinds,
});
}

/**
* Reads one vault and sends its alerts. False if the chain could not be read. Null if a question of the bot reads
* this vault right now: that read sends its alerts, and this poll goes on with the next vault.
*/
private async look(vault: string, known: Known, calls: PollCalls): Promise<boolean | null> {
private async look(vault: string, known: Known, calls: PollCalls, chain: ChainNow | undefined): Promise<boolean | null> {
// Saved before the read: if the function is killed during it, this vault goes to the back of the line, and it
// cannot block every poll after this one.
known.lookedAt = this.clock();
delete known.waitingSince;
await this.save();
const w = this.watcherOf(vault, known, calls.vaults);
const w = this.watcherOf(vault, known, calls.vaults, chain);
let ok: boolean;
try {
ok = await this.store.lock(`vault:${vault}`, () => { calls.read++; return w.poll(); }, { waitMs: 0 });
Expand All @@ -324,7 +326,7 @@ export class AllWatcher {
* and the queue is saved with the new lastBlock before any of them is checked: a search is never done twice, also
* when the function is killed afterwards. Returns the vaults to look at now.
*/
private async scan(probe: Watcher): Promise<{ chainId: number; now: number; touched: Set<string> }> {
private async scan(probe: Watcher): Promise<{ chain: ChainNow; now: number; touched: Set<string> }> {
const s = this.state;
const rpc = probe.rpc;
const chainId = Number(await rpc.call('eth_chainId'));
Expand Down Expand Up @@ -377,7 +379,7 @@ export class AllWatcher {
s.chainId = chainId;
s.lastBlock = to;
this.announce();
return { chainId, now, touched };
return { chain: { chainId, head, timestamp: BigInt(block.timestamp) }, now, touched };
}

/**
Expand Down Expand Up @@ -441,10 +443,13 @@ export class AllWatcher {
// Counted apart from the bot's questions, which use this.probe at the same time.
const calls: PollCalls = { scan: {}, vaults: {}, read: 0 };
this.calls = calls;
const probe = new Watcher({ ...this.cfg, dryRun: true }, { fetch: this.opts.fetch, log: this.opts.log, rpcCounts: calls.scan });
const probe = new Watcher({ ...this.cfg, dryRun: true }, { fetch: this.opts.fetch, log: this.opts.log, rpcCounts: calls.scan, proxyKinds: this.proxyKinds });
// What the search read of the chain. The reads of the vaults use it: one head for the whole poll.
let chain: ChainNow | undefined;
try {
const r = await this.scan(probe);
now = r.now;
chain = r.chain;
for (const vault of r.touched) s.vaults[vault].active = true;
await this.save();
} catch (e) {
Expand Down Expand Up @@ -485,7 +490,7 @@ export class AllWatcher {
// answers anything. Its readers are told (Watcher), and it waits longer each time, while the chain can be read.
let read: boolean | null = false;
try {
read = await this.look(vault, known, calls);
read = await this.look(vault, known, calls, chain);
} catch (e) {
this.log(`${vault}: ${errText(e)}`);
}
Expand Down
22 changes: 19 additions & 3 deletions watcher/src/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,26 @@ export type WatcherOptions = {
where?: string;
/** Counts the requests to the RPC here. */
rpcCounts?: RpcCounts;
/** The chain as the poll of the network read it a moment ago. Then a read does not ask for it again. */
chain?: ChainNow;
/** Which addresses are proxies of the Delay or of Roles, kept by the caller across reads. Proxy code does not change. */
proxyKinds?: ProxyKinds;
};

/** The network and its head block, with the time of that block. */
export type ChainNow = { chainId: number; head: number; timestamp: bigint };

export type ProxyKinds = Map<string, 'delay' | 'roles'>;

export class Watcher {
cfg: Config;
rpc: Rpc;
state: State = emptyState();
log: Log;
fetchFn: FetchFn;
private blockTs = new Map<number, bigint>();
private proxyKinds = new Map<string, 'delay' | 'roles'>();
private proxyKinds: ProxyKinds;
private chain?: ChainNow;
private telegram?: Telegram;
private email?: Email;
private store: Store;
Expand All @@ -154,6 +164,8 @@ export class Watcher {
this.telegram = opts.telegram;
this.email = opts.email;
this.fetchFn = opts.fetch ?? fetch;
this.proxyKinds = opts.proxyKinds ?? new Map();
this.chain = opts.chain;
this.rpc = new Rpc(cfg.rpcUrls, this.fetchFn, 20000,
cfg.rpcServiceKey ? { host: cfg.rpcServiceHost, key: cfg.rpcServiceKey } : undefined, opts.rpcCounts);
const out = opts.log ?? defaultLog;
Expand Down Expand Up @@ -470,11 +482,15 @@ export class Watcher {
private async observe(): Promise<void> {
this.blockTs.clear();
const s = this.state;
const chainId = Number(await this.rpc.call('eth_chainId'));
// The head that the poll of the network read, unless this vault was read at a later block since (a question of the
// bot can read it during the poll): its state must never go back to an older block.
const polled = this.chain && (s.lastBlock === undefined || this.chain.head >= s.lastBlock) ? this.chain : undefined;
const chainId = polled ? polled.chainId : Number(await this.rpc.call('eth_chainId'));
if (s.chainId !== undefined && s.chainId !== chainId) {
throw new ConfigError(`The RPC is on chain ${chainId}, but this watcher watches chain ${s.chainId}. Check RPC_URL.`);
}
const head = Number(await this.rpc.call('eth_blockNumber'));
const head = polled ? polled.head : Number(await this.rpc.call('eth_blockNumber'));
if (polled) this.blockTs.set(head, polled.timestamp);
const now = await this.timestampOf(head);
const tag = hex(head);
const delay = s.delay ?? (await this.resolveDelay(tag));
Expand Down
3 changes: 3 additions & 0 deletions watcher/test/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ test('a poll counts its requests to the RPC: the search apart from the reads of
assert.equal(calls.read, 1, 'the vault with the new request is read');
assert.ok(calls.scan > 0 && calls.vaults > 0, JSON.stringify(calls));
assert.equal(calls.scan + calls.vaults, rpcSeen.length, 'every request the RPC got is counted, once');
// The read of the vault takes the network and the head from the search of the poll.
assert.equal(rpcSeen.filter((m) => m === 'eth_chainId').length, 1);
assert.equal(rpcSeen.filter((m) => m === 'eth_blockNumber').length, 1);
const line = logs.find((l) => l.includes(': rpc: '));
assert.ok(line, logs.join('\n'));
assert.match(line, new RegExp(`: rpc: ${rpcSeen.length} requests \\(search ${calls.scan}, 1 Chronobox read ${calls.vaults}\\): `));
Expand Down
25 changes: 25 additions & 0 deletions watcher/test/watcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,31 @@ test('first start reports Watching and treats queued items as known', async () =
assert.deepEqual(hooks().map((h) => h.json.event), ['ready']);
});

test('a read with the head of the poll does not ask for the chain again, and never goes back to an older block', async () => {
chain.enqueue(OWNER_WALLET, ONE_HALF_ETH);
await watcher().poll();
chain.mine(120n);
const method = (m: string) => chain.calls.filter((c) => c === m).length;

// The head that the poll of the network read: the read takes it, and the time of its block.
chain.calls.length = 0;
const fresh = new Watcher(config(), { log: (m) => logs.push(m), chain: { chainId: 1, head: chain.head, timestamp: chain.now() } });
assert.equal(await fresh.poll(), true);
assert.equal(method('eth_chainId'), 0);
assert.equal(method('eth_blockNumber'), 0);
assert.equal(method('eth_getBlockByNumber'), 0);
assert.equal(fresh.state.lastBlock, chain.head);

// A head from before the last read of this vault (a question of the bot read it during the poll): read again.
const last = chain.head;
chain.mine(120n);
chain.calls.length = 0;
const stale = new Watcher(config(), { log: (m) => logs.push(m), chain: { chainId: 1, head: last - 5, timestamp: chain.ts(last - 5) } });
assert.equal(await stale.poll(), true);
assert.equal(method('eth_blockNumber'), 1);
assert.equal(stale.state.lastBlock, chain.head, 'read at the head of now, not at the older one');
});

test('a queued native withdrawal produces one Queued alert, then Ready once', async () => {
const w = watcher();
await w.poll();
Expand Down
Loading