@aztec/blob-client 0.0.1-commit.03f7ef2

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 (92) hide show
  1. package/README.md +62 -0
  2. package/dest/archive/blobscan_archive_client.d.ts +146 -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 +50 -0
  36. package/dest/client/config.d.ts.map +1 -0
  37. package/dest/client/config.js +55 -0
  38. package/dest/client/factory.d.ts +39 -0
  39. package/dest/client/factory.d.ts.map +1 -0
  40. package/dest/client/factory.js +53 -0
  41. package/dest/client/http.d.ts +63 -0
  42. package/dest/client/http.d.ts.map +1 -0
  43. package/dest/client/http.js +533 -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 +22 -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 +11 -0
  51. package/dest/client/local.d.ts.map +1 -0
  52. package/dest/client/local.js +16 -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 +50 -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 +55 -0
  63. package/dest/filestore/filestore_blob_client.d.ts.map +1 -0
  64. package/dest/filestore/filestore_blob_client.js +91 -0
  65. package/dest/filestore/index.d.ts +3 -0
  66. package/dest/filestore/index.d.ts.map +1 -0
  67. package/dest/filestore/index.js +2 -0
  68. package/package.json +94 -0
  69. package/src/archive/blobscan_archive_client.ts +176 -0
  70. package/src/archive/config.ts +14 -0
  71. package/src/archive/factory.ts +11 -0
  72. package/src/archive/fixtures/blobscan_get_blob_data.json +1 -0
  73. package/src/archive/fixtures/blobscan_get_block.json +56 -0
  74. package/src/archive/index.ts +2 -0
  75. package/src/archive/instrumentation.ts +41 -0
  76. package/src/archive/interface.ts +9 -0
  77. package/src/blobstore/blob_store_test_suite.ts +110 -0
  78. package/src/blobstore/index.ts +2 -0
  79. package/src/blobstore/interface.ts +12 -0
  80. package/src/blobstore/memory_blob_store.ts +31 -0
  81. package/src/client/bin/index.ts +35 -0
  82. package/src/client/config.ts +117 -0
  83. package/src/client/factory.ts +88 -0
  84. package/src/client/http.ts +616 -0
  85. package/src/client/index.ts +5 -0
  86. package/src/client/interface.ts +23 -0
  87. package/src/client/local.ts +25 -0
  88. package/src/client/tests.ts +62 -0
  89. package/src/encoding/index.ts +21 -0
  90. package/src/filestore/factory.ts +145 -0
  91. package/src/filestore/filestore_blob_client.ts +121 -0
  92. package/src/filestore/index.ts +2 -0
@@ -0,0 +1,616 @@
1
+ import { Blob, type BlobJson, computeEthVersionedBlobHash } from '@aztec/blob-lib';
2
+ import { shuffle } from '@aztec/foundation/array';
3
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
+ import { makeBackoff, retry } from '@aztec/foundation/retry';
5
+ import { bufferToHex, hexToBuffer } from '@aztec/foundation/string';
6
+
7
+ import { type RpcBlock, createPublicClient, fallback, http } 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 { type BlobClientConfig, getBlobClientConfigFromEnv } from './config.js';
13
+ import type { BlobClientInterface, GetBlobSidecarOptions } from './interface.js';
14
+
15
+ export class HttpBlobClient implements BlobClientInterface {
16
+ protected readonly log: Logger;
17
+ protected readonly config: BlobClientConfig;
18
+ protected readonly archiveClient: BlobArchiveClient | undefined;
19
+ protected readonly fetch: typeof fetch;
20
+ protected readonly fileStoreClients: FileStoreBlobClient[];
21
+ protected readonly fileStoreUploadClient: FileStoreBlobClient | undefined;
22
+
23
+ private disabled = false;
24
+
25
+ constructor(
26
+ config?: BlobClientConfig,
27
+ private readonly opts: {
28
+ logger?: Logger;
29
+ archiveClient?: BlobArchiveClient;
30
+ fileStoreClients?: FileStoreBlobClient[];
31
+ fileStoreUploadClient?: FileStoreBlobClient;
32
+ /** Callback fired when blobs are successfully fetched from any source */
33
+ onBlobsFetched?: (blobs: Blob[]) => void;
34
+ } = {},
35
+ ) {
36
+ this.config = config ?? getBlobClientConfigFromEnv();
37
+ this.archiveClient = opts.archiveClient ?? createBlobArchiveClient(this.config);
38
+ this.log = opts.logger ?? createLogger('blob-client:client');
39
+ this.fileStoreClients = opts.fileStoreClients ?? [];
40
+ this.fileStoreUploadClient = opts.fileStoreUploadClient;
41
+
42
+ if (this.fileStoreUploadClient && !opts.onBlobsFetched) {
43
+ this.opts.onBlobsFetched = blobs => {
44
+ this.uploadBlobsToFileStore(blobs);
45
+ };
46
+ }
47
+
48
+ this.fetch = async (...args: Parameters<typeof fetch>): Promise<Response> => {
49
+ return await retry(
50
+ () => fetch(...args),
51
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
52
+ `Fetching ${args[0]}`,
53
+ makeBackoff([1, 1, 3]),
54
+ this.log,
55
+ /*failSilently=*/ true,
56
+ );
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Upload fetched blobs to filestore (fire-and-forget).
62
+ * Called automatically when blobs are fetched from any source.
63
+ */
64
+ private uploadBlobsToFileStore(blobs: Blob[]): void {
65
+ if (!this.fileStoreUploadClient) {
66
+ return;
67
+ }
68
+
69
+ void this.fileStoreUploadClient.saveBlobs(blobs, true).catch(err => {
70
+ this.log.warn(`Failed to upload ${blobs.length} blobs to filestore`, err);
71
+ });
72
+ }
73
+
74
+ /**
75
+ * Disables or enables blob storage operations.
76
+ * When disabled, getBlobSidecar returns empty arrays and sendBlobsToFilestore returns false.
77
+ * Useful for testing scenarios where blob storage failure needs to be simulated.
78
+ * @param value - True to disable blob storage, false to enable
79
+ */
80
+ public setDisabled(value: boolean): void {
81
+ this.disabled = value;
82
+ this.log.info(`Blob storage ${value ? 'disabled' : 'enabled'}`);
83
+ }
84
+
85
+ public async testSources() {
86
+ const { l1ConsensusHostUrls } = this.config;
87
+ const archiveUrl = this.archiveClient?.getBaseUrl();
88
+ this.log.info(`Testing configured blob sources`, { l1ConsensusHostUrls, archiveUrl });
89
+
90
+ let successfulSourceCount = 0;
91
+
92
+ if (l1ConsensusHostUrls && l1ConsensusHostUrls.length > 0) {
93
+ for (let l1ConsensusHostIndex = 0; l1ConsensusHostIndex < l1ConsensusHostUrls.length; l1ConsensusHostIndex++) {
94
+ const l1ConsensusHostUrl = l1ConsensusHostUrls[l1ConsensusHostIndex];
95
+ try {
96
+ const { url, ...options } = getBeaconNodeFetchOptions(
97
+ `${l1ConsensusHostUrl}/eth/v1/beacon/headers`,
98
+ this.config,
99
+ l1ConsensusHostIndex,
100
+ );
101
+ const res = await this.fetch(url, options);
102
+ if (res.ok) {
103
+ this.log.info(`L1 consensus host is reachable`, { l1ConsensusHostUrl });
104
+ successfulSourceCount++;
105
+ } else {
106
+ this.log.error(`Failure reaching L1 consensus host: ${res.statusText} (${res.status})`, {
107
+ l1ConsensusHostUrl,
108
+ });
109
+ }
110
+ } catch (err) {
111
+ this.log.error(`Error reaching L1 consensus host`, err, { l1ConsensusHostUrl });
112
+ }
113
+ }
114
+ } else {
115
+ this.log.warn('No L1 consensus host urls configured');
116
+ }
117
+
118
+ if (this.archiveClient) {
119
+ try {
120
+ const latest = await this.archiveClient.getLatestBlock();
121
+ this.log.info(`Archive client is reachable and synced to L1 block ${latest.number}`, { latest, archiveUrl });
122
+ successfulSourceCount++;
123
+ } catch (err) {
124
+ this.log.error(`Error reaching archive client`, err, { archiveUrl });
125
+ }
126
+ } else {
127
+ this.log.warn('No archive client configured');
128
+ }
129
+
130
+ if (this.fileStoreClients.length > 0) {
131
+ for (const fileStoreClient of this.fileStoreClients) {
132
+ try {
133
+ const accessible = await fileStoreClient.testConnection();
134
+ if (accessible) {
135
+ this.log.info(`FileStore is reachable`, { url: fileStoreClient.getBaseUrl() });
136
+ successfulSourceCount++;
137
+ } else {
138
+ this.log.warn(`FileStore is not accessible`, { url: fileStoreClient.getBaseUrl() });
139
+ }
140
+ } catch (err) {
141
+ this.log.error(`Error reaching filestore`, err, { url: fileStoreClient.getBaseUrl() });
142
+ }
143
+ }
144
+ }
145
+
146
+ if (successfulSourceCount === 0) {
147
+ if (this.config.blobAllowEmptySources) {
148
+ this.log.warn('No blob sources are reachable');
149
+ } else {
150
+ throw new Error('No blob sources are reachable');
151
+ }
152
+ }
153
+ }
154
+
155
+ public async sendBlobsToFilestore(blobs: Blob[]): Promise<boolean> {
156
+ if (this.disabled) {
157
+ this.log.warn('Blob storage is disabled, not uploading blobs');
158
+ return false;
159
+ }
160
+
161
+ if (!this.fileStoreUploadClient) {
162
+ this.log.verbose('No filestore upload configured');
163
+ return false;
164
+ }
165
+
166
+ this.log.verbose(`Uploading ${blobs.length} blobs to filestore`);
167
+ try {
168
+ await this.fileStoreUploadClient.saveBlobs(blobs, true);
169
+ return true;
170
+ } catch (err) {
171
+ this.log.error('Failed to upload blobs to filestore', err);
172
+ return false;
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Get the blob sidecar
178
+ *
179
+ * If requesting from the blob client, we send the blobkHash
180
+ * If requesting from the beacon node, we send the slot number
181
+ *
182
+ * Source ordering depends on sync state:
183
+ * - Historical sync: blob client → FileStore → L1 consensus → Archive
184
+ * - Near tip sync: blob client → FileStore → L1 consensus → FileStore (with retries) → Archive (eg blobscan)
185
+ *
186
+ * @param blockHash - The block hash
187
+ * @param blobHashes - The blob hashes to fetch
188
+ * @param opts - Options including isHistoricalSync flag
189
+ * @returns The blobs
190
+ */
191
+ public async getBlobSidecar(
192
+ blockHash: `0x${string}`,
193
+ blobHashes: Buffer[],
194
+ opts?: GetBlobSidecarOptions,
195
+ ): Promise<Blob[]> {
196
+ if (this.disabled) {
197
+ this.log.warn('Blob storage is disabled, returning empty blob sidecar');
198
+ return [];
199
+ }
200
+
201
+ const isHistoricalSync = opts?.isHistoricalSync ?? false;
202
+ // Accumulate blobs across sources, preserving order and handling duplicates
203
+ // resultBlobs[i] will contain the blob for blobHashes[i], or undefined if not yet found
204
+ const resultBlobs: (Blob | undefined)[] = new Array(blobHashes.length).fill(undefined);
205
+
206
+ // Helper to get missing blob hashes that we still need to fetch
207
+ const getMissingBlobHashes = (): Buffer[] =>
208
+ blobHashes
209
+ .map((bh, i) => (resultBlobs[i] === undefined ? bh : undefined))
210
+ .filter((bh): bh is Buffer => bh !== undefined);
211
+
212
+ // Return the result, ignoring any undefined ones
213
+ const getFilledBlobs = (): Blob[] => resultBlobs.filter((b): b is Blob => b !== undefined);
214
+
215
+ // Helper to fill in results from fetched blobs
216
+ const fillResults = (fetchedBlobs: BlobJson[]): Blob[] => {
217
+ const blobs = processFetchedBlobs(fetchedBlobs, blobHashes, this.log);
218
+ // Fill in any missing positions with matching blobs
219
+ for (let i = 0; i < blobHashes.length; i++) {
220
+ if (resultBlobs[i] === undefined) {
221
+ resultBlobs[i] = blobs[i];
222
+ }
223
+ }
224
+ return getFilledBlobs();
225
+ };
226
+
227
+ // Fire callback when returning blobs (fire-and-forget)
228
+ const returnWithCallback = (blobs: Blob[]): Blob[] => {
229
+ if (blobs.length > 0 && this.opts.onBlobsFetched) {
230
+ void Promise.resolve().then(() => this.opts.onBlobsFetched!(blobs));
231
+ }
232
+ return blobs;
233
+ };
234
+
235
+ const { l1ConsensusHostUrls } = this.config;
236
+
237
+ const ctx = { blockHash, blobHashes: blobHashes.map(bufferToHex) };
238
+
239
+ // Try filestore (quick, no retries) - useful for both historical and near-tip sync
240
+ if (this.fileStoreClients.length > 0 && getMissingBlobHashes().length > 0) {
241
+ await this.tryFileStores(getMissingBlobHashes, fillResults, ctx);
242
+ if (getMissingBlobHashes().length === 0) {
243
+ return returnWithCallback(getFilledBlobs());
244
+ }
245
+ }
246
+
247
+ const missingAfterSink = getMissingBlobHashes();
248
+ if (missingAfterSink.length > 0 && l1ConsensusHostUrls && l1ConsensusHostUrls.length > 0) {
249
+ // The beacon api can query by slot number, so we get that first
250
+ const consensusCtx = { l1ConsensusHostUrls, ...ctx };
251
+ this.log.trace(`Attempting to get slot number for block hash`, consensusCtx);
252
+ const slotNumber = await this.getSlotNumber(blockHash);
253
+ this.log.debug(`Got slot number ${slotNumber} from consensus host for querying blobs`, consensusCtx);
254
+
255
+ if (slotNumber) {
256
+ let l1ConsensusHostUrl: string;
257
+ for (let l1ConsensusHostIndex = 0; l1ConsensusHostIndex < l1ConsensusHostUrls.length; l1ConsensusHostIndex++) {
258
+ const missingHashes = getMissingBlobHashes();
259
+ if (missingHashes.length === 0) {
260
+ break;
261
+ }
262
+
263
+ l1ConsensusHostUrl = l1ConsensusHostUrls[l1ConsensusHostIndex];
264
+ this.log.trace(`Attempting to get ${missingHashes.length} blobs from consensus host`, {
265
+ slotNumber,
266
+ l1ConsensusHostUrl,
267
+ ...ctx,
268
+ });
269
+ const blobs = await this.getBlobsFromHost(l1ConsensusHostUrl, slotNumber, l1ConsensusHostIndex);
270
+ const result = fillResults(blobs);
271
+ this.log.debug(
272
+ `Got ${blobs.length} blobs from consensus host (total: ${result.length}/${blobHashes.length})`,
273
+ { slotNumber, l1ConsensusHostUrl, ...ctx },
274
+ );
275
+ if (result.length === blobHashes.length) {
276
+ return returnWithCallback(result);
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ // For near-tip sync, retry filestores with backoff (eventual consistency)
283
+ // This handles the case where blobs are still being uploaded by other validators
284
+ if (!isHistoricalSync && this.fileStoreClients.length > 0 && getMissingBlobHashes().length > 0) {
285
+ try {
286
+ await retry(
287
+ async () => {
288
+ await this.tryFileStores(getMissingBlobHashes, fillResults, ctx);
289
+ if (getMissingBlobHashes().length > 0) {
290
+ throw new Error('Still missing blobs from filestores');
291
+ }
292
+ },
293
+ 'filestore blob retrieval',
294
+ makeBackoff([1, 1, 2]),
295
+ this.log,
296
+ true, // failSilently - expected to fail during eventual consistency
297
+ );
298
+ return returnWithCallback(getFilledBlobs());
299
+ } catch {
300
+ // Exhausted retries, continue to archive fallback
301
+ }
302
+ }
303
+
304
+ const missingAfterConsensus = getMissingBlobHashes();
305
+ if (missingAfterConsensus.length > 0 && this.archiveClient) {
306
+ const archiveCtx = { archiveUrl: this.archiveClient.getBaseUrl(), ...ctx };
307
+ this.log.trace(`Attempting to get ${missingAfterConsensus.length} blobs from archive`, archiveCtx);
308
+ const allBlobs = await this.archiveClient.getBlobsFromBlock(blockHash);
309
+ if (!allBlobs) {
310
+ this.log.debug('No blobs found from archive client', archiveCtx);
311
+ } else {
312
+ this.log.trace(`Got ${allBlobs.length} blobs from archive client before filtering`, archiveCtx);
313
+ const result = fillResults(allBlobs);
314
+ this.log.debug(
315
+ `Got ${allBlobs.length} blobs from archive client (total: ${result.length}/${blobHashes.length})`,
316
+ archiveCtx,
317
+ );
318
+ if (result.length === blobHashes.length) {
319
+ return returnWithCallback(result);
320
+ }
321
+ }
322
+ }
323
+
324
+ const result = getFilledBlobs();
325
+ if (result.length < blobHashes.length) {
326
+ this.log.warn(
327
+ `Failed to fetch all blobs for ${blockHash} from all blob sources (got ${result.length}/${blobHashes.length})`,
328
+ {
329
+ l1ConsensusHostUrls,
330
+ archiveUrl: this.archiveClient?.getBaseUrl(),
331
+ fileStoreUrls: this.fileStoreClients.map(c => c.getBaseUrl()),
332
+ },
333
+ );
334
+ }
335
+ return returnWithCallback(result);
336
+ }
337
+
338
+ /**
339
+ * Try all filestores once (shuffled for load distribution).
340
+ * @param getMissingBlobHashes - Function to get remaining blob hashes to fetch
341
+ * @param fillResults - Callback to fill in results
342
+ * @param ctx - Logging context
343
+ */
344
+ private async tryFileStores(
345
+ getMissingBlobHashes: () => Buffer[],
346
+ fillResults: (blobs: BlobJson[]) => Blob[],
347
+ ctx: { blockHash: string; blobHashes: string[] },
348
+ ): Promise<void> {
349
+ // Shuffle clients for load distribution
350
+ const shuffledClients = [...this.fileStoreClients];
351
+ shuffle(shuffledClients);
352
+
353
+ for (const client of shuffledClients) {
354
+ const blobHashes = getMissingBlobHashes();
355
+ if (blobHashes.length === 0) {
356
+ return; // All blobs found, no need to try more filestores
357
+ }
358
+
359
+ try {
360
+ const blobHashStrings = blobHashes.map(h => `0x${h.toString('hex')}`);
361
+ this.log.trace(`Attempting to get ${blobHashStrings.length} blobs from filestore`, {
362
+ url: client.getBaseUrl(),
363
+ ...ctx,
364
+ });
365
+ const blobs = await client.getBlobsByHashes(blobHashStrings);
366
+ if (blobs.length > 0) {
367
+ const result = fillResults(blobs);
368
+ this.log.debug(
369
+ `Got ${blobs.length} blobs from filestore (total: ${result.length}/${ctx.blobHashes.length})`,
370
+ {
371
+ url: client.getBaseUrl(),
372
+ ...ctx,
373
+ },
374
+ );
375
+ }
376
+ } catch (err) {
377
+ this.log.warn(`Failed to fetch from filestore: ${err}`, { url: client.getBaseUrl() });
378
+ }
379
+ }
380
+ }
381
+
382
+ public async getBlobSidecarFrom(
383
+ hostUrl: string,
384
+ blockHashOrSlot: string | number,
385
+ blobHashes: Buffer[] = [],
386
+ l1ConsensusHostIndex?: number,
387
+ ): Promise<Blob[]> {
388
+ const blobs = await this.getBlobsFromHost(hostUrl, blockHashOrSlot, l1ConsensusHostIndex);
389
+ return processFetchedBlobs(blobs, blobHashes, this.log).filter((b): b is Blob => b !== undefined);
390
+ }
391
+
392
+ public async getBlobsFromHost(
393
+ hostUrl: string,
394
+ blockHashOrSlot: string | number,
395
+ l1ConsensusHostIndex?: number,
396
+ ): Promise<BlobJson[]> {
397
+ try {
398
+ let res = await this.fetchBlobSidecars(hostUrl, blockHashOrSlot, l1ConsensusHostIndex);
399
+ if (res.ok) {
400
+ return parseBlobJsonsFromResponse(await res.json(), this.log);
401
+ }
402
+
403
+ if (res.status === 404 && typeof blockHashOrSlot === 'number') {
404
+ const latestSlot = await this.getLatestSlotNumber(hostUrl, l1ConsensusHostIndex);
405
+ this.log.debug(`Requested L1 slot ${blockHashOrSlot} not found, trying out slots up to ${latestSlot}`, {
406
+ hostUrl,
407
+ status: res.status,
408
+ statusText: res.statusText,
409
+ });
410
+
411
+ let maxRetries = 10;
412
+ let currentSlot = blockHashOrSlot + 1;
413
+ while (res.status === 404 && maxRetries > 0 && latestSlot !== undefined && currentSlot <= latestSlot) {
414
+ this.log.debug(`Trying slot ${currentSlot}`);
415
+ res = await this.fetchBlobSidecars(hostUrl, currentSlot, l1ConsensusHostIndex);
416
+ if (res.ok) {
417
+ return parseBlobJsonsFromResponse(await res.json(), this.log);
418
+ }
419
+ currentSlot++;
420
+ maxRetries--;
421
+ }
422
+ }
423
+
424
+ this.log.warn(`Unable to get blob sidecar for ${blockHashOrSlot}: ${res.statusText} (${res.status})`, {
425
+ status: res.status,
426
+ statusText: res.statusText,
427
+ body: await res.text().catch(() => 'Failed to read response body'),
428
+ });
429
+ return [];
430
+ } catch (error: any) {
431
+ this.log.warn(`Error getting blob sidecar from ${hostUrl}: ${error.message ?? error}`);
432
+ return [];
433
+ }
434
+ }
435
+
436
+ private fetchBlobSidecars(
437
+ hostUrl: string,
438
+ blockHashOrSlot: string | number,
439
+ l1ConsensusHostIndex?: number,
440
+ ): Promise<Response> {
441
+ const baseUrl = `${hostUrl}/eth/v1/beacon/blob_sidecars/${blockHashOrSlot}`;
442
+
443
+ const { url, ...options } = getBeaconNodeFetchOptions(baseUrl, this.config, l1ConsensusHostIndex);
444
+ this.log.debug(`Fetching blob sidecar for ${blockHashOrSlot}`, { url, ...options });
445
+ return this.fetch(url, options);
446
+ }
447
+
448
+ private async getLatestSlotNumber(hostUrl: string, l1ConsensusHostIndex?: number): Promise<number | undefined> {
449
+ try {
450
+ const baseUrl = `${hostUrl}/eth/v1/beacon/headers/head`;
451
+ const { url, ...options } = getBeaconNodeFetchOptions(baseUrl, this.config, l1ConsensusHostIndex);
452
+ this.log.debug(`Fetching latest slot number`, { url, ...options });
453
+ const res = await this.fetch(url, options);
454
+ if (res.ok) {
455
+ const body = await res.json();
456
+ const slot = parseInt(body.data.header.message.slot);
457
+ if (Number.isNaN(slot)) {
458
+ this.log.error(`Failed to parse slot number from response from ${hostUrl}`, { body });
459
+ return undefined;
460
+ }
461
+ return slot;
462
+ }
463
+ } catch (err) {
464
+ this.log.error(`Error getting latest slot number from ${hostUrl}`, err);
465
+ return undefined;
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Get the slot number from the consensus host
471
+ * As of eip-4788, the parentBeaconBlockRoot is included in the execution layer.
472
+ * This allows us to query the consensus layer for the slot number of the parent block, which we will then use
473
+ * to request blobs from the consensus layer.
474
+ *
475
+ * If this returns undefined, it means that we are not connected to a real consensus host, and we should
476
+ * query blobs with the blockHash.
477
+ *
478
+ * If this returns a number, then we should query blobs with the slot number
479
+ *
480
+ * @param blockHash - The block hash
481
+ * @returns The slot number
482
+ */
483
+ private async getSlotNumber(blockHash: `0x${string}`): Promise<number | undefined> {
484
+ const { l1ConsensusHostUrls, l1RpcUrls } = this.config;
485
+ if (!l1ConsensusHostUrls || l1ConsensusHostUrls.length === 0) {
486
+ this.log.debug('No consensus host url configured');
487
+ return undefined;
488
+ }
489
+
490
+ if (!l1RpcUrls || l1RpcUrls.length === 0) {
491
+ this.log.debug('No execution host url configured');
492
+ return undefined;
493
+ }
494
+
495
+ // Ping execution node to get the parentBeaconBlockRoot for this block
496
+ let parentBeaconBlockRoot: string | undefined;
497
+ const client = createPublicClient({
498
+ transport: fallback(l1RpcUrls.map(url => http(url, { batch: false }))),
499
+ });
500
+ try {
501
+ const res: RpcBlock = await client.request({
502
+ method: 'eth_getBlockByHash',
503
+ params: [blockHash, /*tx flag*/ false],
504
+ });
505
+
506
+ if (res.parentBeaconBlockRoot) {
507
+ parentBeaconBlockRoot = res.parentBeaconBlockRoot;
508
+ }
509
+ } catch (err) {
510
+ this.log.error(`Error getting parent beacon block root`, err);
511
+ }
512
+
513
+ if (!parentBeaconBlockRoot) {
514
+ this.log.error(`No parent beacon block root found for block ${blockHash}`);
515
+ return undefined;
516
+ }
517
+
518
+ // Query beacon chain to get the slot number for that block root
519
+ let l1ConsensusHostUrl: string;
520
+ for (let l1ConsensusHostIndex = 0; l1ConsensusHostIndex < l1ConsensusHostUrls.length; l1ConsensusHostIndex++) {
521
+ l1ConsensusHostUrl = l1ConsensusHostUrls[l1ConsensusHostIndex];
522
+ try {
523
+ const { url, ...options } = getBeaconNodeFetchOptions(
524
+ `${l1ConsensusHostUrl}/eth/v1/beacon/headers/${parentBeaconBlockRoot}`,
525
+ this.config,
526
+ l1ConsensusHostIndex,
527
+ );
528
+ const res = await this.fetch(url, options);
529
+
530
+ if (res.ok) {
531
+ const body = await res.json();
532
+
533
+ // Add one to get the slot number of the original block hash
534
+ return Number(body.data.header.message.slot) + 1;
535
+ }
536
+ } catch (err) {
537
+ this.log.error(`Error getting slot number`, err);
538
+ }
539
+ }
540
+
541
+ return undefined;
542
+ }
543
+
544
+ /** @internal - exposed for testing */
545
+ public getArchiveClient(): BlobArchiveClient | undefined {
546
+ return this.archiveClient;
547
+ }
548
+ }
549
+
550
+ function parseBlobJsonsFromResponse(response: any, logger: Logger): BlobJson[] {
551
+ try {
552
+ const blobs = response.data.map(parseBlobJson);
553
+ return blobs;
554
+ } catch (err) {
555
+ logger.error(`Error parsing blob json from response`, err);
556
+ return [];
557
+ }
558
+ }
559
+
560
+ // Blobs will be in this form when requested from the blob client, or from the beacon chain via `getBlobSidecars`:
561
+ // https://ethereum.github.io/beacon-APIs/?urls.primaryName=dev#/Beacon/getBlobSidecars
562
+ // Here we attempt to parse the response data to Buffer, and check the lengths (via Blob's constructor), to avoid
563
+ // throwing an error down the line when calling Blob.fromJson().
564
+ function parseBlobJson(data: any): BlobJson {
565
+ const blobBuffer = Buffer.from(data.blob.slice(2), 'hex');
566
+ const commitmentBuffer = Buffer.from(data.kzg_commitment.slice(2), 'hex');
567
+ const blob = new Blob(blobBuffer, commitmentBuffer);
568
+ return blob.toJSON();
569
+ }
570
+
571
+ // Returns an array that maps each blob hash to the corresponding blob, or undefined if the blob is not found
572
+ // or the data does not match the commitment.
573
+ function processFetchedBlobs(blobs: BlobJson[], blobHashes: Buffer[], logger: Logger): (Blob | undefined)[] {
574
+ const requestedBlobHashes = new Set<string>(blobHashes.map(bufferToHex));
575
+ const hashToBlob = new Map<string, Blob>();
576
+ for (const blobJson of blobs) {
577
+ const hashHex = bufferToHex(computeEthVersionedBlobHash(hexToBuffer(blobJson.kzg_commitment)));
578
+ if (!requestedBlobHashes.has(hashHex) || hashToBlob.has(hashHex)) {
579
+ continue;
580
+ }
581
+
582
+ try {
583
+ const blob = Blob.fromJson(blobJson);
584
+ hashToBlob.set(hashHex, blob);
585
+ } catch (err) {
586
+ // If the above throws, it's likely that the blob commitment does not match the hash of the blob data.
587
+ logger.error(`Error converting blob from json`, err);
588
+ }
589
+ }
590
+ return blobHashes.map(h => hashToBlob.get(bufferToHex(h)));
591
+ }
592
+
593
+ function getBeaconNodeFetchOptions(url: string, config: BlobClientConfig, l1ConsensusHostIndex?: number) {
594
+ const { l1ConsensusHostApiKeys, l1ConsensusHostApiKeyHeaders } = config;
595
+ const l1ConsensusHostApiKey =
596
+ l1ConsensusHostIndex !== undefined && l1ConsensusHostApiKeys && l1ConsensusHostApiKeys[l1ConsensusHostIndex];
597
+ const l1ConsensusHostApiKeyHeader =
598
+ l1ConsensusHostIndex !== undefined &&
599
+ l1ConsensusHostApiKeyHeaders &&
600
+ l1ConsensusHostApiKeyHeaders[l1ConsensusHostIndex];
601
+
602
+ let formattedUrl = url;
603
+ if (l1ConsensusHostApiKey && l1ConsensusHostApiKey.getValue() !== '' && !l1ConsensusHostApiKeyHeader) {
604
+ formattedUrl += `${formattedUrl.includes('?') ? '&' : '?'}key=${l1ConsensusHostApiKey.getValue()}`;
605
+ }
606
+
607
+ return {
608
+ url: formattedUrl,
609
+ ...(l1ConsensusHostApiKey &&
610
+ l1ConsensusHostApiKeyHeader && {
611
+ headers: {
612
+ [l1ConsensusHostApiKeyHeader]: l1ConsensusHostApiKey.getValue(),
613
+ },
614
+ }),
615
+ };
616
+ }
@@ -0,0 +1,5 @@
1
+ export * from './http.js';
2
+ export * from './local.js';
3
+ export * from './interface.js';
4
+ export * from './factory.js';
5
+ export * from './config.js';
@@ -0,0 +1,23 @@
1
+ import type { Blob } from '@aztec/blob-lib';
2
+
3
+ /**
4
+ * Options for getBlobSidecar method.
5
+ */
6
+ export interface GetBlobSidecarOptions {
7
+ /**
8
+ * True if the archiver is catching up (historical sync), false if near tip.
9
+ * This affects source ordering:
10
+ * - Historical: FileStore first (data should exist), then L1 consensus, then archive (eg. blobscan)
11
+ * - Near tip: FileStore first with no retries (data should exist), L1 consensus second (freshest data), then FileStore with retries, then archive (eg. blobscan)
12
+ */
13
+ isHistoricalSync?: boolean;
14
+ }
15
+
16
+ export interface BlobClientInterface {
17
+ /** Sends the given blobs to the filestore, to be indexed by blob hash. */
18
+ sendBlobsToFilestore(blobs: Blob[]): Promise<boolean>;
19
+ /** Fetches the given blob sidecars by block hash and blob hashes. */
20
+ getBlobSidecar(blockId: string, blobHashes?: Buffer[], opts?: GetBlobSidecarOptions): Promise<Blob[]>;
21
+ /** Tests all configured blob sources and logs whether they are reachable or not. */
22
+ testSources(): Promise<void>;
23
+ }
@@ -0,0 +1,25 @@
1
+ import type { Blob } from '@aztec/blob-lib';
2
+
3
+ import type { BlobStore } from '../blobstore/index.js';
4
+ import type { BlobClientInterface, GetBlobSidecarOptions } from './interface.js';
5
+
6
+ export class LocalBlobClient implements BlobClientInterface {
7
+ private readonly blobStore: BlobStore;
8
+
9
+ constructor(blobStore: BlobStore) {
10
+ this.blobStore = blobStore;
11
+ }
12
+
13
+ public testSources(): Promise<void> {
14
+ return Promise.resolve();
15
+ }
16
+
17
+ public async sendBlobsToFilestore(blobs: Blob[]): Promise<boolean> {
18
+ await this.blobStore.addBlobs(blobs);
19
+ return true;
20
+ }
21
+
22
+ public getBlobSidecar(_blockId: string, blobHashes: Buffer[], _opts?: GetBlobSidecarOptions): Promise<Blob[]> {
23
+ return this.blobStore.getBlobsByHashes(blobHashes);
24
+ }
25
+ }