@aztec/blob-client 0.0.1-commit.001888fc

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