@aztec/blob-client 3.0.0-nightly.20251223

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