@aztec/aztec-node 0.0.1-commit.9372f48 → 0.0.1-commit.949a33fd8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,11 @@
1
1
  import type { EpochCache } from '@aztec/epoch-cache';
2
2
  import { createLogger } from '@aztec/foundation/log';
3
- import type { DataStoreConfig } from '@aztec/kv-store/config';
4
3
  import { createStore } from '@aztec/kv-store/lmdb-v2';
5
4
  import type { P2PClient } from '@aztec/p2p';
6
5
  import type { L2BlockSource } from '@aztec/stdlib/block';
6
+ import type { ChainConfig } from '@aztec/stdlib/config';
7
7
  import type { SlasherConfig } from '@aztec/stdlib/interfaces/server';
8
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
8
9
 
9
10
  import type { SentinelConfig } from './config.js';
10
11
  import { Sentinel } from './sentinel.js';
@@ -14,7 +15,7 @@ export async function createSentinel(
14
15
  epochCache: EpochCache,
15
16
  archiver: L2BlockSource,
16
17
  p2p: P2PClient,
17
- config: SentinelConfig & DataStoreConfig & SlasherConfig,
18
+ config: SentinelConfig & DataStoreConfig & SlasherConfig & Pick<ChainConfig, 'l1ChainId' | 'l1Contracts'>,
18
19
  logger = createLogger('node:sentinel'),
19
20
  ): Promise<Sentinel | undefined> {
20
21
  if (!config.sentinelEnabled) {
@@ -21,7 +21,9 @@ import {
21
21
  type L2BlockStreamEventHandler,
22
22
  getAttestationInfoFromPublishedCheckpoint,
23
23
  } from '@aztec/stdlib/block';
24
+ import type { ChainConfig } from '@aztec/stdlib/config';
24
25
  import { getEpochAtSlot, getSlotRangeForEpoch, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
26
+ import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
25
27
  import type {
26
28
  SingleValidatorStats,
27
29
  ValidatorStats,
@@ -36,6 +38,23 @@ import EventEmitter from 'node:events';
36
38
 
37
39
  import { SentinelStore } from './store.js';
38
40
 
41
+ export type SentinelRuntimeConfig = Pick<
42
+ SlasherConfig,
43
+ 'slashInactivityTargetPercentage' | 'slashInactivityPenalty' | 'slashInactivityConsecutiveEpochThreshold'
44
+ > &
45
+ Pick<ChainConfig, 'l1ChainId' | 'l1Contracts'>;
46
+
47
+ /** Maps a validator status to its category: proposer or attestation. */
48
+ function statusToCategory(status: ValidatorStatusInSlot): ValidatorStatusType {
49
+ switch (status) {
50
+ case 'attestation-sent':
51
+ case 'attestation-missed':
52
+ return 'attestation';
53
+ default:
54
+ return 'proposer';
55
+ }
56
+ }
57
+
39
58
  export class Sentinel extends (EventEmitter as new () => WatcherEmitter) implements L2BlockStreamEventHandler, Watcher {
40
59
  protected runningPromise: RunningPromise;
41
60
  protected blockStream!: L2BlockStream;
@@ -54,10 +73,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
54
73
  protected archiver: L2BlockSource,
55
74
  protected p2p: P2PClient,
56
75
  protected store: SentinelStore,
57
- protected config: Pick<
58
- SlasherConfig,
59
- 'slashInactivityTargetPercentage' | 'slashInactivityPenalty' | 'slashInactivityConsecutiveEpochThreshold'
60
- >,
76
+ protected config: SentinelRuntimeConfig,
61
77
  protected logger = createLogger('node:sentinel'),
62
78
  ) {
63
79
  super();
@@ -66,6 +82,13 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
66
82
  this.runningPromise = new RunningPromise(this.work.bind(this), logger, interval);
67
83
  }
68
84
 
85
+ private getSignatureContext(): CoordinationSignatureContext {
86
+ return {
87
+ chainId: this.config.l1ChainId,
88
+ rollupAddress: this.config.l1Contracts.rollupAddress,
89
+ };
90
+ }
91
+
69
92
  public updateConfig(config: Partial<SlasherConfig>) {
70
93
  this.config = { ...this.config, ...config };
71
94
  }
@@ -77,7 +100,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
77
100
 
78
101
  /** Loads initial slot and initializes blockstream. We will not process anything at or before the initial slot. */
79
102
  protected async init() {
80
- this.initialSlot = this.epochCache.getEpochAndSlotNow().slot;
103
+ this.initialSlot = this.epochCache.getSlotNow();
81
104
  const startingBlock = BlockNumber(await this.archiver.getBlockNumber());
82
105
  this.logger.info(`Starting validator sentinel with initial slot ${this.initialSlot} and block ${startingBlock}`);
83
106
  this.blockStream = new L2BlockStream(this.archiver, this.l2TipsStore, this, this.logger, { startingBlock });
@@ -106,7 +129,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
106
129
  this.slotNumberToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, {
107
130
  checkpointNumber: checkpoint.checkpoint.number,
108
131
  archive: checkpoint.checkpoint.archive.root.toString(),
109
- attestors: getAttestationInfoFromPublishedCheckpoint(checkpoint)
132
+ attestors: getAttestationInfoFromPublishedCheckpoint(checkpoint, this.getSignatureContext())
110
133
  .filter(a => a.status === 'recovered-from-signature')
111
134
  .map(a => a.address!),
112
135
  });
@@ -128,15 +151,15 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
128
151
  return;
129
152
  }
130
153
  const blockNumber = event.block.number;
131
- const block = await this.archiver.getL2Block(blockNumber);
132
- if (!block) {
133
- this.logger.error(`Failed to get block ${blockNumber}`, { block });
154
+ const header = await this.archiver.getBlockHeader(blockNumber);
155
+ if (!header) {
156
+ this.logger.error(`Failed to get block header ${blockNumber}`);
134
157
  return;
135
158
  }
136
159
 
137
160
  // TODO(palla/slash): We should only be computing proven performance if this is
138
161
  // a full proof epoch and not a partial one, otherwise we'll end up with skewed stats.
139
- const epoch = getEpochAtSlot(block.header.getSlot(), this.epochCache.getL1Constants());
162
+ const epoch = getEpochAtSlot(header.getSlot(), this.epochCache.getL1Constants());
140
163
  this.logger.debug(`Computing proven performance for epoch ${epoch}`);
141
164
  const performance = await this.computeProvenPerformance(epoch);
142
165
  this.logger.info(`Computed proven performance for epoch ${epoch}`, performance);
@@ -147,7 +170,11 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
147
170
 
148
171
  protected async computeProvenPerformance(epoch: EpochNumber): Promise<ValidatorsEpochPerformance> {
149
172
  const [fromSlot, toSlot] = getSlotRangeForEpoch(epoch, this.epochCache.getL1Constants());
150
- const { committee } = await this.epochCache.getCommittee(fromSlot);
173
+ const { committee, isEscapeHatchOpen } = await this.epochCache.getCommittee(fromSlot);
174
+ if (isEscapeHatchOpen) {
175
+ this.logger.info(`Skipping proven performance for epoch ${epoch} - escape hatch is open`);
176
+ return {};
177
+ }
151
178
  if (!committee) {
152
179
  this.logger.trace(`No committee found for slot ${fromSlot}`);
153
180
  return {};
@@ -204,7 +231,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
204
231
  // Check that we have at least requiredConsecutiveEpochs and that all of them are above the inactivity threshold
205
232
  return pastEpochs
206
233
  .slice(0, requiredConsecutiveEpochs)
207
- .every(p => p.missed / p.total >= this.config.slashInactivityTargetPercentage);
234
+ .every(p => (p.total === 0 ? false : p.missed / p.total >= this.config.slashInactivityTargetPercentage));
208
235
  }
209
236
 
210
237
  protected async handleProvenPerformance(epoch: EpochNumber, performance: ValidatorsEpochPerformance) {
@@ -213,7 +240,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
213
240
  }
214
241
 
215
242
  const inactiveValidators = getEntries(performance)
216
- .filter(([_, { missed, total }]) => missed / total >= this.config.slashInactivityTargetPercentage)
243
+ .filter(([_, { missed, total }]) => total > 0 && missed / total >= this.config.slashInactivityTargetPercentage)
217
244
  .map(([address]) => address);
218
245
 
219
246
  this.logger.debug(`Found ${inactiveValidators.length} inactive validators in epoch ${epoch}`, {
@@ -249,7 +276,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
249
276
  * and we don't have that data if we were offline during the period.
250
277
  */
251
278
  public async work() {
252
- const { slot: currentSlot } = this.epochCache.getEpochAndSlotNow();
279
+ const currentSlot = this.epochCache.getSlotNow();
253
280
  try {
254
281
  // Manually sync the block stream to ensure we have the latest data.
255
282
  // Note we never `start` the blockstream, so it loops at the same pace as we do.
@@ -294,9 +321,9 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
294
321
  return false;
295
322
  }
296
323
 
297
- const archiverSlot = await this.archiver.getL2SlotNumber();
298
- if (archiverSlot === undefined || archiverSlot < targetSlot) {
299
- this.logger.debug(`Waiting for archiver to sync with L2 slot ${targetSlot}`, { archiverSlot, targetSlot });
324
+ const syncedSlot = await this.archiver.getSyncedL2SlotNumber();
325
+ if (syncedSlot === undefined || syncedSlot < targetSlot) {
326
+ this.logger.debug(`Waiting for archiver to sync with L2 slot ${targetSlot}`, { syncedSlot, targetSlot });
300
327
  return false;
301
328
  }
302
329
 
@@ -316,7 +343,12 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
316
343
  * and updates overall stats.
317
344
  */
318
345
  protected async processSlot(slot: SlotNumber) {
319
- const { epoch, seed, committee } = await this.epochCache.getCommittee(slot);
346
+ const { epoch, seed, committee, isEscapeHatchOpen } = await this.epochCache.getCommittee(slot);
347
+ if (isEscapeHatchOpen) {
348
+ this.logger.info(`Skipping slot ${slot} at epoch ${epoch} - escape hatch is open`);
349
+ this.lastProcessedSlot = slot;
350
+ return;
351
+ }
320
352
  if (!committee || committee.length === 0) {
321
353
  this.logger.trace(`No committee found for slot ${slot} at epoch ${epoch}`);
322
354
  this.lastProcessedSlot = slot;
@@ -336,16 +368,16 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
336
368
 
337
369
  // Check if there is an L2 block in L1 for this L2 slot
338
370
 
339
- // Here we get all attestations for the block mined at the given slot,
340
- // or all attestations for all proposals in the slot if no block was mined.
371
+ // Here we get all checkpoint attestations for the checkpoint at the given slot,
372
+ // or all checkpoint attestations for all proposals in the slot if no checkpoint was mined.
341
373
  // We gather from both p2p (contains the ones seen on the p2p layer) and archiver
342
- // (contains the ones synced from mined blocks, which we may have missed from p2p).
343
- const block = this.slotNumberToCheckpoint.get(slot);
344
- const p2pAttested = await this.p2p.getCheckpointAttestationsForSlot(slot, block?.archive);
374
+ // (contains the ones synced from mined checkpoints, which we may have missed from p2p).
375
+ const checkpoint = this.slotNumberToCheckpoint.get(slot);
376
+ const p2pAttested = await this.p2p.getCheckpointAttestationsForSlot(slot, checkpoint?.archive);
345
377
  // Filter out attestations with invalid signatures
346
378
  const p2pAttestors = p2pAttested.map(a => a.getSender()).filter((s): s is EthAddress => s !== undefined);
347
379
  const attestors = new Set(
348
- [...p2pAttestors.map(a => a.toString()), ...(block?.attestors.map(a => a.toString()) ?? [])].filter(
380
+ [...p2pAttestors.map(a => a.toString()), ...(checkpoint?.attestors.map(a => a.toString()) ?? [])].filter(
349
381
  addr => proposer.toString() !== addr, // Exclude the proposer from the attestors
350
382
  ),
351
383
  );
@@ -356,20 +388,29 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
356
388
  // But we'll leave that corner case out to reduce pressure on the node.
357
389
  // TODO(palla/slash): This breaks if a given node has more than one validator in the current committee,
358
390
  // since they will attest to their own proposal it even if it's not re-executable.
359
- const blockStatus = block ? 'mined' : attestors.size > 0 ? 'proposed' : 'missed';
360
- this.logger.debug(`Block for slot ${slot} was ${blockStatus}`, { ...block, slot });
391
+ let status: 'checkpoint-mined' | 'checkpoint-proposed' | 'checkpoint-missed' | 'blocks-missed';
392
+ if (checkpoint) {
393
+ status = 'checkpoint-mined';
394
+ } else if (attestors.size > 0) {
395
+ status = 'checkpoint-proposed';
396
+ } else {
397
+ // No checkpoint on L1 and no checkpoint attestations seen. Check if block proposals were sent for this slot.
398
+ const hasBlockProposals = await this.p2p.hasBlockProposalsForSlot(slot);
399
+ status = hasBlockProposals ? 'checkpoint-missed' : 'blocks-missed';
400
+ }
401
+ this.logger.debug(`Checkpoint status for slot ${slot}: ${status}`, { ...checkpoint, slot });
361
402
 
362
- // Get attestors that failed their duties for this block, but only if there was a block proposed
403
+ // Get attestors that failed their checkpoint attestation duties, but only if there was a checkpoint proposed or mined
363
404
  const missedAttestors = new Set(
364
- blockStatus === 'missed'
405
+ status === 'blocks-missed' || status === 'checkpoint-missed'
365
406
  ? []
366
407
  : committee.filter(v => !attestors.has(v.toString()) && !proposer.equals(v)).map(v => v.toString()),
367
408
  );
368
409
 
369
410
  this.logger.debug(`Retrieved ${attestors.size} attestors out of ${committee.length} for slot ${slot}`, {
370
- blockStatus,
411
+ status,
371
412
  proposer: proposer.toString(),
372
- ...block,
413
+ ...checkpoint,
373
414
  slot,
374
415
  attestors: [...attestors],
375
416
  missedAttestors: [...missedAttestors],
@@ -379,7 +420,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
379
420
  // Compute the status for each validator in the committee
380
421
  const statusFor = (who: `0x${string}`): ValidatorStatusInSlot | undefined => {
381
422
  if (who === proposer.toString()) {
382
- return `block-${blockStatus}`;
423
+ return status;
383
424
  } else if (attestors.has(who)) {
384
425
  return 'attestation-sent';
385
426
  } else if (missedAttestors.has(who)) {
@@ -407,7 +448,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
407
448
  ? fromEntries(await Promise.all(validators.map(async v => [v.toString(), await this.store.getHistory(v)])))
408
449
  : await this.store.getHistories();
409
450
 
410
- const slotNow = this.epochCache.getEpochAndSlotNow().slot;
451
+ const slotNow = this.epochCache.getSlotNow();
411
452
  fromSlot ??= SlotNumber(Math.max((this.lastProcessedSlot ?? slotNow) - this.store.getHistoryLength(), 0));
412
453
  toSlot ??= this.lastProcessedSlot ?? slotNow;
413
454
 
@@ -435,7 +476,7 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
435
476
  return undefined;
436
477
  }
437
478
 
438
- const slotNow = this.epochCache.getEpochAndSlotNow().slot;
479
+ const slotNow = this.epochCache.getSlotNow();
439
480
  const effectiveFromSlot =
440
481
  fromSlot ?? SlotNumber(Math.max((this.lastProcessedSlot ?? slotNow) - this.store.getHistoryLength(), 0));
441
482
  const effectiveToSlot = toSlot ?? this.lastProcessedSlot ?? slotNow;
@@ -472,14 +513,16 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
472
513
  ): ValidatorStats {
473
514
  let history = fromSlot ? allHistory.filter(h => BigInt(h.slot) >= fromSlot) : allHistory;
474
515
  history = toSlot ? history.filter(h => BigInt(h.slot) <= toSlot) : history;
475
- const lastProposal = history.filter(h => h.status === 'block-proposed' || h.status === 'block-mined').at(-1);
516
+ const lastProposal = history
517
+ .filter(h => h.status === 'checkpoint-proposed' || h.status === 'checkpoint-mined')
518
+ .at(-1);
476
519
  const lastAttestation = history.filter(h => h.status === 'attestation-sent').at(-1);
477
520
  return {
478
521
  address: EthAddress.fromString(address),
479
522
  lastProposal: this.computeFromSlot(lastProposal?.slot),
480
523
  lastAttestation: this.computeFromSlot(lastAttestation?.slot),
481
524
  totalSlots: history.length,
482
- missedProposals: this.computeMissed(history, 'block', ['block-missed']),
525
+ missedProposals: this.computeMissed(history, 'proposer', ['checkpoint-missed', 'blocks-missed']),
483
526
  missedAttestations: this.computeMissed(history, 'attestation', ['attestation-missed']),
484
527
  history,
485
528
  };
@@ -487,10 +530,12 @@ export class Sentinel extends (EventEmitter as new () => WatcherEmitter) impleme
487
530
 
488
531
  protected computeMissed(
489
532
  history: ValidatorStatusHistory,
490
- computeOverPrefix: ValidatorStatusType | undefined,
533
+ computeOverCategory: ValidatorStatusType | undefined,
491
534
  filter: ValidatorStatusInSlot[],
492
535
  ) {
493
- const relevantHistory = history.filter(h => !computeOverPrefix || h.status.startsWith(computeOverPrefix));
536
+ const relevantHistory = history.filter(
537
+ h => !computeOverCategory || statusToCategory(h.status) === computeOverCategory,
538
+ );
494
539
  const filteredHistory = relevantHistory.filter(h => filter.includes(h.status));
495
540
  return {
496
541
  currentStreak: countWhile([...relevantHistory].reverse(), h => filter.includes(h.status)),
@@ -9,7 +9,7 @@ import type {
9
9
  } from '@aztec/stdlib/validators';
10
10
 
11
11
  export class SentinelStore {
12
- public static readonly SCHEMA_VERSION = 2;
12
+ public static readonly SCHEMA_VERSION = 3;
13
13
 
14
14
  // a map from validator address to their ValidatorStatusHistory
15
15
  private readonly historyMap: AztecAsyncMap<`0x${string}`, Buffer>;
@@ -86,11 +86,7 @@ export class SentinelStore {
86
86
  });
87
87
  }
88
88
 
89
- private async pushValidatorStatusForSlot(
90
- who: EthAddress,
91
- slot: SlotNumber,
92
- status: 'block-mined' | 'block-proposed' | 'block-missed' | 'attestation-sent' | 'attestation-missed',
93
- ) {
89
+ private async pushValidatorStatusForSlot(who: EthAddress, slot: SlotNumber, status: ValidatorStatusInSlot) {
94
90
  await this.store.transactionAsync(async () => {
95
91
  const currentHistory = (await this.getHistory(who)) ?? [];
96
92
  const newHistory = [...currentHistory, { slot, status }].slice(-this.config.historyLength);
@@ -149,16 +145,18 @@ export class SentinelStore {
149
145
 
150
146
  private statusToNumber(status: ValidatorStatusInSlot): number {
151
147
  switch (status) {
152
- case 'block-mined':
148
+ case 'checkpoint-mined':
153
149
  return 1;
154
- case 'block-proposed':
150
+ case 'checkpoint-proposed':
155
151
  return 2;
156
- case 'block-missed':
152
+ case 'checkpoint-missed':
157
153
  return 3;
158
154
  case 'attestation-sent':
159
155
  return 4;
160
156
  case 'attestation-missed':
161
157
  return 5;
158
+ case 'blocks-missed':
159
+ return 6;
162
160
  default: {
163
161
  const _exhaustive: never = status;
164
162
  throw new Error(`Unknown status: ${status}`);
@@ -169,15 +167,17 @@ export class SentinelStore {
169
167
  private statusFromNumber(status: number): ValidatorStatusInSlot {
170
168
  switch (status) {
171
169
  case 1:
172
- return 'block-mined';
170
+ return 'checkpoint-mined';
173
171
  case 2:
174
- return 'block-proposed';
172
+ return 'checkpoint-proposed';
175
173
  case 3:
176
- return 'block-missed';
174
+ return 'checkpoint-missed';
177
175
  case 4:
178
176
  return 'attestation-sent';
179
177
  case 5:
180
178
  return 'attestation-missed';
179
+ case 6:
180
+ return 'blocks-missed';
181
181
  default:
182
182
  throw new Error(`Unknown status: ${status}`);
183
183
  }