@aztec-labs/blob-client 6.0.0-nightly.20260829

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 (96) hide show
  1. package/README.md +71 -0
  2. package/dest/archive/blobscan_archive_client.d.ts +62 -0
  3. package/dest/archive/blobscan_archive_client.d.ts.map +1 -0
  4. package/dest/archive/blobscan_archive_client.js +138 -0
  5. package/dest/archive/config.d.ts +7 -0
  6. package/dest/archive/config.d.ts.map +1 -0
  7. package/dest/archive/config.js +11 -0
  8. package/dest/archive/factory.d.ts +4 -0
  9. package/dest/archive/factory.d.ts.map +1 -0
  10. package/dest/archive/factory.js +7 -0
  11. package/dest/archive/index.d.ts +3 -0
  12. package/dest/archive/index.d.ts.map +1 -0
  13. package/dest/archive/index.js +2 -0
  14. package/dest/archive/instrumentation.d.ts +11 -0
  15. package/dest/archive/instrumentation.d.ts.map +1 -0
  16. package/dest/archive/instrumentation.js +33 -0
  17. package/dest/archive/interface.d.ts +13 -0
  18. package/dest/archive/interface.d.ts.map +1 -0
  19. package/dest/archive/interface.js +1 -0
  20. package/dest/blobstore/blob_store_test_suite.d.ts +3 -0
  21. package/dest/blobstore/blob_store_test_suite.d.ts.map +1 -0
  22. package/dest/blobstore/blob_store_test_suite.js +133 -0
  23. package/dest/blobstore/index.d.ts +3 -0
  24. package/dest/blobstore/index.d.ts.map +1 -0
  25. package/dest/blobstore/index.js +2 -0
  26. package/dest/blobstore/interface.d.ts +12 -0
  27. package/dest/blobstore/interface.d.ts.map +1 -0
  28. package/dest/blobstore/interface.js +1 -0
  29. package/dest/blobstore/memory_blob_store.d.ts +8 -0
  30. package/dest/blobstore/memory_blob_store.d.ts.map +1 -0
  31. package/dest/blobstore/memory_blob_store.js +24 -0
  32. package/dest/client/bin/index.d.ts +3 -0
  33. package/dest/client/bin/index.d.ts.map +1 -0
  34. package/dest/client/bin/index.js +30 -0
  35. package/dest/client/config.d.ts +60 -0
  36. package/dest/client/config.d.ts.map +1 -0
  37. package/dest/client/config.js +75 -0
  38. package/dest/client/factory.d.ts +38 -0
  39. package/dest/client/factory.d.ts.map +1 -0
  40. package/dest/client/factory.js +62 -0
  41. package/dest/client/http.d.ts +87 -0
  42. package/dest/client/http.d.ts.map +1 -0
  43. package/dest/client/http.js +698 -0
  44. package/dest/client/index.d.ts +6 -0
  45. package/dest/client/index.d.ts.map +1 -0
  46. package/dest/client/index.js +5 -0
  47. package/dest/client/interface.d.ts +37 -0
  48. package/dest/client/interface.d.ts.map +1 -0
  49. package/dest/client/interface.js +1 -0
  50. package/dest/client/local.d.ts +13 -0
  51. package/dest/client/local.d.ts.map +1 -0
  52. package/dest/client/local.js +19 -0
  53. package/dest/client/tests.d.ts +11 -0
  54. package/dest/client/tests.d.ts.map +1 -0
  55. package/dest/client/tests.js +51 -0
  56. package/dest/encoding/index.d.ts +15 -0
  57. package/dest/encoding/index.d.ts.map +1 -0
  58. package/dest/encoding/index.js +19 -0
  59. package/dest/filestore/factory.d.ts +51 -0
  60. package/dest/filestore/factory.d.ts.map +1 -0
  61. package/dest/filestore/factory.js +67 -0
  62. package/dest/filestore/filestore_blob_client.d.ts +67 -0
  63. package/dest/filestore/filestore_blob_client.d.ts.map +1 -0
  64. package/dest/filestore/filestore_blob_client.js +115 -0
  65. package/dest/filestore/healthcheck.d.ts +5 -0
  66. package/dest/filestore/healthcheck.d.ts.map +1 -0
  67. package/dest/filestore/healthcheck.js +3 -0
  68. package/dest/filestore/index.d.ts +3 -0
  69. package/dest/filestore/index.d.ts.map +1 -0
  70. package/dest/filestore/index.js +2 -0
  71. package/package.json +93 -0
  72. package/src/archive/blobscan_archive_client.ts +175 -0
  73. package/src/archive/config.ts +14 -0
  74. package/src/archive/factory.ts +11 -0
  75. package/src/archive/fixtures/blobscan_get_blob_data.json +1 -0
  76. package/src/archive/fixtures/blobscan_get_block.json +56 -0
  77. package/src/archive/index.ts +2 -0
  78. package/src/archive/instrumentation.ts +50 -0
  79. package/src/archive/interface.ts +9 -0
  80. package/src/blobstore/blob_store_test_suite.ts +110 -0
  81. package/src/blobstore/index.ts +2 -0
  82. package/src/blobstore/interface.ts +12 -0
  83. package/src/blobstore/memory_blob_store.ts +31 -0
  84. package/src/client/bin/index.ts +35 -0
  85. package/src/client/config.ts +152 -0
  86. package/src/client/factory.ts +100 -0
  87. package/src/client/http.ts +838 -0
  88. package/src/client/index.ts +5 -0
  89. package/src/client/interface.ts +38 -0
  90. package/src/client/local.ts +30 -0
  91. package/src/client/tests.ts +61 -0
  92. package/src/encoding/index.ts +21 -0
  93. package/src/filestore/factory.ts +150 -0
  94. package/src/filestore/filestore_blob_client.ts +149 -0
  95. package/src/filestore/healthcheck.ts +5 -0
  96. package/src/filestore/index.ts +2 -0
@@ -0,0 +1,838 @@
1
+ import { Blob, type BlobJson, computeEthVersionedBlobHash } from '@aztec-labs/blob-lib';
2
+ import { makeL1HttpTransport } from '@aztec-labs/ethereum/client';
3
+ import { shuffle } from '@aztec-labs/foundation/array';
4
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
5
+ import { makeBackoff, retry } from '@aztec-labs/foundation/retry';
6
+ import { bufferToHex, hexToBuffer } from '@aztec-labs/foundation/string';
7
+ import { type RpcBlock, createPublicClient } from 'viem';
8
+
9
+ import { createBlobArchiveClient } from '../archive/factory.js';
10
+ import type { BlobArchiveClient } from '../archive/interface.js';
11
+ import type { FileStoreBlobClient } from '../filestore/filestore_blob_client.js';
12
+ import { DEFAULT_HEALTHCHECK_UPLOAD_INTERVAL_MINUTES } from '../filestore/healthcheck.js';
13
+ import { type BlobClientConfig, getBlobClientConfigFromEnv } from './config.js';
14
+ import type { BlobClientInterface, GetBlobSidecarOptions } from './interface.js';
15
+
16
+ export class HttpBlobClient implements BlobClientInterface {
17
+ protected readonly log: Logger;
18
+ protected readonly config: BlobClientConfig;
19
+ protected readonly archiveClient: BlobArchiveClient | undefined;
20
+ protected readonly fetch: typeof fetch;
21
+ protected readonly fileStoreClients: FileStoreBlobClient[];
22
+ protected readonly fileStoreUploadClient: FileStoreBlobClient | undefined;
23
+
24
+ private disabled = false;
25
+ private healthcheckUploadIntervalId?: NodeJS.Timeout;
26
+
27
+ /** Cached beacon genesis time (seconds since Unix epoch). Fetched once at startup. */
28
+ private beaconGenesisTime?: bigint;
29
+ /** Cached beacon slot duration in seconds. Fetched once at startup. */
30
+ private beaconSecondsPerSlot?: number;
31
+
32
+ /** Indexes of consensus hosts that serve blob sidecars (supernodes). Populated by testSources(). */
33
+ private superNodeHostIndexes?: Set<number>;
34
+
35
+ constructor(
36
+ config?: BlobClientConfig,
37
+ private readonly opts: {
38
+ logger?: Logger;
39
+ archiveClient?: BlobArchiveClient;
40
+ fileStoreClients?: FileStoreBlobClient[];
41
+ fileStoreUploadClient?: FileStoreBlobClient;
42
+ /** Callback fired when blobs are successfully fetched from any source */
43
+ onBlobsFetched?: (blobs: Blob[]) => void;
44
+ } = {},
45
+ ) {
46
+ this.config = config ?? getBlobClientConfigFromEnv();
47
+ this.archiveClient = opts.archiveClient ?? createBlobArchiveClient(this.config);
48
+ this.log = opts.logger ?? createLogger('blob-client:client');
49
+ this.fileStoreClients = opts.fileStoreClients ?? [];
50
+ this.fileStoreUploadClient = opts.fileStoreUploadClient;
51
+
52
+ if (this.fileStoreUploadClient && !opts.onBlobsFetched) {
53
+ this.opts.onBlobsFetched = blobs => {
54
+ this.uploadBlobsToFileStore(blobs);
55
+ };
56
+ }
57
+
58
+ this.fetch = async (...args: Parameters<typeof fetch>): Promise<Response> => {
59
+ return await retry(
60
+ () => fetch(...args),
61
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
62
+ `Fetching ${args[0]}`,
63
+ makeBackoff([1, 1, 3]),
64
+ this.log,
65
+ /*failSilently=*/ true,
66
+ );
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Upload fetched blobs to filestore (fire-and-forget).
72
+ * Called automatically when blobs are fetched from any source.
73
+ */
74
+ private uploadBlobsToFileStore(blobs: Blob[]): void {
75
+ if (!this.fileStoreUploadClient) {
76
+ return;
77
+ }
78
+
79
+ void this.fileStoreUploadClient.saveBlobs(blobs, true).catch(err => {
80
+ this.log.warn(`Failed to upload ${blobs.length} blobs to filestore`, err);
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Disables or enables blob storage operations.
86
+ * When disabled, getBlobSidecar returns empty arrays and sendBlobsToFilestore returns false.
87
+ * Useful for testing scenarios where blob storage failure needs to be simulated.
88
+ * @param value - True to disable blob storage, false to enable
89
+ */
90
+ public setDisabled(value: boolean): void {
91
+ this.disabled = value;
92
+ this.log.info(`Blob storage ${value ? 'disabled' : 'enabled'}`);
93
+ }
94
+
95
+ public async testSources() {
96
+ const { l1ConsensusHostUrls } = this.config;
97
+ const archiveUrl = this.archiveClient?.getBaseUrl();
98
+ this.log.info(`Testing configured blob sources`, { l1ConsensusHostUrls, archiveUrl });
99
+
100
+ let consensusSuperNodes = 0;
101
+ let consensusNonSuperNodes = 0;
102
+ let archiveSources = 0;
103
+ let blobSinks = 0;
104
+
105
+ const detectedSuperNodes = new Set<number>();
106
+
107
+ if (l1ConsensusHostUrls && l1ConsensusHostUrls.length > 0) {
108
+ for (let l1ConsensusHostIndex = 0; l1ConsensusHostIndex < l1ConsensusHostUrls.length; l1ConsensusHostIndex++) {
109
+ const l1ConsensusHostUrl = l1ConsensusHostUrls[l1ConsensusHostIndex];
110
+ try {
111
+ const { url, ...options } = getBeaconNodeFetchOptions(
112
+ `${l1ConsensusHostUrl}/eth/v1/beacon/headers/head`,
113
+ this.config,
114
+ l1ConsensusHostIndex,
115
+ );
116
+ const res = await this.fetch(url, options);
117
+ if (!res.ok) {
118
+ this.log.error(`Failure reaching L1 consensus host: ${res.statusText} (${res.status})`, {
119
+ l1ConsensusHostUrl,
120
+ });
121
+ continue;
122
+ }
123
+
124
+ this.log.info(`L1 consensus host is reachable`, { l1ConsensusHostUrl });
125
+
126
+ // Check if the host serves blob sidecars (supernode/semi-supernode).
127
+ // Post-Fusaka (PeerDAS), non-supernode beacon nodes no longer serve the
128
+ // blob sidecar endpoint. A 200 response (even with an empty data array
129
+ // for a slot with no blobs) means the node supports serving blob sidecars.
130
+ const body = await res.json();
131
+ const headSlot = body?.data?.header?.message?.slot;
132
+ if (headSlot) {
133
+ const { url: blobUrl, ...blobOptions } = getBeaconNodeFetchOptions(
134
+ `${l1ConsensusHostUrl}/eth/v1/beacon/blobs/${headSlot}`,
135
+ this.config,
136
+ l1ConsensusHostIndex,
137
+ );
138
+ const blobRes = await this.fetch(blobUrl, blobOptions);
139
+ if (blobRes.ok) {
140
+ this.log.info(`L1 consensus host serves blob sidecars (supernode)`, { l1ConsensusHostUrl });
141
+ detectedSuperNodes.add(l1ConsensusHostIndex);
142
+ consensusSuperNodes++;
143
+ } else {
144
+ this.log.info(`L1 consensus host does not serve blob sidecars, skipping for blob fetching`, {
145
+ l1ConsensusHostUrl,
146
+ });
147
+ consensusNonSuperNodes++;
148
+ }
149
+ } else {
150
+ this.log.info(`L1 consensus host is reachable but could not determine head slot`, { l1ConsensusHostUrl });
151
+ consensusNonSuperNodes++;
152
+ }
153
+ } catch (err) {
154
+ this.log.error(`Error reaching L1 consensus host`, err, { l1ConsensusHostUrl });
155
+ }
156
+ }
157
+ }
158
+
159
+ this.superNodeHostIndexes = detectedSuperNodes;
160
+
161
+ if (this.archiveClient) {
162
+ try {
163
+ const latest = await this.archiveClient.getLatestBlock();
164
+ this.log.info(`Archive client is reachable and synced to L1 block ${latest.number}`, { latest, archiveUrl });
165
+ archiveSources++;
166
+ } catch (err) {
167
+ this.log.error(`Error reaching archive client`, err, { archiveUrl });
168
+ }
169
+ }
170
+
171
+ if (this.fileStoreClients.length > 0) {
172
+ for (const fileStoreClient of this.fileStoreClients) {
173
+ try {
174
+ const accessible = await fileStoreClient.testConnection();
175
+ if (accessible) {
176
+ this.log.info(`FileStore is reachable`, { url: fileStoreClient.getBaseUrl() });
177
+ blobSinks++;
178
+ } else {
179
+ this.log.warn(`FileStore is not accessible`, { url: fileStoreClient.getBaseUrl() });
180
+ }
181
+ } catch (err) {
182
+ this.log.error(`Error reaching filestore`, err, { url: fileStoreClient.getBaseUrl() });
183
+ }
184
+ }
185
+ }
186
+
187
+ // Emit a single summary after validating all sources
188
+ const successfulSourceCount = consensusSuperNodes + archiveSources + blobSinks;
189
+
190
+ let summary = `Blob client running with consensusSuperNodes=${consensusSuperNodes} archiveSources=${archiveSources} blobSinks=${blobSinks}`;
191
+ if (consensusNonSuperNodes > 0) {
192
+ summary += `. ${consensusNonSuperNodes} consensus client(s) ignored because they are not running in supernode or semi-supernode mode`;
193
+ }
194
+
195
+ if (successfulSourceCount === 0) {
196
+ if (this.config.blobAllowEmptySources) {
197
+ this.log.warn(summary);
198
+ } else {
199
+ throw new Error(summary);
200
+ }
201
+ } else if (consensusSuperNodes === 0) {
202
+ this.log.warn(summary);
203
+ } else {
204
+ this.log.info(summary);
205
+ }
206
+ }
207
+
208
+ public async sendBlobsToFilestore(blobs: Blob[]): Promise<boolean> {
209
+ if (this.disabled) {
210
+ this.log.warn('Blob storage is disabled, not uploading blobs');
211
+ return false;
212
+ }
213
+
214
+ if (!this.fileStoreUploadClient) {
215
+ this.log.verbose('No filestore upload configured');
216
+ return false;
217
+ }
218
+
219
+ this.log.verbose(`Uploading ${blobs.length} blobs to filestore`);
220
+ try {
221
+ await this.fileStoreUploadClient.saveBlobs(blobs, true);
222
+ return true;
223
+ } catch (err) {
224
+ this.log.error('Failed to upload blobs to filestore', err);
225
+ return false;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Get the blob sidecar.
231
+ *
232
+ * Alternates between two primary sources (consensus and filestore) in a retry loop,
233
+ * then falls back to archive if blobs are still missing. The order of the primary
234
+ * sources is configurable via `blobPreferFilestores`.
235
+ *
236
+ * @param blockHash - The block hash
237
+ * @param blobHashes - The blob hashes to fetch
238
+ * @param opts - Options for slot resolution
239
+ * @returns The blobs
240
+ */
241
+ public async getBlobSidecar(
242
+ blockHash: `0x${string}`,
243
+ blobHashes: Buffer[],
244
+ opts?: GetBlobSidecarOptions,
245
+ ): Promise<Blob[]> {
246
+ if (this.disabled) {
247
+ this.log.warn('Blob storage is disabled, returning empty blob sidecar');
248
+ return [];
249
+ }
250
+
251
+ // Accumulate blobs across sources, preserving order and handling duplicates
252
+ // resultBlobs[i] will contain the blob for blobHashes[i], or undefined if not yet found
253
+ const resultBlobs: (Blob | undefined)[] = new Array(blobHashes.length).fill(undefined);
254
+
255
+ // Helper to get missing blob hashes that we still need to fetch
256
+ const getMissingBlobHashes = (): Buffer[] =>
257
+ blobHashes
258
+ .map((bh, i) => (resultBlobs[i] === undefined ? bh : undefined))
259
+ .filter((bh): bh is Buffer => bh !== undefined);
260
+
261
+ // Return the result, ignoring any undefined ones
262
+ const getFilledBlobs = (): Blob[] => resultBlobs.filter((b): b is Blob => b !== undefined);
263
+
264
+ // Helper to fill in results from fetched blobs
265
+ const fillResults = async (fetchedBlobs: BlobJson[]): Promise<Blob[]> => {
266
+ const blobs = await processFetchedBlobs(fetchedBlobs, blobHashes, this.log);
267
+ // Fill in any missing positions with matching blobs
268
+ for (let i = 0; i < blobHashes.length; i++) {
269
+ if (resultBlobs[i] === undefined) {
270
+ resultBlobs[i] = blobs[i];
271
+ }
272
+ }
273
+ return getFilledBlobs();
274
+ };
275
+
276
+ // Fire callback when returning blobs (fire-and-forget)
277
+ const returnWithCallback = (blobs: Blob[]): Blob[] => {
278
+ if (blobs.length > 0 && this.opts.onBlobsFetched) {
279
+ void Promise.resolve().then(() => this.opts.onBlobsFetched!(blobs));
280
+ }
281
+ return blobs;
282
+ };
283
+
284
+ const ctx = { blockHash, blobHashes: blobHashes.map(bufferToHex) };
285
+
286
+ // Lazily resolve the slot number — only resolved when consensus hosts are actually tried.
287
+ let slotNumber: number | undefined;
288
+ let slotResolved = false;
289
+ const getSlotNumber = async (): Promise<number | undefined> => {
290
+ if (!slotResolved) {
291
+ slotNumber = await this.resolveSlotNumber(blockHash, opts);
292
+ slotResolved = true;
293
+ }
294
+ return slotNumber;
295
+ };
296
+
297
+ // Build the two source-try functions. The order depends on the config.
298
+ const tryConsensus = () => this.tryConsensusHosts(getSlotNumber, getMissingBlobHashes, fillResults, ctx);
299
+ const tryFilestores = () => this.tryFileStores(getMissingBlobHashes, fillResults, ctx);
300
+
301
+ const preferFilestores = this.config.blobPreferFilestores ?? false;
302
+ const [trySourceA, trySourceB] = preferFilestores ? [tryFilestores, tryConsensus] : [tryConsensus, tryFilestores];
303
+
304
+ // Historical sync: blobs should already exist, use shorter backoff for transient errors.
305
+ // Near-tip sync: blobs may still be uploading, use longer backoff for eventual consistency.
306
+ const isHistoricalSync = opts?.isHistoricalSync ?? false;
307
+ const backoff = isHistoricalSync ? [1, 1] : [1, 1, 1, 2, 2];
308
+
309
+ // Retry loop: alternate between the two primary sources with backoff.
310
+ try {
311
+ await retry(
312
+ async () => {
313
+ if (getMissingBlobHashes().length > 0) {
314
+ await trySourceA();
315
+ }
316
+ if (getMissingBlobHashes().length > 0) {
317
+ await trySourceB();
318
+ }
319
+ if (getMissingBlobHashes().length > 0) {
320
+ throw new Error('Still missing blobs after trying all primary sources');
321
+ }
322
+ },
323
+ 'blob retrieval',
324
+ makeBackoff(backoff),
325
+ this.log,
326
+ true, // failSilently — expected during eventual consistency
327
+ );
328
+ return returnWithCallback(getFilledBlobs());
329
+ } catch {
330
+ // Exhausted retries, continue to archive fallback
331
+ }
332
+
333
+ // Archive fallback
334
+ const missingAfterPrimary = getMissingBlobHashes();
335
+ if (missingAfterPrimary.length > 0 && this.archiveClient) {
336
+ const archiveCtx = { archiveUrl: this.archiveClient.getBaseUrl(), ...ctx };
337
+ this.log.trace(`Attempting to get ${missingAfterPrimary.length} blobs from archive`, archiveCtx);
338
+ const allBlobs = await this.archiveClient.getBlobsFromBlock(blockHash);
339
+ if (!allBlobs) {
340
+ this.log.debug('No blobs found from archive client', archiveCtx);
341
+ } else {
342
+ this.log.trace(`Got ${allBlobs.length} blobs from archive client before filtering`, archiveCtx);
343
+ const result = await fillResults(allBlobs);
344
+ this.log.debug(
345
+ `Got ${allBlobs.length} blobs from archive client (total: ${result.length}/${blobHashes.length})`,
346
+ archiveCtx,
347
+ );
348
+ if (result.length === blobHashes.length) {
349
+ return returnWithCallback(result);
350
+ }
351
+ }
352
+ }
353
+
354
+ const result = getFilledBlobs();
355
+ if (result.length < blobHashes.length) {
356
+ this.log.warn(
357
+ `Failed to fetch all blobs for ${blockHash} from all blob sources (got ${result.length}/${blobHashes.length})`,
358
+ {
359
+ l1ConsensusHostUrls: this.config.l1ConsensusHostUrls,
360
+ archiveUrl: this.archiveClient?.getBaseUrl(),
361
+ fileStoreUrls: this.fileStoreClients.map(c => c.getBaseUrl()),
362
+ },
363
+ );
364
+ }
365
+ return returnWithCallback(result);
366
+ }
367
+
368
+ /** Resolves the beacon slot number for the given block hash. Returns undefined if no consensus hosts. */
369
+ private resolveSlotNumber(
370
+ blockHash: `0x${string}`,
371
+ opts?: GetBlobSidecarOptions,
372
+ ): Promise<number | undefined> | undefined {
373
+ const { l1ConsensusHostUrls } = this.config;
374
+ if (!l1ConsensusHostUrls || l1ConsensusHostUrls.length === 0) {
375
+ return undefined;
376
+ }
377
+ // If no supernodes, no point resolving the slot
378
+ if (this.superNodeHostIndexes && this.superNodeHostIndexes.size === 0) {
379
+ return undefined;
380
+ }
381
+ return this.getSlotNumber(blockHash, opts?.parentBeaconBlockRoot, opts?.l1BlockTimestamp);
382
+ }
383
+
384
+ /**
385
+ * Try all supernode consensus hosts for blob sidecars.
386
+ * Skips hosts that were detected as non-supernodes during testSources().
387
+ */
388
+ private async tryConsensusHosts(
389
+ getSlotNumber: () => Promise<number | undefined>,
390
+ getMissingBlobHashes: () => Buffer[],
391
+ fillResults: (blobs: BlobJson[]) => Promise<Blob[]>,
392
+ ctx: { blockHash: string; blobHashes: string[] },
393
+ ): Promise<void> {
394
+ const { l1ConsensusHostUrls } = this.config;
395
+ if (!l1ConsensusHostUrls || l1ConsensusHostUrls.length === 0) {
396
+ return;
397
+ }
398
+
399
+ const slotNumber = await getSlotNumber();
400
+ if (!slotNumber) {
401
+ return;
402
+ }
403
+
404
+ for (let l1ConsensusHostIndex = 0; l1ConsensusHostIndex < l1ConsensusHostUrls.length; l1ConsensusHostIndex++) {
405
+ const missingHashes = getMissingBlobHashes();
406
+ if (missingHashes.length === 0) {
407
+ break;
408
+ }
409
+
410
+ // Skip non-supernode hosts if we've already detected supernodes
411
+ if (this.superNodeHostIndexes && !this.superNodeHostIndexes.has(l1ConsensusHostIndex)) {
412
+ this.log.trace(`Skipping non-supernode consensus host`, {
413
+ l1ConsensusHostUrl: l1ConsensusHostUrls[l1ConsensusHostIndex],
414
+ });
415
+ continue;
416
+ }
417
+
418
+ const l1ConsensusHostUrl = l1ConsensusHostUrls[l1ConsensusHostIndex];
419
+ this.log.trace(`Attempting to get ${missingHashes.length} blobs from consensus host`, {
420
+ slotNumber,
421
+ l1ConsensusHostUrl,
422
+ ...ctx,
423
+ });
424
+ const blobs = await this.getBlobsFromHost(l1ConsensusHostUrl, slotNumber, l1ConsensusHostIndex, missingHashes);
425
+ const result = await fillResults(blobs);
426
+ this.log.debug(
427
+ `Got ${blobs.length} blobs from consensus host (total: ${result.length}/${ctx.blobHashes.length})`,
428
+ { slotNumber, l1ConsensusHostUrl, ...ctx },
429
+ );
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Try all filestores once (shuffled for load distribution).
435
+ * @param getMissingBlobHashes - Function to get remaining blob hashes to fetch
436
+ * @param fillResults - Callback to fill in results
437
+ * @param ctx - Logging context
438
+ */
439
+ private async tryFileStores(
440
+ getMissingBlobHashes: () => Buffer[],
441
+ fillResults: (blobs: BlobJson[]) => Promise<Blob[]>,
442
+ ctx: { blockHash: string; blobHashes: string[] },
443
+ ): Promise<void> {
444
+ // Shuffle clients for load distribution
445
+ const shuffledClients = [...this.fileStoreClients];
446
+ shuffle(shuffledClients);
447
+
448
+ for (const client of shuffledClients) {
449
+ const blobHashes = getMissingBlobHashes();
450
+ if (blobHashes.length === 0) {
451
+ return; // All blobs found, no need to try more filestores
452
+ }
453
+
454
+ try {
455
+ const blobHashStrings = blobHashes.map(h => `0x${h.toString('hex')}`);
456
+ this.log.trace(`Attempting to get ${blobHashStrings.length} blobs from filestore`, {
457
+ url: client.getBaseUrl(),
458
+ ...ctx,
459
+ });
460
+ const blobs = await client.getBlobsByHashes(blobHashStrings);
461
+ if (blobs.length > 0) {
462
+ const result = await fillResults(blobs);
463
+ this.log.debug(
464
+ `Got ${blobs.length} blobs from filestore (total: ${result.length}/${ctx.blobHashes.length})`,
465
+ {
466
+ url: client.getBaseUrl(),
467
+ ...ctx,
468
+ },
469
+ );
470
+ }
471
+ } catch (err) {
472
+ this.log.warn(`Failed to fetch from filestore: ${err}`, { url: client.getBaseUrl() });
473
+ }
474
+ }
475
+ }
476
+
477
+ public async getBlobSidecarFrom(
478
+ hostUrl: string,
479
+ blockHashOrSlot: string | number,
480
+ blobHashes: Buffer[] = [],
481
+ l1ConsensusHostIndex?: number,
482
+ ): Promise<Blob[]> {
483
+ const blobs = await this.getBlobsFromHost(hostUrl, blockHashOrSlot, l1ConsensusHostIndex, blobHashes);
484
+ return (await processFetchedBlobs(blobs, blobHashes, this.log)).filter((b): b is Blob => b !== undefined);
485
+ }
486
+
487
+ public async getBlobsFromHost(
488
+ hostUrl: string,
489
+ blockHashOrSlot: string | number,
490
+ l1ConsensusHostIndex?: number,
491
+ blobHashes?: Buffer[],
492
+ ): Promise<BlobJson[]> {
493
+ try {
494
+ let res = await this.fetchBlobSidecars(hostUrl, blockHashOrSlot, l1ConsensusHostIndex, blobHashes);
495
+ if (res.ok) {
496
+ return await parseBlobJsonsFromResponse(await res.json(), this.log);
497
+ }
498
+
499
+ if (res.status === 404 && typeof blockHashOrSlot === 'number') {
500
+ const latestSlot = await this.getLatestSlotNumber(hostUrl, l1ConsensusHostIndex);
501
+ this.log.debug(`Requested L1 slot ${blockHashOrSlot} not found, trying out slots up to ${latestSlot}`, {
502
+ hostUrl,
503
+ status: res.status,
504
+ statusText: res.statusText,
505
+ });
506
+
507
+ let maxRetries = 10;
508
+ let currentSlot = blockHashOrSlot + 1;
509
+ while (res.status === 404 && maxRetries > 0 && latestSlot !== undefined && currentSlot <= latestSlot) {
510
+ this.log.debug(`Trying slot ${currentSlot}`);
511
+ res = await this.fetchBlobSidecars(hostUrl, currentSlot, l1ConsensusHostIndex, blobHashes);
512
+ if (res.ok) {
513
+ return await parseBlobJsonsFromResponse(await res.json(), this.log);
514
+ }
515
+ currentSlot++;
516
+ maxRetries--;
517
+ }
518
+ }
519
+
520
+ this.log.warn(`Unable to get blob sidecar for ${blockHashOrSlot}: ${res.statusText} (${res.status})`, {
521
+ status: res.status,
522
+ statusText: res.statusText,
523
+ body: await res.text().catch(() => 'Failed to read response body'),
524
+ });
525
+ return [];
526
+ } catch (error: any) {
527
+ this.log.warn(`Error getting blob sidecar from ${hostUrl}: ${error.message ?? error}`);
528
+ return [];
529
+ }
530
+ }
531
+
532
+ private fetchBlobSidecars(
533
+ hostUrl: string,
534
+ blockHashOrSlot: string | number,
535
+ l1ConsensusHostIndex?: number,
536
+ blobHashes?: Buffer[],
537
+ ): Promise<Response> {
538
+ let baseUrl = `${hostUrl}/eth/v1/beacon/blobs/${blockHashOrSlot}`;
539
+
540
+ if (blobHashes && blobHashes.length > 0) {
541
+ const params = new URLSearchParams();
542
+ for (const hash of blobHashes) {
543
+ params.append('versioned_hashes', `0x${hash.toString('hex')}`);
544
+ }
545
+ baseUrl += `?${params.toString()}`;
546
+ }
547
+
548
+ const { url, logSafeUrl, ...options } = getBeaconNodeFetchOptions(baseUrl, this.config, l1ConsensusHostIndex);
549
+ this.log.debug(`Fetching blob sidecar for ${blockHashOrSlot}`, { url: logSafeUrl, ...options });
550
+ // No retry here — this is called inside the main retry loop in getBlobSidecar
551
+ return fetch(url, options);
552
+ }
553
+
554
+ private async getLatestSlotNumber(hostUrl: string, l1ConsensusHostIndex?: number): Promise<number | undefined> {
555
+ try {
556
+ const baseUrl = `${hostUrl}/eth/v1/beacon/headers/head`;
557
+ const { url, logSafeUrl, ...options } = getBeaconNodeFetchOptions(baseUrl, this.config, l1ConsensusHostIndex);
558
+ this.log.debug(`Fetching latest slot number`, { url: logSafeUrl, ...options });
559
+ const res = await this.fetch(url, options);
560
+ if (res.ok) {
561
+ const body = await res.json();
562
+ const slot = parseInt(body.data.header.message.slot);
563
+ if (Number.isNaN(slot)) {
564
+ this.log.error(`Failed to parse slot number from response from ${hostUrl}`, { body });
565
+ return undefined;
566
+ }
567
+ return slot;
568
+ }
569
+ } catch (err) {
570
+ this.log.error(`Error getting latest slot number from ${hostUrl}`, err);
571
+ return undefined;
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Get the slot number from the consensus host
577
+ * As of eip-4788, the parentBeaconBlockRoot is included in the execution layer.
578
+ * This allows us to query the consensus layer for the slot number of the parent block, which we will then use
579
+ * to request blobs from the consensus layer.
580
+ *
581
+ * If this returns undefined, it means that we are not connected to a real consensus host, and we should
582
+ * query blobs with the blockHash.
583
+ *
584
+ * If this returns a number, then we should query blobs with the slot number
585
+ *
586
+ * @param blockHash - The block hash
587
+ * @returns The slot number
588
+ */
589
+ private async getSlotNumber(
590
+ blockHash: `0x${string}`,
591
+ parentBeaconBlockRoot?: string,
592
+ l1BlockTimestamp?: bigint,
593
+ ): Promise<number | undefined> {
594
+ const { l1ConsensusHostUrls, l1RpcUrls } = this.config;
595
+ if (!l1ConsensusHostUrls || l1ConsensusHostUrls.length === 0) {
596
+ this.log.debug('No consensus host url configured');
597
+ return undefined;
598
+ }
599
+
600
+ // Primary path: compute slot from timestamp if genesis config is cached (no network call needed)
601
+ if (
602
+ l1BlockTimestamp !== undefined &&
603
+ this.beaconGenesisTime !== undefined &&
604
+ this.beaconSecondsPerSlot !== undefined
605
+ ) {
606
+ const slot = Number((l1BlockTimestamp - this.beaconGenesisTime) / BigInt(this.beaconSecondsPerSlot));
607
+ this.log.debug(`Computed slot ${slot} from L1 block timestamp`, { l1BlockTimestamp });
608
+ return slot;
609
+ }
610
+
611
+ if (!parentBeaconBlockRoot) {
612
+ // parentBeaconBlockRoot not provided by caller — fetch it from the execution RPC
613
+ if (!l1RpcUrls || l1RpcUrls.length === 0) {
614
+ this.log.debug('No execution host url configured');
615
+ return undefined;
616
+ }
617
+
618
+ const client = createPublicClient({
619
+ transport: makeL1HttpTransport(l1RpcUrls, { timeout: this.config.l1HttpTimeoutMS }),
620
+ });
621
+ try {
622
+ const res: RpcBlock = await client.request({
623
+ method: 'eth_getBlockByHash',
624
+ params: [blockHash, /*tx flag*/ false],
625
+ });
626
+
627
+ if (res.parentBeaconBlockRoot) {
628
+ parentBeaconBlockRoot = res.parentBeaconBlockRoot;
629
+ }
630
+ } catch (err) {
631
+ this.log.error(`Error getting parent beacon block root`, err);
632
+ }
633
+ }
634
+
635
+ if (!parentBeaconBlockRoot) {
636
+ this.log.error(`No parent beacon block root found for block ${blockHash}`);
637
+ return undefined;
638
+ }
639
+
640
+ // Query beacon chain to get the slot number for that block root
641
+ let l1ConsensusHostUrl: string;
642
+ for (let l1ConsensusHostIndex = 0; l1ConsensusHostIndex < l1ConsensusHostUrls.length; l1ConsensusHostIndex++) {
643
+ l1ConsensusHostUrl = l1ConsensusHostUrls[l1ConsensusHostIndex];
644
+ try {
645
+ const { url, ...options } = getBeaconNodeFetchOptions(
646
+ `${l1ConsensusHostUrl}/eth/v1/beacon/headers/${parentBeaconBlockRoot}`,
647
+ this.config,
648
+ l1ConsensusHostIndex,
649
+ );
650
+ const res = await this.fetch(url, options);
651
+
652
+ if (res.ok) {
653
+ const body = await res.json();
654
+
655
+ // Add one to get the slot number of the original block hash
656
+ return Number(body.data.header.message.slot) + 1;
657
+ }
658
+ } catch (err) {
659
+ this.log.error(`Error getting slot number`, err);
660
+ }
661
+ }
662
+
663
+ return undefined;
664
+ }
665
+
666
+ /** @internal - exposed for testing */
667
+ public getArchiveClient(): BlobArchiveClient | undefined {
668
+ return this.archiveClient;
669
+ }
670
+
671
+ /** Returns true if this client can upload blobs to filestore. */
672
+ public canUpload(): boolean {
673
+ return this.fileStoreUploadClient !== undefined;
674
+ }
675
+
676
+ /**
677
+ * Start the blob client.
678
+ * Fetches and caches beacon genesis config for timestamp-based slot resolution,
679
+ * then uploads the initial healthcheck file (awaited) and starts periodic uploads.
680
+ */
681
+ public async start(): Promise<void> {
682
+ await this.fetchBeaconConfig();
683
+
684
+ if (!this.fileStoreUploadClient) {
685
+ return;
686
+ }
687
+
688
+ await this.fileStoreUploadClient.uploadHealthcheck();
689
+ this.log.debug('Initial healthcheck file uploaded');
690
+
691
+ this.startPeriodicHealthcheckUpload();
692
+ }
693
+
694
+ /**
695
+ * Start periodic healthcheck upload to the file store to ensure it remains available even if accidentally deleted.
696
+ */
697
+ private startPeriodicHealthcheckUpload(): void {
698
+ const intervalMs =
699
+ (this.config.blobHealthcheckUploadIntervalMinutes ?? DEFAULT_HEALTHCHECK_UPLOAD_INTERVAL_MINUTES) * 60 * 1000;
700
+
701
+ this.healthcheckUploadIntervalId = setInterval(() => {
702
+ void this.fileStoreUploadClient!.uploadHealthcheck().catch(err => {
703
+ this.log.warn('Failed to upload periodic healthcheck file', err);
704
+ });
705
+ }, intervalMs);
706
+ }
707
+
708
+ /**
709
+ * Fetches and caches beacon genesis time and slot duration from the first available consensus host.
710
+ * These static values enable timestamp-based slot resolution, eliminating the per-fetch headers call.
711
+ * Logs a warning and leaves fields undefined if all hosts fail, callers fall back gracefully.
712
+ */
713
+ private async fetchBeaconConfig(): Promise<void> {
714
+ const { l1ConsensusHostUrls } = this.config;
715
+ if (!l1ConsensusHostUrls || l1ConsensusHostUrls.length === 0) {
716
+ return;
717
+ }
718
+
719
+ for (let i = 0; i < l1ConsensusHostUrls.length; i++) {
720
+ try {
721
+ const { url: genesisUrl, ...genesisOptions } = getBeaconNodeFetchOptions(
722
+ `${l1ConsensusHostUrls[i]}/eth/v1/config/genesis`,
723
+ this.config,
724
+ i,
725
+ );
726
+ const { url: specUrl, ...specOptions } = getBeaconNodeFetchOptions(
727
+ `${l1ConsensusHostUrls[i]}/eth/v1/config/spec`,
728
+ this.config,
729
+ i,
730
+ );
731
+
732
+ const [genesisRes, specRes] = await Promise.all([
733
+ this.fetch(genesisUrl, genesisOptions),
734
+ this.fetch(specUrl, specOptions),
735
+ ]);
736
+
737
+ if (genesisRes.ok && specRes.ok) {
738
+ const genesis = await genesisRes.json();
739
+ const spec = await specRes.json();
740
+ this.beaconGenesisTime = BigInt(genesis.data.genesisTime);
741
+ this.beaconSecondsPerSlot = parseInt(spec.data.secondsPerSlot);
742
+ this.log.debug(`Fetched beacon genesis config`, {
743
+ genesisTime: this.beaconGenesisTime,
744
+ secondsPerSlot: this.beaconSecondsPerSlot,
745
+ });
746
+ return;
747
+ }
748
+ } catch (err) {
749
+ this.log.warn(`Failed to fetch beacon config from host ${l1ConsensusHostUrls[i]}`, err);
750
+ }
751
+ }
752
+ this.log.warn('Could not fetch beacon genesis config from any consensus host — will use headers call fallback');
753
+ }
754
+
755
+ /**
756
+ * Stop the blob client, clearing any periodic tasks.
757
+ */
758
+ public stop(): void {
759
+ if (this.healthcheckUploadIntervalId) {
760
+ clearInterval(this.healthcheckUploadIntervalId);
761
+ this.healthcheckUploadIntervalId = undefined;
762
+ }
763
+ }
764
+ }
765
+
766
+ async function parseBlobJsonsFromResponse(response: any, logger: Logger): Promise<BlobJson[]> {
767
+ try {
768
+ return await Promise.all((response.data as string[]).map(parseBlobJson));
769
+ } catch (err) {
770
+ logger.error(`Error parsing blob json from response`, err);
771
+ return [];
772
+ }
773
+ }
774
+
775
+ // Blobs will be in this form when requested from the blob client, or from the beacon chain via `getBlobSidecars`:
776
+ // https://ethereum.github.io/beacon-APIs/?urls.primaryName=dev#/Beacon/getBlobSidecars
777
+ // Here we attempt to parse the response data to Buffer, and check the lengths (via Blob's constructor), to avoid
778
+ // throwing an error down the line when calling Blob.fromJson().
779
+ async function parseBlobJson(rawHex: string): Promise<BlobJson> {
780
+ const blobBuffer = Buffer.from(rawHex.slice(2), 'hex');
781
+ const blob = await Blob.fromBlobBuffer(blobBuffer);
782
+ return blob.toJSON();
783
+ }
784
+
785
+ // Returns an array that maps each blob hash to the corresponding blob, or undefined if the blob is not found
786
+ // or the data does not match the commitment.
787
+ async function processFetchedBlobs(
788
+ blobs: BlobJson[],
789
+ blobHashes: Buffer[],
790
+ logger: Logger,
791
+ ): Promise<(Blob | undefined)[]> {
792
+ const requestedBlobHashes = new Set<string>(blobHashes.map(bufferToHex));
793
+ const hashToBlob = new Map<string, Blob>();
794
+ for (const blobJson of blobs) {
795
+ const hashHex = bufferToHex(computeEthVersionedBlobHash(hexToBuffer(blobJson.kzg_commitment)));
796
+ if (!requestedBlobHashes.has(hashHex) || hashToBlob.has(hashHex)) {
797
+ continue;
798
+ }
799
+
800
+ try {
801
+ const blob = await Blob.fromJson(blobJson);
802
+ hashToBlob.set(hashHex, blob);
803
+ } catch (err) {
804
+ // If the above throws, it's likely that the blob commitment does not match the hash of the blob data.
805
+ logger.error(`Error converting blob from json`, err);
806
+ }
807
+ }
808
+ return blobHashes.map(h => hashToBlob.get(bufferToHex(h)));
809
+ }
810
+
811
+ function getBeaconNodeFetchOptions(url: string, config: BlobClientConfig, l1ConsensusHostIndex?: number) {
812
+ const { l1ConsensusHostApiKeys, l1ConsensusHostApiKeyHeaders } = config;
813
+ const l1ConsensusHostApiKey =
814
+ l1ConsensusHostIndex !== undefined && l1ConsensusHostApiKeys && l1ConsensusHostApiKeys[l1ConsensusHostIndex];
815
+ const l1ConsensusHostApiKeyHeader =
816
+ l1ConsensusHostIndex !== undefined &&
817
+ l1ConsensusHostApiKeyHeaders &&
818
+ l1ConsensusHostApiKeyHeaders[l1ConsensusHostIndex];
819
+
820
+ let formattedUrl = url;
821
+ let logSafeUrl = url;
822
+ if (l1ConsensusHostApiKey && l1ConsensusHostApiKey.getValue() !== '' && !l1ConsensusHostApiKeyHeader) {
823
+ const separator = formattedUrl.includes('?') ? '&' : '?';
824
+ formattedUrl += `${separator}key=${l1ConsensusHostApiKey.getValue()}`;
825
+ logSafeUrl += `${separator}key=[REDACTED]`;
826
+ }
827
+
828
+ return {
829
+ url: formattedUrl,
830
+ logSafeUrl,
831
+ ...(l1ConsensusHostApiKey &&
832
+ l1ConsensusHostApiKeyHeader && {
833
+ headers: {
834
+ [l1ConsensusHostApiKeyHeader]: l1ConsensusHostApiKey.getValue(),
835
+ },
836
+ }),
837
+ };
838
+ }