@lodestar/beacon-node 1.51.0-dev.a877514e67 → 1.51.0-dev.aa1ecb7c18

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.
Files changed (132) hide show
  1. package/lib/api/impl/validator/index.d.ts +6 -0
  2. package/lib/api/impl/validator/index.d.ts.map +1 -1
  3. package/lib/api/impl/validator/index.js +38 -25
  4. package/lib/api/impl/validator/index.js.map +1 -1
  5. package/lib/chain/blocks/importExecutionPayload.d.ts +2 -10
  6. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  7. package/lib/chain/blocks/importExecutionPayload.js +2 -14
  8. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  9. package/lib/chain/blocks/payloadEnvelopeProcessor.d.ts +10 -7
  10. package/lib/chain/blocks/payloadEnvelopeProcessor.d.ts.map +1 -1
  11. package/lib/chain/blocks/payloadEnvelopeProcessor.js +21 -16
  12. package/lib/chain/blocks/payloadEnvelopeProcessor.js.map +1 -1
  13. package/lib/chain/blocks/types.d.ts +4 -1
  14. package/lib/chain/blocks/types.d.ts.map +1 -1
  15. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  16. package/lib/chain/blocks/verifyBlock.js +17 -6
  17. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  18. package/lib/chain/blocks/verifyBlocksSignatures.d.ts.map +1 -1
  19. package/lib/chain/blocks/verifyBlocksSignatures.js +7 -5
  20. package/lib/chain/blocks/verifyBlocksSignatures.js.map +1 -1
  21. package/lib/chain/blocks/verifyPayloadsDataAvailability.d.ts.map +1 -1
  22. package/lib/chain/blocks/verifyPayloadsDataAvailability.js +1 -3
  23. package/lib/chain/blocks/verifyPayloadsDataAvailability.js.map +1 -1
  24. package/lib/chain/bls/interface.d.ts +2 -0
  25. package/lib/chain/bls/interface.d.ts.map +1 -1
  26. package/lib/chain/bls/multithread/index.d.ts.map +1 -1
  27. package/lib/chain/bls/multithread/index.js +8 -6
  28. package/lib/chain/bls/multithread/index.js.map +1 -1
  29. package/lib/chain/errors/executionPayloadEnvelope.d.ts +7 -0
  30. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  31. package/lib/chain/errors/executionPayloadEnvelope.js +1 -0
  32. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  33. package/lib/chain/validation/executionPayloadEnvelope.d.ts +6 -0
  34. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  35. package/lib/chain/validation/executionPayloadEnvelope.js +53 -0
  36. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  37. package/lib/db/flatFileStore/flatFileStore.js +5 -5
  38. package/lib/db/flatFileStore/flatFileStore.js.map +1 -1
  39. package/lib/db/flatFileStore/slotIndex.d.ts.map +1 -1
  40. package/lib/db/flatFileStore/slotIndex.js +2 -2
  41. package/lib/db/flatFileStore/slotIndex.js.map +1 -1
  42. package/lib/execution/builder/apiClient.d.ts +14 -8
  43. package/lib/execution/builder/apiClient.d.ts.map +1 -1
  44. package/lib/execution/builder/apiClient.js +12 -10
  45. package/lib/execution/builder/apiClient.js.map +1 -1
  46. package/lib/execution/builder/http.d.ts +2 -0
  47. package/lib/execution/builder/http.d.ts.map +1 -1
  48. package/lib/execution/builder/http.js +2 -0
  49. package/lib/execution/builder/http.js.map +1 -1
  50. package/lib/execution/engine/utils.d.ts.map +1 -1
  51. package/lib/execution/engine/utils.js +3 -2
  52. package/lib/execution/engine/utils.js.map +1 -1
  53. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  54. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  55. package/lib/metrics/metrics/lodestar.js +5 -0
  56. package/lib/metrics/metrics/lodestar.js.map +1 -1
  57. package/lib/metrics/server/http.js +5 -5
  58. package/lib/metrics/server/http.js.map +1 -1
  59. package/lib/network/gossip/gossipsub.d.ts +1 -0
  60. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  61. package/lib/network/gossip/gossipsub.js +10 -0
  62. package/lib/network/gossip/gossipsub.js.map +1 -1
  63. package/lib/network/libp2p/index.d.ts.map +1 -1
  64. package/lib/network/libp2p/index.js +5 -1
  65. package/lib/network/libp2p/index.js.map +1 -1
  66. package/lib/network/network.d.ts +2 -1
  67. package/lib/network/network.d.ts.map +1 -1
  68. package/lib/network/network.js +42 -17
  69. package/lib/network/network.js.map +1 -1
  70. package/lib/network/options.d.ts +2 -0
  71. package/lib/network/options.d.ts.map +1 -1
  72. package/lib/network/options.js.map +1 -1
  73. package/lib/network/peers/peerManager.d.ts.map +1 -1
  74. package/lib/network/peers/peerManager.js +28 -1
  75. package/lib/network/peers/peerManager.js.map +1 -1
  76. package/lib/network/peers/utils/prioritizePeers.d.ts +4 -1
  77. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  78. package/lib/network/peers/utils/prioritizePeers.js +8 -16
  79. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  80. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  81. package/lib/network/processor/gossipHandlers.js +24 -14
  82. package/lib/network/processor/gossipHandlers.js.map +1 -1
  83. package/lib/network/processor/index.d.ts +6 -0
  84. package/lib/network/processor/index.d.ts.map +1 -1
  85. package/lib/network/processor/index.js +29 -3
  86. package/lib/network/processor/index.js.map +1 -1
  87. package/lib/node/nodejs.d.ts +2 -0
  88. package/lib/node/nodejs.d.ts.map +1 -1
  89. package/lib/node/nodejs.js +37 -19
  90. package/lib/node/nodejs.js.map +1 -1
  91. package/lib/node/options.d.ts +3 -1
  92. package/lib/node/options.d.ts.map +1 -1
  93. package/lib/node/options.js +4 -2
  94. package/lib/node/options.js.map +1 -1
  95. package/lib/util/file.d.ts.map +1 -1
  96. package/lib/util/file.js +8 -9
  97. package/lib/util/file.js.map +1 -1
  98. package/lib/util/sszBytes.d.ts +5 -0
  99. package/lib/util/sszBytes.d.ts.map +1 -1
  100. package/lib/util/sszBytes.js +33 -0
  101. package/lib/util/sszBytes.js.map +1 -1
  102. package/package.json +16 -16
  103. package/src/api/impl/validator/index.ts +43 -29
  104. package/src/chain/blocks/importExecutionPayload.ts +2 -20
  105. package/src/chain/blocks/payloadEnvelopeProcessor.ts +32 -21
  106. package/src/chain/blocks/types.ts +4 -1
  107. package/src/chain/blocks/verifyBlock.ts +30 -16
  108. package/src/chain/blocks/verifyBlocksSignatures.ts +7 -5
  109. package/src/chain/blocks/verifyPayloadsDataAvailability.ts +1 -3
  110. package/src/chain/bls/interface.ts +2 -0
  111. package/src/chain/bls/multithread/index.ts +9 -5
  112. package/src/chain/errors/executionPayloadEnvelope.ts +8 -0
  113. package/src/chain/validation/executionPayloadEnvelope.ts +68 -1
  114. package/src/db/flatFileStore/flatFileStore.ts +7 -7
  115. package/src/db/flatFileStore/slotIndex.ts +4 -3
  116. package/src/execution/builder/apiClient.ts +16 -13
  117. package/src/execution/builder/http.ts +4 -0
  118. package/src/execution/engine/utils.ts +4 -2
  119. package/src/metrics/metrics/lodestar.ts +5 -0
  120. package/src/metrics/server/http.ts +5 -5
  121. package/src/network/gossip/gossipsub.ts +11 -0
  122. package/src/network/libp2p/index.ts +5 -1
  123. package/src/network/network.ts +40 -21
  124. package/src/network/options.ts +2 -0
  125. package/src/network/peers/peerManager.ts +27 -2
  126. package/src/network/peers/utils/prioritizePeers.ts +14 -22
  127. package/src/network/processor/gossipHandlers.ts +29 -16
  128. package/src/network/processor/index.ts +25 -3
  129. package/src/node/nodejs.ts +34 -15
  130. package/src/node/options.ts +5 -1
  131. package/src/util/file.ts +8 -9
  132. package/src/util/sszBytes.ts +40 -0
@@ -1,4 +1,4 @@
1
- import {PayloadStatus} from "@lodestar/fork-choice";
1
+ import {PayloadStatus, ProtoBlock} from "@lodestar/fork-choice";
2
2
  import {
3
3
  computeStartSlotAtEpoch,
4
4
  getExecutionPayloadEnvelopeSignatureSet,
@@ -6,9 +6,15 @@ import {
6
6
  } from "@lodestar/state-transition";
7
7
  import {gloas, ssz} from "@lodestar/types";
8
8
  import {byteArrayEquals, toRootHex} from "@lodestar/utils";
9
+ import {
10
+ getBeaconBlockRootFromExecutionPayloadEnvelopeSerialized,
11
+ getSlotFromExecutionPayloadEnvelopeSerialized,
12
+ getTransactionCountFromExecutionPayloadEnvelopeSerialized,
13
+ } from "../../util/sszBytes.js";
9
14
  import {ExecutionPayloadEnvelopeError, ExecutionPayloadEnvelopeErrorCode, GossipAction} from "../errors/index.js";
10
15
  import {IBeaconChain} from "../index.js";
11
16
  import {RegenCaller} from "../regen/index.js";
17
+ import {PayloadEnvelopeInput} from "../seenCache/seenPayloadEnvelopeInput.js";
12
18
 
13
19
  export async function validateApiExecutionPayloadEnvelope(
14
20
  chain: IBeaconChain,
@@ -24,6 +30,40 @@ export async function validateGossipExecutionPayloadEnvelope(
24
30
  return validateExecutionPayloadEnvelope(chain, executionPayloadEnvelope);
25
31
  }
26
32
 
33
+ /**
34
+ * Applies the transaction count check to the serialized envelope so that an oversized envelope is dropped
35
+ * before it is deserialized. Defers to validateGossipExecutionPayloadEnvelope if the data is malformed
36
+ * or the block is not known.
37
+ */
38
+ export function validateGossipExecutionPayloadEnvelopeSerialized(
39
+ chain: IBeaconChain,
40
+ serializedData: Uint8Array
41
+ ): void {
42
+ const blockRootHex = getBeaconBlockRootFromExecutionPayloadEnvelopeSerialized(serializedData);
43
+ const slot = getSlotFromExecutionPayloadEnvelopeSerialized(serializedData);
44
+ const transactionCount = getTransactionCountFromExecutionPayloadEnvelopeSerialized(serializedData);
45
+ if (blockRootHex === null || slot === null || transactionCount === null) {
46
+ return;
47
+ }
48
+
49
+ const block = chain.forkChoice.getBlockHexDefaultStatus(blockRootHex);
50
+ const payloadInput = chain.seenPayloadEnvelopeInputCache.get(blockRootHex);
51
+ if (!block || !payloadInput) {
52
+ return;
53
+ }
54
+
55
+ const maxTransactionCount = getMaxTransactionCount(chain, block, payloadInput);
56
+ if (BigInt(transactionCount) > maxTransactionCount) {
57
+ throw new ExecutionPayloadEnvelopeError(GossipAction.IGNORE, {
58
+ code: ExecutionPayloadEnvelopeErrorCode.TOO_MANY_TRANSACTIONS,
59
+ slot,
60
+ root: blockRootHex,
61
+ transactionCount,
62
+ maxTransactionCount: Number(maxTransactionCount),
63
+ });
64
+ }
65
+ }
66
+
27
67
  async function validateExecutionPayloadEnvelope(
28
68
  chain: IBeaconChain,
29
69
  executionPayloadEnvelope: gloas.SignedExecutionPayloadEnvelope
@@ -123,6 +163,20 @@ async function validateExecutionPayloadEnvelope(
123
163
  });
124
164
  }
125
165
 
166
+ // [IGNORE] The number of transactions is within the limit implied by the parent payload's gas limit
167
+ // TODO GLOAS: [REJECT] once https://github.com/ethereum/consensus-specs/pull/5802 is released,
168
+ // also in validateGossipExecutionPayloadEnvelopeSerialized
169
+ const maxTransactionCount = getMaxTransactionCount(chain, block, payloadInput);
170
+ if (BigInt(payload.transactions.length) > maxTransactionCount) {
171
+ throw new ExecutionPayloadEnvelopeError(GossipAction.IGNORE, {
172
+ code: ExecutionPayloadEnvelopeErrorCode.TOO_MANY_TRANSACTIONS,
173
+ slot: payload.slotNumber,
174
+ root: blockRootHex,
175
+ transactionCount: payload.transactions.length,
176
+ maxTransactionCount: Number(maxTransactionCount),
177
+ });
178
+ }
179
+
126
180
  // Get the block state to verify the builder's signature.
127
181
  const blockState = await chain.regen
128
182
  .getState(block.stateRoot, RegenCaller.validateGossipPayloadEnvelope)
@@ -154,3 +208,16 @@ async function validateExecutionPayloadEnvelope(
154
208
  });
155
209
  }
156
210
  }
211
+
212
+ /**
213
+ * The bid's gas limit is only tied to the parent payload by bid gossip, so the bound is the gas limit the
214
+ * EIP-1559 rule allows on top of the parent payload's. The bid is the only bound if that gas limit is unknown.
215
+ */
216
+ function getMaxTransactionCount(chain: IBeaconChain, block: ProtoBlock, payloadInput: PayloadEnvelopeInput): bigint {
217
+ const parentGasLimit = block.executionPayloadBlockHash === null ? 0n : BigInt(block.executionPayloadGasLimit);
218
+ const maxGasLimit =
219
+ parentGasLimit === 0n
220
+ ? payloadInput.getBid().gasLimit
221
+ : parentGasLimit + (parentGasLimit / 1024n > 1n ? parentGasLimit / 1024n : 1n) - 1n;
222
+ return maxGasLimit / BigInt(chain.config.MIN_TRANSACTION_GAS);
223
+ }
@@ -1,4 +1,4 @@
1
- import fs from "node:fs";
1
+ import {type FileHandle, open, readFile, rm} from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import {ChainForkConfig} from "@lodestar/config";
4
4
  import {ForkPostFulu} from "@lodestar/params";
@@ -172,7 +172,7 @@ export class FlatFileStore implements IFlatFileStore {
172
172
  for (const slot of slotsToPrune) {
173
173
  const release = await this.acquireMutationLock(slot);
174
174
  try {
175
- await fs.promises.rm(path.join(this.dataColumnDir, padSlot(slot)), {recursive: true, force: true});
175
+ await rm(path.join(this.dataColumnDir, padSlot(slot)), {recursive: true, force: true});
176
176
  this.slotIndex.remove(slot);
177
177
  this.metrics?.prunedDirectories.inc();
178
178
  } finally {
@@ -212,7 +212,7 @@ export class FlatFileStore implements IFlatFileStore {
212
212
 
213
213
  private async readFile(slot: Slot, rootHex: RootHex): Promise<Uint8Array | null> {
214
214
  try {
215
- return await fs.promises.readFile(this.filePath(slot, rootHex));
215
+ return await readFile(this.filePath(slot, rootHex));
216
216
  } catch (e) {
217
217
  if (!isFsNotFoundError(e)) throw e;
218
218
  return null;
@@ -224,9 +224,9 @@ export class FlatFileStore implements IFlatFileStore {
224
224
  rootHex: RootHex,
225
225
  indices: number[]
226
226
  ): Promise<(Uint8Array | undefined)[] | null> {
227
- let fd: fs.promises.FileHandle;
227
+ let fd: FileHandle;
228
228
  try {
229
- fd = await fs.promises.open(this.filePath(slot, rootHex), "r");
229
+ fd = await open(this.filePath(slot, rootHex), "r");
230
230
  } catch (e) {
231
231
  if (!isFsNotFoundError(e)) throw e;
232
232
  return null;
@@ -270,7 +270,7 @@ export class FlatFileStore implements IFlatFileStore {
270
270
  await observeFlatFileStoreOperation(this.metrics, FlatFileStoreOperation.delete, async () => {
271
271
  const release = await this.acquireMutationLock(slot);
272
272
  try {
273
- await fs.promises.rm(this.filePath(slot, rootHex), {force: true});
273
+ await rm(this.filePath(slot, rootHex), {force: true});
274
274
  } finally {
275
275
  release();
276
276
  }
@@ -294,7 +294,7 @@ function validateDcolHeader(header: DcolHeader, slot: Slot, rootHex: RootHex): v
294
294
  }
295
295
  }
296
296
 
297
- async function readExactly(fd: fs.promises.FileHandle, buffer: Uint8Array, position: number): Promise<void> {
297
+ async function readExactly(fd: FileHandle, buffer: Uint8Array, position: number): Promise<void> {
298
298
  let totalRead = 0;
299
299
  while (totalRead < buffer.length) {
300
300
  const {bytesRead} = await fd.read(buffer, totalRead, buffer.length - totalRead, position + totalRead);
@@ -1,4 +1,5 @@
1
- import fs from "node:fs";
1
+ import type {Dirent} from "node:fs";
2
+ import {readdir} from "node:fs/promises";
2
3
  import {Slot} from "@lodestar/types";
3
4
  import {isFsNotFoundError} from "./errors.js";
4
5
  import {padSlot} from "./path.js";
@@ -33,9 +34,9 @@ export class SlotIndex {
33
34
 
34
35
  async rebuildFromDisk(columnsDir: string): Promise<SlotIndexRebuildStats> {
35
36
  this.slots.clear();
36
- let entries: fs.Dirent[];
37
+ let entries: Dirent[];
37
38
  try {
38
- entries = await fs.promises.readdir(columnsDir, {withFileTypes: true});
39
+ entries = await readdir(columnsDir, {withFileTypes: true});
39
40
  } catch (e) {
40
41
  if (!isFsNotFoundError(e)) throw e;
41
42
  return {slots: 0, ignoredEntries: 0};
@@ -19,21 +19,20 @@ import {IClock} from "../../util/clock.js";
19
19
  * Additional duration to account for potential event loop lag which causes
20
20
  * builder bids to be rejected even though the response was sent in time.
21
21
  */
22
- const EVENT_LOOP_LAG_BUFFER = 250;
22
+ export const BUILDER_BID_LAG_BUFFER_MS = 250;
23
23
 
24
24
  /**
25
- * Duration given to a builder to provide a `SignedExecutionPayloadBid` before the deadline
26
- * is reached, advertised on each bid request via the `X-Timeout-Ms` header. The p2p bid is
27
- * selected after the same duration, only considering bids received up to that point.
25
+ * Default duration given to a builder to provide a `SignedExecutionPayloadBid` before the deadline
26
+ * is reached, advertised on each bid request via the `X-Timeout-Ms` header. Bids received via
27
+ * p2p are given the same time to bid up.
28
28
  */
29
- export const BUILDER_BID_DEADLINE_MS = 500;
30
-
31
- /** Local timeout for bid requests, event loop lag must not discard bids that arrived in time */
32
- export const BUILDER_BID_REQUEST_TIMEOUT_MS = BUILDER_BID_DEADLINE_MS + EVENT_LOOP_LAG_BUFFER;
29
+ export const DEFAULT_BUILDER_BID_DEADLINE_MS = 500;
33
30
 
34
31
  export type BuilderApiClientOpts = {
35
- /** Timeout for builder api requests, bid requests always use `BUILDER_BID_REQUEST_TIMEOUT_MS` */
32
+ /** Timeout for builder api requests, bid requests are bounded by `bidDeadline` instead */
36
33
  timeout?: number;
34
+ /** Time builders are given to provide a bid once block production starts, in milliseconds */
35
+ bidDeadline?: number;
37
36
  // Add User-Agent header to all requests
38
37
  userAgent?: string;
39
38
  };
@@ -69,6 +68,7 @@ export type BuilderApiBid = {
69
68
  * each block production request, clients are dialed on demand based on the entry `url`.
70
69
  */
71
70
  export class BuilderApiClient {
71
+ readonly bidDeadline: number;
72
72
  private readonly clients = new Map<BuilderUrl, BuilderApi>();
73
73
 
74
74
  constructor(
@@ -78,7 +78,9 @@ export class BuilderApiClient {
78
78
  private readonly bls: IBlsVerifier,
79
79
  private readonly metrics: Metrics | null = null,
80
80
  private readonly logger?: Logger
81
- ) {}
81
+ ) {
82
+ this.bidDeadline = opts.bidDeadline ?? DEFAULT_BUILDER_BID_DEADLINE_MS;
83
+ }
82
84
 
83
85
  /**
84
86
  * Fan out bid requests to the builders named by the entries, one request per unique
@@ -139,9 +141,10 @@ export class BuilderApiClient {
139
141
  proposerPubkey,
140
142
  requestAuth: entry.auth,
141
143
  dateMilliseconds: Date.now(),
142
- timeoutMs: BUILDER_BID_DEADLINE_MS,
144
+ timeoutMs: this.bidDeadline,
143
145
  },
144
- {timeoutMs: BUILDER_BID_REQUEST_TIMEOUT_MS}
146
+ // Event loop lag must not discard bids that arrived in time
147
+ {timeoutMs: this.bidDeadline + BUILDER_BID_LAG_BUFFER_MS}
145
148
  );
146
149
  const signedBid = res.value();
147
150
  if (signedBid === undefined) {
@@ -203,7 +206,7 @@ export class BuilderApiClient {
203
206
 
204
207
  /**
205
208
  * Establish the connection to every known builder outside the bid deadline, a cold TCP/TLS handshake
206
- * to a distant builder can exhaust `BUILDER_BID_DEADLINE_MS` on its own, and a long idle connection
209
+ * to a distant builder can exhaust the bid deadline on its own, and a long idle connection
207
210
  * may be half-open and only fail once written to.
208
211
  */
209
212
  async checkStatus(): Promise<void> {
@@ -20,6 +20,7 @@ import {
20
20
  } from "@lodestar/types";
21
21
  import {toPrintableUrl} from "@lodestar/utils";
22
22
  import {Metrics} from "../../metrics/metrics.js";
23
+ import {DEFAULT_BUILDER_BID_DEADLINE_MS} from "./apiClient.js";
23
24
  import {ValidatorRegistration, ValidatorRegistrationCache} from "./cache.js";
24
25
  import {IExecutionBuilder} from "./interface.js";
25
26
 
@@ -29,6 +30,8 @@ export type ExecutionBuilderHttpOpts = {
29
30
  timeout?: number;
30
31
  faultInspectionWindow?: number;
31
32
  allowedFaults?: number;
33
+ /** Post-gloas only, time builders are given to provide a bid once block production starts, in milliseconds */
34
+ bidDeadline?: number;
32
35
 
33
36
  // Only required for merge-mock runs, no need to expose it to cli
34
37
  issueLocalFcUWithFeeRecipient?: string;
@@ -40,6 +43,7 @@ export const defaultExecutionBuilderHttpOpts: ExecutionBuilderHttpOpts = {
40
43
  enabled: false,
41
44
  url: "http://localhost:8661",
42
45
  timeout: 12000,
46
+ bidDeadline: DEFAULT_BUILDER_BID_DEADLINE_MS,
43
47
  };
44
48
 
45
49
  export enum BuilderStatus {
@@ -169,14 +169,16 @@ function getExecutionEngineStateForPayloadStatus(payloadStatus: ExecutionPayload
169
169
  return ExecutionEngineState.SYNCED;
170
170
 
171
171
  case ExecutionPayloadStatus.ELERROR:
172
- case ExecutionPayloadStatus.INVALID:
173
172
  case ExecutionPayloadStatus.SYNCING:
174
- case ExecutionPayloadStatus.INVALID_BLOCK_HASH:
175
173
  return ExecutionEngineState.SYNCING;
176
174
 
177
175
  case ExecutionPayloadStatus.UNAVAILABLE:
178
176
  return ExecutionEngineState.OFFLINE;
179
177
 
178
+ case ExecutionPayloadStatus.INVALID:
179
+ case ExecutionPayloadStatus.INVALID_BLOCK_HASH:
180
+ return ExecutionEngineState.ONLINE;
181
+
180
182
  default:
181
183
  // In case we can't determine the state, we assume it stays in old state
182
184
  // This assumption is better than considering offline, because the offline state may trigger some notifications
@@ -1013,6 +1013,11 @@ export function createLodestarMetrics(
1013
1013
  help: "Time elapsed between block received and fully verified state, signatures and payload",
1014
1014
  buckets: [0.05, 0.1, 0.3, 0.5, 0.7, 1, 1.3, 1.6, 2, 2.5, 3, 3.5, 4],
1015
1015
  }),
1016
+ receivedToConsensusVerifiedTime: register.histogram({
1017
+ name: "lodestar_gossip_block_received_to_consensus_verified_seconds",
1018
+ help: "Time from gossip block arrival until both the state transition and all block signature verifications are complete, excluding execution payload verification",
1019
+ buckets: [0.01, 0.015, 0.02, 0.025, 0.03, 0.04, 0.5, 1],
1020
+ }),
1016
1021
  verifiedToBlobsAvailabiltyTime: register.histogram<{numBlobs: number}>({
1017
1022
  name: "lodestar_gossip_block_verified_to_blobs_availability_time",
1018
1023
  help: "Time elapsed between block verified and blobs became available",
@@ -44,16 +44,16 @@ export async function getHttpMetricsServer(
44
44
  ): Promise<void> {
45
45
  if (req.method === "GET" && req.url && req.url.includes("/metrics")) {
46
46
  const timer = scrapeTimeMetric.startTimer();
47
- const metricsRes = await Promise.all([wrapError(register.metrics()), getOtherMetrics()]);
48
- timer({status: metricsRes[0].err ? RequestStatus.error : RequestStatus.success});
47
+ const metricsRes = await wrapError(Promise.all([register.metrics(), getOtherMetrics()]));
48
+ timer({status: metricsRes.err ? RequestStatus.error : RequestStatus.success});
49
49
 
50
50
  // Ensure we only writeHead once
51
- if (metricsRes[0].err) {
52
- res.writeHead(500, {"content-type": "text/plain"}).end(metricsRes[0].err.stack);
51
+ if (metricsRes.err) {
52
+ res.writeHead(500, {"content-type": "text/plain"}).end(metricsRes.err.stack);
53
53
  } else {
54
54
  // Get scrape time metrics
55
55
  const httpServerMetrics = await httpServerRegister.metrics();
56
- const metrics = [metricsRes[0].result, httpServerMetrics, ...metricsRes[1]];
56
+ const metrics = [metricsRes.result[0], httpServerMetrics, ...metricsRes.result[1]];
57
57
  const metricsStr = metrics.join("\n\n");
58
58
  res.writeHead(200, {"content-type": register.contentType}).end(metricsStr);
59
59
  }
@@ -108,6 +108,7 @@ type GossipSubInternal = GossipSub & {
108
108
  score: {score: (peerIdStr: string) => number};
109
109
  direct: Set<string>;
110
110
  topics: Map<string, Set<string>>;
111
+ streamsOutbound: ReadonlyMap<string, unknown>;
111
112
  start: () => Promise<void>;
112
113
  stop: () => Promise<void>;
113
114
  publish: (topic: TopicStr, data: Uint8Array, opts?: PublishOpts) => Promise<PublishResult>;
@@ -248,6 +249,16 @@ export class Eth2Gossipsub {
248
249
  return this.gossipsub.getMeshPeers(topic);
249
250
  }
250
251
 
252
+ getSubscribersWithOutboundStream(topic: GossipTopic): Set<string> {
253
+ const topicStr = stringifyGossipTopic(this.config, topic);
254
+ const peers = new Set<string>();
255
+ for (const peer of this.gossipsub.getSubscribers(topicStr)) {
256
+ const id = peer.toString();
257
+ if (this.gossipsub.streamsOutbound.has(id)) peers.add(id);
258
+ }
259
+ return peers;
260
+ }
261
+
251
262
  publish(topic: TopicStr, data: Uint8Array, opts?: PublishOpts): Promise<PublishResult> {
252
263
  return this.gossipsub.publish(topic, data, opts);
253
264
  }
@@ -150,7 +150,11 @@ export async function createNodeJsLibp2p(
150
150
  nodeInfo: {
151
151
  name: "lodestar",
152
152
  version: networkOpts.version ?? "unknown",
153
- userAgent: networkOpts.private ? "" : networkOpts.version ? `lodestar/${networkOpts.version}` : "lodestar",
153
+ userAgent: networkOpts.private
154
+ ? ""
155
+ : networkOpts.advertiseVersion && networkOpts.version
156
+ ? `lodestar/${networkOpts.version}`
157
+ : "lodestar",
154
158
  },
155
159
  addresses: {
156
160
  listen: localMultiaddrs,
@@ -30,7 +30,7 @@ import {
30
30
  isGloasDataColumnSidecar,
31
31
  phase0,
32
32
  } from "@lodestar/types";
33
- import {prettyPrintIndices, sleep} from "@lodestar/utils";
33
+ import {defer, prettyPrintIndices, sleep} from "@lodestar/utils";
34
34
  import {BlockInputSource} from "../chain/blocks/blockInput/types.js";
35
35
  import {ChainEvent, IBeaconChain} from "../chain/index.js";
36
36
  import {computeSubnetForDataColumnSidecar} from "../chain/validation/dataColumnSidecar.js";
@@ -128,6 +128,7 @@ export class Network implements INetwork {
128
128
 
129
129
  private subscribedToCoreTopics = false;
130
130
  private connectedPeersSyncMeta = new Map<PeerIdStr, Omit<PeerSyncMeta, "peerId">>();
131
+ private closePromise: Promise<void> | undefined;
131
132
 
132
133
  constructor(modules: NetworkModules) {
133
134
  this.peerId = peerIdFromPrivateKey(modules.privateKey);
@@ -145,12 +146,8 @@ export class Network implements INetwork {
145
146
  this.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
146
147
  this.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
147
148
  this.chain.emitter.on(routes.events.EventType.head, this.onHead);
148
- this.chain.emitter.on(routes.events.EventType.lightClientFinalityUpdate, ({data}) =>
149
- this.onLightClientFinalityUpdate(data)
150
- );
151
- this.chain.emitter.on(routes.events.EventType.lightClientOptimisticUpdate, ({data}) =>
152
- this.onLightClientOptimisticUpdate(data)
153
- );
149
+ this.chain.emitter.on(routes.events.EventType.lightClientFinalityUpdate, this.onLightClientFinalityUpdate);
150
+ this.chain.emitter.on(routes.events.EventType.lightClientOptimisticUpdate, this.onLightClientOptimisticUpdate);
154
151
  this.chain.emitter.on(ChainEvent.updateTargetCustodyGroupCount, this.onTargetGroupCountUpdated);
155
152
  this.chain.emitter.on(ChainEvent.publishDataColumns, this.onPublishDataColumns);
156
153
  this.chain.emitter.on(ChainEvent.publishBlobSidecars, this.onPublishBlobSidecars);
@@ -240,9 +237,16 @@ export class Network implements INetwork {
240
237
  return this.controller.signal.aborted;
241
238
  }
242
239
 
243
- /** Destroy this instance. Can only be called once. */
244
- async close(): Promise<void> {
245
- if (this.closed) return;
240
+ close(): Promise<void> {
241
+ if (this.closePromise !== undefined) return this.closePromise;
242
+ const completion = defer<void>();
243
+ this.closePromise = completion.promise;
244
+ void this.closeInternal().then(completion.resolve, completion.reject);
245
+ return this.closePromise;
246
+ }
247
+
248
+ private async closeInternal(): Promise<void> {
249
+ this.controller.abort();
246
250
 
247
251
  this.events.off(NetworkEvent.peerConnected, this.onPeerConnected);
248
252
  this.events.off(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
@@ -254,10 +258,12 @@ export class Network implements INetwork {
254
258
  this.chain.emitter.off(ChainEvent.publishBlobSidecars, this.onPublishBlobSidecars);
255
259
  this.chain.emitter.off(ChainEvent.publishProposerSlashing, this.onPublishProposerSlashing);
256
260
  this.chain.emitter.off(ChainEvent.updateStatus, this.onUpdateStatus);
257
- await this.core.close();
258
-
259
- // Used only for sleep() statements
260
- this.controller.abort();
261
+ this.connectedPeersSyncMeta.clear();
262
+ this.subscribedToCoreTopics = false;
263
+ const results = await Promise.allSettled([this.networkProcessor.stop(), this.core.close()]);
264
+ for (const result of results) {
265
+ if (result.status === "rejected") throw result.reason;
266
+ }
261
267
  this.logger.debug("network core closed");
262
268
  }
263
269
 
@@ -333,6 +339,7 @@ export class Network implements INetwork {
333
339
  async subscribeGossipCoreTopics(): Promise<void> {
334
340
  if (!this.subscribedToCoreTopics) {
335
341
  await this.core.subscribeGossipCoreTopics();
342
+ if (this.closed) return;
336
343
  // Only mark subscribedToCoreTopics if worker resolved this call
337
344
  this.subscribedToCoreTopics = true;
338
345
  }
@@ -803,26 +810,32 @@ export class Network implements INetwork {
803
810
  return this.core.writeDiscv5HeapSnapshot(prefix, dirpath);
804
811
  }
805
812
 
806
- private onLightClientFinalityUpdate = async (finalityUpdate: LightClientFinalityUpdate): Promise<void> => {
813
+ private onLightClientFinalityUpdate = async ({
814
+ data: finalityUpdate,
815
+ }: routes.events.EventData[routes.events.EventType.lightClientFinalityUpdate]): Promise<void> => {
807
816
  // TODO: Review is OK to remove if (this.hasAttachedSyncCommitteeMember())
808
817
 
809
818
  try {
810
819
  // messages SHOULD be broadcast after SYNC_MESSAGE_DUE_BPS of slot has transpired
811
820
  // https://github.com/ethereum/consensus-specs/blob/v1.6.1/specs/altair/light-client/p2p-interface.md#sync-committee
812
821
  await this.waitForSyncMessageCutoff(finalityUpdate.signatureSlot);
822
+ if (this.closed) return;
813
823
  await this.publishLightClientFinalityUpdate(finalityUpdate);
814
824
  } catch (e) {
815
825
  this.logger.debug("Error on BeaconGossipHandler.onLightclientFinalityUpdate", {}, e as Error);
816
826
  }
817
827
  };
818
828
 
819
- private onLightClientOptimisticUpdate = async (optimisticUpdate: LightClientOptimisticUpdate): Promise<void> => {
829
+ private onLightClientOptimisticUpdate = async ({
830
+ data: optimisticUpdate,
831
+ }: routes.events.EventData[routes.events.EventType.lightClientOptimisticUpdate]): Promise<void> => {
820
832
  // TODO: Review is OK to remove if (this.hasAttachedSyncCommitteeMember())
821
833
 
822
834
  try {
823
835
  // messages SHOULD be broadcast after SYNC_MESSAGE_DUE_BPS of slot has transpired
824
836
  // https://github.com/ethereum/consensus-specs/blob/v1.6.1/specs/altair/light-client/p2p-interface.md#sync-committee
825
837
  await this.waitForSyncMessageCutoff(optimisticUpdate.signatureSlot);
838
+ if (this.closed) return;
826
839
  await this.publishLightClientOptimisticUpdate(optimisticUpdate);
827
840
  } catch (e) {
828
841
  this.logger.debug("Error on BeaconGossipHandler.onLightclientOptimisticUpdate", {}, e as Error);
@@ -859,10 +872,12 @@ export class Network implements INetwork {
859
872
  this.connectedPeersSyncMeta.delete(data.peer);
860
873
  };
861
874
 
862
- private onTargetGroupCountUpdated = (count: number): void => {
863
- this.core.setTargetGroupCount(count).catch((e) => {
864
- this.logger.debug("Error setting target custody group count", {count}, e as Error);
865
- });
875
+ private onTargetGroupCountUpdated = async (count: number): Promise<void> => {
876
+ try {
877
+ await this.core.setTargetGroupCount(count);
878
+ } catch (error) {
879
+ this.logger.error("Error updating network custody group count", {count}, error as Error);
880
+ }
866
881
  };
867
882
 
868
883
  private onPublishDataColumns = async (sidecars: DataColumnSidecar[]): Promise<void> => {
@@ -886,6 +901,10 @@ export class Network implements INetwork {
886
901
  };
887
902
 
888
903
  private onUpdateStatus = async (): Promise<void> => {
889
- await this.core.updateStatus(this.chain.getStatus());
904
+ try {
905
+ await this.core.updateStatus(this.chain.getStatus());
906
+ } catch (error) {
907
+ this.logger.error("Error updating network status", {}, error as Error);
908
+ }
890
909
  };
891
910
  }
@@ -25,6 +25,8 @@ export interface NetworkOptions
25
25
  mdns?: boolean;
26
26
  connectToDiscv5Bootnodes?: boolean;
27
27
  version?: string;
28
+ /** Include the version in libp2p Identify. Private mode takes precedence. */
29
+ advertiseVersion?: boolean;
28
30
  private?: boolean;
29
31
  useWorker?: boolean;
30
32
  maxYoungGenerationSizeMb?: number;
@@ -14,6 +14,7 @@ import {NetworkCoreMetrics} from "../core/metrics.js";
14
14
  import {LodestarDiscv5Opts} from "../discv5/types.js";
15
15
  import {INetworkEventBus, NetworkEvent, NetworkEventData} from "../events.js";
16
16
  import {Eth2Gossipsub} from "../gossip/gossipsub.js";
17
+ import {GossipType} from "../gossip/interface.js";
17
18
  import {Libp2p} from "../interface.js";
18
19
  import {SubnetType} from "../metadata.js";
19
20
  import {NetworkConfig} from "../networkConfig.js";
@@ -577,6 +578,8 @@ export class PeerManager {
577
578
  this.lastStatus = status;
578
579
  this.metrics?.peerManager.starved.set(starved ? 1 : 0);
579
580
  const forkSeq = this.config.getForkSeq(this.clock.currentSlot);
581
+ const boundary = this.config.getForkBoundaryAtEpoch(this.clock.currentEpoch);
582
+ const connectedHealthyPeerIds = new Set(connectedHealthyPeers.map((peer) => peer.toString()));
580
583
 
581
584
  const prioritizeTimer = this.metrics?.peerManager.prioritizePeersDuration.startTimer();
582
585
  const {peersToDisconnect, peersToConnect, attnetQueries, syncnetQueries, custodyGroupQueries} = prioritizePeers(
@@ -594,8 +597,30 @@ export class PeerManager {
594
597
  };
595
598
  }),
596
599
  // Collect subnets which we need peers for in the current slot
597
- this.attnetsService.getActiveSubnets(),
598
- this.syncnetsService.getActiveSubnets(),
600
+ this.attnetsService.getActiveSubnets().map((request) => {
601
+ const subscribers = this.gossipsub.getSubscribersWithOutboundStream({
602
+ type: GossipType.beacon_attestation,
603
+ boundary,
604
+ subnet: request.subnet,
605
+ });
606
+ let peerCount = 0;
607
+ for (const peer of subscribers) {
608
+ if (connectedHealthyPeerIds.has(peer)) peerCount++;
609
+ }
610
+ return {...request, peerCount};
611
+ }),
612
+ this.syncnetsService.getActiveSubnets().map((request) => {
613
+ const subscribers = this.gossipsub.getSubscribersWithOutboundStream({
614
+ type: GossipType.sync_committee,
615
+ boundary,
616
+ subnet: request.subnet,
617
+ });
618
+ let peerCount = 0;
619
+ for (const peer of subscribers) {
620
+ if (connectedHealthyPeerIds.has(peer)) peerCount++;
621
+ }
622
+ return {...request, peerCount};
623
+ }),
599
624
  // ignore samplingGroups for pre-fulu forks
600
625
  forkSeq >= ForkSeq.fulu ? this.networkConfig.custodyConfig.sampleGroups : undefined,
601
626
  {
@@ -49,6 +49,8 @@ const syncnetsZero = BitArray.fromBitLen(SYNC_COMMITTEE_SUBNET_COUNT);
49
49
 
50
50
  type SubnetDiscvQuery = {subnet: SubnetID; toSlot: number; maxPeersToDiscover: number};
51
51
 
52
+ export type RequestedSubnetWithPeerCount = RequestedSubnet & {peerCount: number};
53
+
52
54
  /**
53
55
  * A map of das custody group index to maxPeersToDiscover
54
56
  */
@@ -145,8 +147,8 @@ export function prioritizePeers(
145
147
  samplingGroups: CustodyIndex[] | null;
146
148
  score: number;
147
149
  }[],
148
- activeAttnets: RequestedSubnet[],
149
- activeSyncnets: RequestedSubnet[],
150
+ activeAttnets: RequestedSubnetWithPeerCount[],
151
+ activeSyncnets: RequestedSubnetWithPeerCount[],
150
152
  samplingGroups: CustodyIndex[] | undefined,
151
153
  opts: PrioritizePeersOpts,
152
154
  config: ChainConfig,
@@ -231,8 +233,8 @@ export function prioritizePeers(
231
233
  */
232
234
  function requestSubnetPeers(
233
235
  connectedPeers: PeerInfo[],
234
- activeAttnets: RequestedSubnet[],
235
- activeSyncnets: RequestedSubnet[],
236
+ activeAttnets: RequestedSubnetWithPeerCount[],
237
+ activeSyncnets: RequestedSubnetWithPeerCount[],
236
238
  ourSamplingGroups: CustodyIndex[] | undefined,
237
239
  opts: PrioritizePeersOpts,
238
240
  config: ChainConfig,
@@ -252,54 +254,44 @@ function requestSubnetPeers(
252
254
 
253
255
  // attnets, do we need queries for more peers
254
256
  if (activeAttnets.length > 0) {
255
- /** Map of peers per subnet, peer may be in multiple arrays */
256
- const peersPerSubnet = new Map<number, number>();
257
-
258
257
  for (const peer of connectedPeers) {
259
258
  const trueBitIndices = peer.attnetsTrueBitIndices;
260
259
  let dutyCount = 0;
261
260
  for (const {subnet} of activeAttnets) {
262
261
  if (trueBitIndices.includes(subnet)) {
263
262
  dutyCount += 1;
264
- peersPerSubnet.set(subnet, 1 + (peersPerSubnet.get(subnet) ?? 0));
265
263
  }
266
264
  }
267
265
  dutiesByPeer.set(peer, dutyCount);
268
266
  }
269
267
 
270
- for (const {subnet, toSlot} of activeAttnets) {
271
- const peersInSubnet = peersPerSubnet.get(subnet) ?? 0;
272
- metrics?.peerManager.peersPerActiveSubnet.observe({type: SubnetType.attnets}, peersInSubnet);
273
- if (peersInSubnet < targetSubnetPeers) {
268
+ for (const {subnet, toSlot, peerCount} of activeAttnets) {
269
+ metrics?.peerManager.peersPerActiveSubnet.observe({type: SubnetType.attnets}, peerCount);
270
+ if (peerCount < targetSubnetPeers) {
274
271
  // We need more peers
275
- attnetQueries.push({subnet, toSlot, maxPeersToDiscover: targetSubnetPeers - peersInSubnet});
272
+ attnetQueries.push({subnet, toSlot, maxPeersToDiscover: targetSubnetPeers - peerCount});
276
273
  }
277
274
  }
278
275
  }
279
276
 
280
277
  // syncnets, do we need queries for more peers
281
278
  if (activeSyncnets.length > 0) {
282
- /** Map of peers per subnet, peer may be in multiple arrays */
283
- const peersPerSubnet = new Map<number, number>();
284
-
285
279
  for (const peer of connectedPeers) {
286
280
  const trueBitIndices = peer.syncnetsTrueBitIndices;
287
281
  let dutyCount = dutiesByPeer.get(peer) ?? 0;
288
282
  for (const {subnet} of activeSyncnets) {
289
283
  if (trueBitIndices.includes(subnet)) {
290
284
  dutyCount += 1;
291
- peersPerSubnet.set(subnet, 1 + (peersPerSubnet.get(subnet) ?? 0));
292
285
  }
293
286
  }
294
287
  dutiesByPeer.set(peer, dutyCount);
295
288
  }
296
289
 
297
- for (const {subnet, toSlot} of activeSyncnets) {
298
- const peersInSubnet = peersPerSubnet.get(subnet) ?? 0;
299
- metrics?.peerManager.peersPerActiveSubnet.observe({type: SubnetType.syncnets}, peersInSubnet);
300
- if (peersInSubnet < targetSubnetPeers) {
290
+ for (const {subnet, toSlot, peerCount} of activeSyncnets) {
291
+ metrics?.peerManager.peersPerActiveSubnet.observe({type: SubnetType.syncnets}, peerCount);
292
+ if (peerCount < targetSubnetPeers) {
301
293
  // We need more peers
302
- syncnetQueries.push({subnet, toSlot, maxPeersToDiscover: targetSubnetPeers - peersInSubnet});
294
+ syncnetQueries.push({subnet, toSlot, maxPeersToDiscover: targetSubnetPeers - peerCount});
303
295
  }
304
296
  }
305
297
  }