@aztec/stdlib 2.1.0-rc.1 → 2.1.0-rc.3

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.
@@ -59,4 +59,6 @@ export declare function getProofSubmissionDeadlineEpoch(epochNumber: bigint, con
59
59
  * Computed as the start of the given epoch plus the proof submission window.
60
60
  */
61
61
  export declare function getProofSubmissionDeadlineTimestamp(epochNumber: bigint, constants: Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration' | 'epochDuration' | 'proofSubmissionEpochs'>): bigint;
62
+ /** Returns the timestamp to start building a block for a given L2 slot. Computed as the start timestamp of the slot minus one L1 slot duration. */
63
+ export declare function getSlotStartBuildTimestamp(slotNumber: number | bigint, constants: Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration' | 'ethereumSlotDuration'>): number;
62
64
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/epoch-helpers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,MAAM,MAAM,iBAAiB,GAAG;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,qBAAqB,EAAE,MAAM,CAAC;CAC/B,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,iBAOpC,CAAC;AAEF,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;EAOE,CAAC;AAEvC,iDAAiD;AACjD,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,cAAc,CAAC,UAGrE;AAED,qDAAqD;AACrD,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,M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C,GAC9G,CAAC,MAAM,EAAE,MAAM,CAAC,CASlB;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,cAAc,GAAG,eAAe,CAAC,UAIvF;AAED;;;GAGG;AACH,wBAAgB,+BAA+B,CAC7C,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,IAAI,CAAC,iBAAiB,EAAE,uBAAuB,CAAC,UAG5D;AAED;;;GAGG;AACH,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,cAAc,GAAG,eAAe,GAAG,uBAAuB,CAAC,UAOjH;AAED,mJAAmJ;AACnJ,wBAAgB,0BAA0B,CACxC,UAAU,EAAE,MAAM,GAAG,MAAM,EAC3B,SAAS,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,cAAc,GAAG,sBAAsB,CAAC,GAC5F,MAAM,CAER"}
@@ -68,3 +68,6 @@ export const L1RollupConstantsSchema = z.object({
68
68
  const [deadlineSlot] = getSlotRangeForEpoch(deadlineEpoch, constants);
69
69
  return getTimestampForSlot(deadlineSlot, constants);
70
70
  }
71
+ /** Returns the timestamp to start building a block for a given L2 slot. Computed as the start timestamp of the slot minus one L1 slot duration. */ export function getSlotStartBuildTimestamp(slotNumber, constants) {
72
+ return Number(constants.l1GenesisTime) + Number(slotNumber) * constants.slotDuration - constants.ethereumSlotDuration;
73
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/file-store/factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAgB,MAAM,uBAAuB,CAAC;AAIlE,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AASnE,wBAAsB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;AAC3F,wBAAsB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;AAgC9F,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAC3G,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC"}
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src/file-store/factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAgB,MAAM,uBAAuB,CAAC;AAIlE,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAWnE,wBAAsB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;AAC3F,wBAAsB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;AA6C9F,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAC3G,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC"}
@@ -2,8 +2,10 @@ import { createLogger } from '@aztec/foundation/log';
2
2
  import { GoogleCloudFileStore } from './gcs.js';
3
3
  import { HttpFileStore } from './http.js';
4
4
  import { LocalFileStore } from './local.js';
5
+ import { S3FileStore } from './s3.js';
5
6
  const supportedExamples = [
6
7
  `gs://bucket-name/path/to/store`,
8
+ `s3://bucket-name/path/to/store`,
7
9
  `file:///absolute/local/path/to/store`,
8
10
  `https://host/path`
9
11
  ];
@@ -30,6 +32,22 @@ export async function createFileStore(config, logger = createLogger('stdlib:file
30
32
  } catch {
31
33
  throw new Error(`Invalid google cloud store definition: '${config}'.`);
32
34
  }
35
+ } else if (config.startsWith('s3://')) {
36
+ try {
37
+ const url = new URL(config);
38
+ const bucket = url.host;
39
+ const path = url.pathname.replace(/^\/+/, '');
40
+ const endpoint = url.searchParams.get('endpoint');
41
+ const publicBaseUrl = url.searchParams.get('publicBaseUrl') ?? undefined;
42
+ logger.info(`Creating S3 file store at ${bucket} ${path}`);
43
+ const store = new S3FileStore(bucket, path, {
44
+ endpoint: endpoint ?? undefined,
45
+ publicBaseUrl
46
+ });
47
+ return store;
48
+ } catch {
49
+ throw new Error(`Invalid S3 store definition: '${config}'.`);
50
+ }
33
51
  } else {
34
52
  throw new Error(`Unknown file store config: '${config}'. Supported values are ${supportedExamples.join(', ')}.`);
35
53
  }
@@ -14,9 +14,15 @@ export type FileStoreSaveOptions = {
14
14
  };
15
15
  /** Simple file store. */
16
16
  export interface FileStore extends ReadOnlyFileStore {
17
- /** Saves contents to the given path. Returns an URI that can be used later to `read` the file. */
17
+ /**
18
+ * Saves contents to the given path. Returns an URI that can be used later to `read` the file.
19
+ * Default: `compress` is false unless explicitly set.
20
+ */
18
21
  save(path: string, data: Buffer, opts?: FileStoreSaveOptions): Promise<string>;
19
- /** Uploads contents from a local file. Returns an URI that can be used later to `read` the file. */
22
+ /**
23
+ * Uploads contents from a local file. Returns an URI that can be used later to `read` the file.
24
+ * Default: `compress` is true unless explicitly set to false.
25
+ */
20
26
  upload(destPath: string, srcPath: string, opts?: FileStoreSaveOptions): Promise<string>;
21
27
  }
22
28
  //# sourceMappingURL=interface.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"interface.d.ts","sourceRoot":"","sources":["../../src/file-store/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AM,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC7C;AAED,MAAM,MAAM,oBAAoB,GAAG;IAAE,MAAM,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC;AAE/G,yBAAyB;AACzB,MAAM,WAAW,SAAU,SAAQ,iBAAiB;IAClD;;;OAGG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/E;;;OAGG;IACH,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACzF"}
@@ -0,0 +1,26 @@
1
+ import { type Logger } from '@aztec/foundation/log';
2
+ import type { FileStore, FileStoreSaveOptions } from './interface.js';
3
+ export declare class S3FileStore implements FileStore {
4
+ private readonly bucketName;
5
+ private readonly basePath;
6
+ private readonly log;
7
+ private readonly s3;
8
+ private readonly region;
9
+ private readonly endpoint?;
10
+ private readonly publicBaseUrl?;
11
+ constructor(bucketName: string, basePath: string, opts: {
12
+ endpoint?: string;
13
+ publicBaseUrl?: string;
14
+ }, log?: Logger);
15
+ save(path: string, data: Buffer, opts?: FileStoreSaveOptions): Promise<string>;
16
+ upload(destPath: string, srcPath: string, opts?: FileStoreSaveOptions): Promise<string>;
17
+ read(pathOrUrlStr: string): Promise<Buffer>;
18
+ download(pathOrUrlStr: string, destPath: string): Promise<void>;
19
+ exists(pathOrUrlStr: string): Promise<boolean>;
20
+ private extractUserMetadata;
21
+ private detectContentType;
22
+ private buildReturnedUrl;
23
+ private getBucketAndKey;
24
+ private getFullPath;
25
+ }
26
+ //# sourceM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O,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,iBAAiB;IAsBzB,OAAO,CAAC,gBAAgB;IA0BxB,OAAO,CAAC,eAAe;IA2BvB,OAAO,CAAC,WAAW;CAKpB"}
@@ -0,0 +1,252 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+ import { GetObjectCommand, HeadObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
3
+ import { createReadStream, createWriteStream } from 'fs';
4
+ import { mkdir, mkdtemp, stat, unlink } from 'fs/promises';
5
+ import { tmpdir } from 'os';
6
+ import { basename, dirname, join } from 'path';
7
+ import { finished } from 'stream/promises';
8
+ import { createGzip } from 'zlib';
9
+ function normalizeBasePath(path) {
10
+ return path?.replace(/^\/+|\/+$/g, '') ?? '';
11
+ }
12
+ export class S3FileStore {
13
+ bucketName;
14
+ basePath;
15
+ log;
16
+ s3;
17
+ region;
18
+ endpoint;
19
+ publicBaseUrl;
20
+ constructor(bucketName, basePath, opts, log = createLogger('stdlib:s3-file-store')){
21
+ this.bucketName = bucketName;
22
+ this.basePath = basePath;
23
+ this.log = log;
24
+ this.endpoint = opts.endpoint;
25
+ this.region = this.endpoint ? 'auto' : process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? 'us-east-1';
26
+ this.publicBaseUrl = opts.publicBaseUrl;
27
+ const clientOptions = {};
28
+ if (this.endpoint) {
29
+ clientOptions.region = 'auto';
30
+ clientOptions.endpoint = this.endpoint;
31
+ clientOptions.forcePathStyle = true;
32
+ } else {
33
+ clientOptions.region = this.region;
34
+ }
35
+ this.s3 = new S3Client(clientOptions);
36
+ }
37
+ async save(path, data, opts = {}) {
38
+ const key = this.getFullPath(path);
39
+ const shouldCompress = !!opts.compress;
40
+ const body = shouldCompress ? (await import('zlib')).gzipSync(data) : data;
41
+ const contentLength = body.length;
42
+ const contentType = this.detectContentType(key, shouldCompress);
43
+ const put = new PutObjectCommand({
44
+ Bucket: this.bucketName,
45
+ Key: key,
46
+ Body: body,
47
+ ContentType: contentType,
48
+ CacheControl: opts.metadata?.['Cache-control'],
49
+ Metadata: this.extractUserMetadata(opts.metadata),
50
+ ContentLength: contentLength
51
+ });
52
+ await this.s3.send(put);
53
+ return this.buildReturnedUrl(key, !!opts.public);
54
+ }
55
+ async upload(destPath, srcPath, opts = {}) {
56
+ const key = this.getFullPath(destPath);
57
+ const shouldCompress = opts.compress !== false; // default true like GCS impl
58
+ await mkdir(dirname(srcPath), {
59
+ recursive: true
60
+ }).catch(()=>undefined);
61
+ let contentLength;
62
+ let bodyPath = srcPath;
63
+ // We don't set Content-Encoding and we avoid SigV4 streaming (aws-chunked).
64
+ // With AWS SigV4 streaming uploads (Content-Encoding: aws-chunked[,gzip]), servers require
65
+ // x-amz-decoded-content-length (the size of the decoded payload) and an exact Content-Length
66
+ // that includes chunk metadata. For on-the-fly compression, providing
67
+ // those values without buffering or a pre-pass is impractical. Instead, we pre-gzip to a temp file
68
+ // to know ContentLength up-front and upload the gzipped bytes as-is, omitting Content-Encoding.
69
+ // Reference: AWS SigV4 streaming (chunked upload) requirements —
70
+ // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
71
+ if (shouldCompress) {
72
+ // Pre-gzip to a temp file so we know the exact length for R2/S3 headers
73
+ const tmpDir = await mkdtemp(join(tmpdir(), 's3-upload-'));
74
+ const gzPath = join(tmpDir, `${basename(srcPath)}.gz`);
75
+ const source = createReadStream(srcPath);
76
+ const gz = createGzip();
77
+ const out = createWriteStream(gzPath);
78
+ try {
79
+ await finished(source.pipe(gz).pipe(out));
80
+ const st = await stat(gzPath);
81
+ contentLength = st.size;
82
+ bodyPath = gzPath;
83
+ } catch (err) {
84
+ // Ensure temp file is removed on failure
85
+ await unlink(gzPath).catch(()=>undefined);
86
+ throw err;
87
+ }
88
+ } else {
89
+ const st = await stat(srcPath);
90
+ contentLength = st.size;
91
+ bodyPath = srcPath;
92
+ }
93
+ const bodyStream = createReadStream(bodyPath);
94
+ const contentType = this.detectContentType(key, shouldCompress);
95
+ try {
96
+ const put = new PutObjectCommand({
97
+ Bucket: this.bucketName,
98
+ Key: key,
99
+ Body: bodyStream,
100
+ ContentType: contentType,
101
+ CacheControl: opts.metadata?.['Cache-control'],
102
+ Metadata: this.extractUserMetadata(opts.metadata),
103
+ // Explicitly set ContentLength so R2 can compute x-amz-decoded-content-length correctly
104
+ ContentLength: contentLength
105
+ });
106
+ await this.s3.send(put);
107
+ } finally{
108
+ if (shouldCompress && bodyPath !== srcPath) {
109
+ await unlink(bodyPath).catch(()=>undefined);
110
+ }
111
+ }
112
+ return this.buildReturnedUrl(key, !!opts.public);
113
+ }
114
+ async read(pathOrUrlStr) {
115
+ const { bucket, key } = this.getBucketAndKey(pathOrUrlStr);
116
+ const out = await this.s3.send(new GetObjectCommand({
117
+ Bucket: bucket,
118
+ Key: key
119
+ }));
120
+ const stream = out.Body;
121
+ const chunks = [];
122
+ for await (const chunk of stream){
123
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
124
+ }
125
+ return Buffer.concat(chunks);
126
+ }
127
+ async download(pathOrUrlStr, destPath) {
128
+ const { bucket, key } = this.getBucketAndKey(pathOrUrlStr);
129
+ const out = await this.s3.send(new GetObjectCommand({
130
+ Bucket: bucket,
131
+ Key: key
132
+ }));
133
+ await mkdir(dirname(destPath), {
134
+ recursive: true
135
+ });
136
+ const write = createWriteStream(destPath);
137
+ await finished(out.Body.pipe(write));
138
+ }
139
+ async exists(pathOrUrlStr) {
140
+ try {
141
+ const { bucket, key } = this.getBucketAndKey(pathOrUrlStr);
142
+ await this.s3.send(new HeadObjectCommand({
143
+ Bucket: bucket,
144
+ Key: key
145
+ }));
146
+ return true;
147
+ } catch (err) {
148
+ const code = err?.$metadata?.httpStatusCode ?? err?.name ?? err?.Code;
149
+ if (code === 404 || code === 'NotFound' || code === 'NoSuchKey') {
150
+ return false;
151
+ }
152
+ this.log.warn(`Error checking existence for ${pathOrUrlStr}: ${err?.message ?? String(err)}`);
153
+ return false;
154
+ }
155
+ }
156
+ extractUserMetadata(meta) {
157
+ if (!meta) {
158
+ return undefined;
159
+ }
160
+ const { ['Cache-control']: _ignored, ...rest } = meta;
161
+ return Object.keys(rest).length ? rest : undefined;
162
+ }
163
+ detectContentType(key, isCompressed) {
164
+ // Basic content type inference
165
+ const lower = key.toLowerCase();
166
+ if (lower.endsWith('.json') || lower.endsWith('.json.gz')) {
167
+ return 'application/json';
168
+ }
169
+ if (lower.endsWith('.txt') || lower.endsWith('.log') || lower.endsWith('.csv') || lower.endsWith('.md')) {
170
+ return 'text/plain; charset=utf-8';
171
+ }
172
+ if (lower.endsWith('.db') || lower.endsWith('.sqlite') || lower.endsWith('.bin')) {
173
+ return 'application/octet-stream';
174
+ }
175
+ if (lower.endsWith('.wasm') || lower.endsWith('.wasm.gz')) {
176
+ return 'application/wasm';
177
+ }
178
+ // If compressed, prefer octet-stream unless known
179
+ if (isCompressed) {
180
+ return 'application/octet-stream';
181
+ }
182
+ return undefined;
183
+ }
184
+ buildReturnedUrl(key, makePublic) {
185
+ if (!makePublic) {
186
+ return `s3://${this.bucketName}/${key}`;
187
+ }
188
+ if (this.publicBaseUrl) {
189
+ const base = this.publicBaseUrl.replace(/\/$/, '');
190
+ // key already includes basePath via getFullPath, so do not prefix basePath again
191
+ const full = key.replace(/^\/+/, '');
192
+ return `${base}/${full}`;
193
+ }
194
+ // Try to synthesize a URL from endpoint if available (works for public R2 buckets)
195
+ if (this.endpoint) {
196
+ try {
197
+ const url = new URL(this.endpoint);
198
+ return `https://${this.bucketName}.${url.host}/${key}`;
199
+ } catch {
200
+ // fallthrough
201
+ }
202
+ }
203
+ // Fallback to AWS style URL if region looks valid
204
+ return `https://${this.bucketName}.s3.${this.region}.amazonaws.com/${key}`;
205
+ }
206
+ getBucketAndKey(pathOrUrlStr) {
207
+ if (URL.canParse(pathOrUrlStr)) {
208
+ const url = new URL(pathOrUrlStr);
209
+ if (url.protocol === 's3:') {
210
+ return {
211
+ bucket: url.host,
212
+ key: url.pathname.replace(/^\/+/, '')
213
+ };
214
+ }
215
+ // For https URLs, try to infer virtual-hosted or path-style
216
+ if (url.protocol === 'https:' || url.protocol === 'http:') {
217
+ // If the URL matches the configured publicBaseUrl host, map back to our bucket and key
218
+ if (this.publicBaseUrl && url.host === new URL(this.publicBaseUrl).host) {
219
+ return {
220
+ bucket: this.bucketName,
221
+ key: url.pathname.replace(/^\/+/, '')
222
+ };
223
+ }
224
+ const hostParts = url.host.split('.');
225
+ if (hostParts.length > 3 && (hostParts[1] === 's3' || hostParts[hostParts.length - 2] === 'r2')) {
226
+ // virtual hosted
227
+ return {
228
+ bucket: hostParts[0],
229
+ key: url.pathname.replace(/^\/+/, '')
230
+ };
231
+ } else if (this.endpoint && url.host === new URL(this.endpoint).host) {
232
+ // path-style at custom endpoint
233
+ const [bucket, ...rest] = url.pathname.replace(/^\/+/, '').split('/');
234
+ return {
235
+ bucket,
236
+ key: rest.join('/')
237
+ };
238
+ }
239
+ }
240
+ }
241
+ // Treat as path
242
+ return {
243
+ bucket: this.bucketName,
244
+ key: this.getFullPath(pathOrUrlStr)
245
+ };
246
+ }
247
+ getFullPath(path) {
248
+ const base = normalizeBasePath(this.basePath);
249
+ const rel = path.replace(/^\/+/, '');
250
+ return base ? join(base, rel) : rel;
251
+ }
252
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"download.d.ts","sourceRoot":"","sources":["../../src/snapshots/download.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,EACL,gBAAgB,EAChB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,sBAAsB,EAE5B,MAAM,YAAY,CAAC;AAEpB,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,sBAAsB,EAChC,KAAK,EAAE,iBAAiB,GACvB,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAarC;AAED,wBAAsB,yBAAyB,C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AAoCD,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,EAC5C,UAAU,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAC5C,KAAK,EAAE,iBAAiB,GACvB,OAAO,CAAC,IAAI,CAAC,CAyBf"}
@@ -1,5 +1,10 @@
1
1
  import { fromEntries, getEntries, maxBy } from '@aztec/foundation/collection';
2
2
  import { jsonParseWithSchema } from '@aztec/foundation/json-rpc';
3
+ import { createReadStream, createWriteStream } from 'fs';
4
+ import fs from 'fs/promises';
5
+ import pathMod from 'path';
6
+ import { pipeline } from 'stream/promises';
7
+ import { createGunzip, gunzipSync } from 'zlib';
3
8
  import { SnapshotDataKeys, SnapshotsIndexSchema } from './types.js';
4
9
  export async function getSnapshotIndex(metadata, store) {
5
10
  const basePath = getBasePath(metadata);
@@ -7,7 +12,8 @@ export async function getSnapshotIndex(metadata, store) {
7
12
  try {
8
13
  if (await store.exists(snapshotIndexPath)) {
9
14
  const snapshotIndexData = await store.read(snapshotIndexPath);
10
- return jsonParseWithSchema(snapshotIndexData.toString(), SnapshotsIndexSchema);
15
+ const buf = maybeGunzip(snapshotIndexData);
16
+ return jsonParseWithSchema(buf.toString('utf-8'), SnapshotsIndexSchema);
11
17
  } else {
12
18
  return undefined;
13
19
  }
@@ -32,6 +38,56 @@ export function makeSnapshotPaths(baseDir) {
32
38
  `${baseDir}/${key}.db`
33
39
  ]));
34
40
  }
41
+ function isGzipMagic(data) {
42
+ return data.length >= 2 && data[0] === 0x1f && data[1] === 0x8b;
43
+ }
44
+ function maybeGunzip(data) {
45
+ const magicNumberIndicatesGzip = isGzipMagic(data);
46
+ if (magicNumberIndicatesGzip) {
47
+ try {
48
+ const out = gunzipSync(data);
49
+ return out;
50
+ } catch (err) {
51
+ throw new Error(`Decompression of gzipped data failed: ${err.message}`);
52
+ }
53
+ }
54
+ return data;
55
+ }
56
+ async function detectGzip(localFilePathToPeek) {
57
+ // Peek the actual bytes we downloaded.
58
+ try {
59
+ const fd = await fs.open(localFilePathToPeek, 'r');
60
+ try {
61
+ const header = Buffer.alloc(2);
62
+ const { bytesRead } = await fd.read(header, 0, 2, 0);
63
+ return bytesRead >= 2 && isGzipMagic(header);
64
+ } finally{
65
+ await fd.close();
66
+ }
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
35
71
  export async function downloadSnapshot(snapshot, localPaths, store) {
36
- await Promise.all(getEntries(localPaths).map(([key, path])=>store.download(snapshot.dataUrls[key], path)));
72
+ await Promise.all(getEntries(localPaths).map(async ([key, path])=>{
73
+ await fs.mkdir(pathMod.dirname(path), {
74
+ recursive: true
75
+ });
76
+ const tmpPath = `${path}.download`;
77
+ try {
78
+ const url = snapshot.dataUrls[key];
79
+ await store.download(url, tmpPath);
80
+ const isGzip = await detectGzip(tmpPath);
81
+ const read = createReadStream(tmpPath);
82
+ const write = createWriteStream(path);
83
+ if (isGzip) {
84
+ const gunzip = createGunzip();
85
+ await pipeline(read, gunzip, write);
86
+ } else {
87
+ await pipeline(read, write);
88
+ }
89
+ } finally{
90
+ await fs.unlink(tmpPath).catch(()=>undefined);
91
+ }
92
+ }));
37
93
  }
@@ -1 +1 @@
1
- {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/snapshots/upload.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAG1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAkB,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAE7G,wBAAsB,kBAAkB,CACtC,UAAU,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAC5C,cAAc,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,EAClD,QAAQ,EAAE,sBAAsB,EAChC,KAAK,EAAE,SAAS,EAChB,IAAI,GAAE;IAAE,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,gBAAgB,KAAK,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAO,GAC5E,OAAO,CAAC,gBAAgB,CAAC,CAsB3B;AAED,wBAAsB,qBAAqB,CACzC,UAAU,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAC5C,cAAc,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,EAClD,QAAQ,EAAE,sBAAsB,EAChC,KAAK,EAAE,SAAS,GACf,OAAO,CAAC,gBAAgB,CAAC,CAU3B"}
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/snapshots/upload.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAG1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAkB,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAE7G,wBAAsB,kBAAkB,CACtC,UAAU,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAC5C,cAAc,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,EAClD,QAAQ,EAAE,sBAAsB,EAChC,KAAK,EAAE,SAAS,EAChB,IAAI,GAAE;IAAE,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,gBAAgB,KAAK,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAO,GAC5E,OAAO,CAAC,gBAAgB,CAAC,CAsB3B;AAED,wBAAsB,qBAAqB,CACzC,UAAU,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAC5C,cAAc,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,EAClD,QAAQ,EAAE,sBAAsB,EAChC,KAAK,EAAE,SAAS,GACf,OAAO,CAAC,gBAAgB,CAAC,CAW3B"}
@@ -27,6 +27,7 @@ export async function uploadSnapshotToIndex(localPaths, schemaVersions, metadata
27
27
  snapshotsIndex.snapshots.unshift(newSnapshotMetadata);
28
28
  await store.save(getSnapshotIndexPath(metadata), Buffer.from(jsonStringify(snapshotsIndex, true)), {
29
29
  public: true,
30
+ compress: false,
30
31
  metadata: {
31
32
  ['Cache-control']: 'no-store'
32
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/stdlib",
3
- "version": "2.1.0-rc.1",
3
+ "version": "2.1.0-rc.3",
4
4
  "type": "module",
5
5
  "inherits": [
6
6
  "../package.common.json",
@@ -69,13 +69,14 @@
69
69
  "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
70
70
  },
71
71
  "dependencies": {
72
- "@aztec/bb.js": "2.1.0-rc.1",
73
- "@aztec/blob-lib": "2.1.0-rc.1",
74
- "@aztec/constants": "2.1.0-rc.1",
75
- "@aztec/ethereum": "2.1.0-rc.1",
76
- "@aztec/foundation": "2.1.0-rc.1",
77
- "@aztec/l1-artifacts": "2.1.0-rc.1",
78
- "@aztec/noir-noirc_abi": "2.1.0-rc.1",
72
+ "@aws-sdk/client-s3": "^3.892.0",
73
+ "@aztec/bb.js": "2.1.0-rc.3",
74
+ "@aztec/blob-lib": "2.1.0-rc.3",
75
+ "@aztec/constants": "2.1.0-rc.3",
76
+ "@aztec/ethereum": "2.1.0-rc.3",
77
+ "@aztec/foundation": "2.1.0-rc.3",
78
+ "@aztec/l1-artifacts": "2.1.0-rc.3",
79
+ "@aztec/noir-noirc_abi": "2.1.0-rc.3",
79
80
  "@google-cloud/storage": "^7.15.0",
80
81
  "axios": "^1.12.0",
81
82
  "json-stringify-deterministic": "1.0.12",
@@ -118,3 +118,11 @@ export function getProofSubmissionDeadlineTimestamp(
118
118
  const [deadlineSlot] = getSlotRangeForEpoch(deadlineEpoch, constants);
119
119
  return getTimestampForSlot(deadlineSlot, constants);
120
120
  }
121
+
122
+ /** Returns the timestamp to start building a block for a given L2 slot. Computed as the start timestamp of the slot minus one L1 slot duration. */
123
+ export function getSlotStartBuildTimestamp(
124
+ slotNumber: number | bigint,
125
+ constants: Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration' | 'ethereumSlotDuration'>,
126
+ ): number {
127
+ return Number(constants.l1GenesisTime) + Number(slotNumber) * constants.slotDuration - constants.ethereumSlotDuration;
128
+ }
@@ -4,9 +4,11 @@ import { GoogleCloudFileStore } from './gcs.js';
4
4
  import { HttpFileStore } from './http.js';
5
5
  import type { FileStore, ReadOnlyFileStore } from './interface.js';
6
6
  import { LocalFileStore } from './local.js';
7
+ import { S3FileStore } from './s3.js';
7
8
 
8
9
  const supportedExamples = [
9
10
  `gs://bucket-name/path/to/store`,
11
+ `s3://bucket-name/path/to/store`,
10
12
  `file:///absolute/local/path/to/store`,
11
13
  `https://host/path`,
12
14
  ];
@@ -39,6 +41,19 @@ export async function createFileStore(
39
41
  } catch {
40
42
  throw new Error(`Invalid google cloud store definition: '${config}'.`);
41
43
  }
44
+ } else if (config.startsWith('s3://')) {
45
+ try {
46
+ const url = new URL(config);
47
+ const bucket = url.host;
48
+ const path = url.pathname.replace(/^\/+/, '');
49
+ const endpoint = url.searchParams.get('endpoint');
50
+ const publicBaseUrl = url.searchParams.get('publicBaseUrl') ?? undefined;
51
+ logger.info(`Creating S3 file store at ${bucket} ${path}`);
52
+ const store = new S3FileStore(bucket, path, { endpoint: endpoint ?? undefined, publicBaseUrl });
53
+ return store;
54
+ } catch {
55
+ throw new Error(`Invalid S3 store definition: '${config}'.`);
56
+ }
42
57
  } else {
43
58
  throw new Error(`Unknown file store config: '${config}'. Supported values are ${supportedExamples.join(', ')}.`);
44
59
  }
@@ -12,8 +12,14 @@ export type FileStoreSaveOptions = { public?: boolean; metadata?: Record<string,
12
12
 
13
13
  /** Simple file store. */
14
14
  export interface FileStore extends ReadOnlyFileStore {
15
- /** Saves contents to the given path. Returns an URI that can be used later to `read` the file. */
15
+ /**
16
+ * Saves contents to the given path. Returns an URI that can be used later to `read` the file.
17
+ * Default: `compress` is false unless explicitly set.
18
+ */
16
19
  save(path: string, data: Buffer, opts?: FileStoreSaveOptions): Promise<string>;
17
- /** Uploads contents from a local file. Returns an URI that can be used later to `read` the file. */
20
+ /**
21
+ * Uploads contents from a local file. Returns an URI that can be used later to `read` the file.
22
+ * Default: `compress` is true unless explicitly set to false.
23
+ */
18
24
  upload(destPath: string, srcPath: string, opts?: FileStoreSaveOptions): Promise<string>;
19
25
  }
@@ -0,0 +1,254 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+
3
+ import {
4
+ GetObjectCommand,
5
+ type GetObjectCommandOutput,
6
+ HeadObjectCommand,
7
+ PutObjectCommand,
8
+ S3Client,
9
+ } from '@aws-sdk/client-s3';
10
+ import { createReadStream, createWriteStream } from 'fs';
11
+ import { mkdir, mkdtemp, stat, unlink } from 'fs/promises';
12
+ import { tmpdir } from 'os';
13
+ import { basename, dirname, join } from 'path';
14
+ import { Readable } from 'stream';
15
+ import { finished } from 'stream/promises';
16
+ import { createGzip } from 'zlib';
17
+
18
+ import type { FileStore, FileStoreSaveOptions } from './interface.js';
19
+
20
+ function normalizeBasePath(path: string): string {
21
+ return path?.replace(/^\/+|\/+$/g, '') ?? '';
22
+ }
23
+
24
+ export class S3FileStore implements FileStore {
25
+ private readonly s3: S3Client;
26
+ private readonly region: string;
27
+ private readonly endpoint?: string;
28
+ private readonly publicBaseUrl?: string;
29
+
30
+ constructor(
31
+ private readonly bucketName: string,
32
+ private readonly basePath: string,
33
+ opts: { endpoint?: string; publicBaseUrl?: string },
34
+ private readonly log: Logger = createLogger('stdlib:s3-file-store'),
35
+ ) {
36
+ this.endpoint = opts.endpoint;
37
+ this.region = this.endpoint ? 'auto' : (process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? 'us-east-1');
38
+ this.publicBaseUrl = opts.publicBaseUrl;
39
+
40
+ const clientOptions: any = {};
41
+ if (this.endpoint) {
42
+ clientOptions.region = 'auto';
43
+ clientOptions.endpoint = this.endpoint;
44
+ clientOptions.forcePathStyle = true;
45
+ } else {
46
+ clientOptions.region = this.region;
47
+ }
48
+ this.s3 = new S3Client(clientOptions);
49
+ }
50
+
51
+ public async save(path: string, data: Buffer, opts: FileStoreSaveOptions = {}): Promise<string> {
52
+ const key = this.getFullPath(path);
53
+ const shouldCompress = !!opts.compress;
54
+
55
+ const body = shouldCompress ? (await import('zlib')).gzipSync(data) : data;
56
+ const contentLength = body.length;
57
+ const contentType = this.detectContentType(key, shouldCompress);
58
+ const put = new PutObjectCommand({
59
+ Bucket: this.bucketName,
60
+ Key: key,
61
+ Body: body,
62
+ ContentType: contentType,
63
+ CacheControl: opts.metadata?.['Cache-control'],
64
+ Metadata: this.extractUserMetadata(opts.metadata),
65
+ ContentLength: contentLength,
66
+ });
67
+ await this.s3.send(put);
68
+ return this.buildReturnedUrl(key, !!opts.public);
69
+ }
70
+
71
+ public async upload(destPath: string, srcPath: string, opts: FileStoreSaveOptions = {}): Promise<string> {
72
+ const key = this.getFullPath(destPath);
73
+ const shouldCompress = opts.compress !== false; // default true like GCS impl
74
+
75
+ await mkdir(dirname(srcPath), { recursive: true }).catch(() => undefined);
76
+ let contentLength: number | undefined;
77
+ let bodyPath = srcPath;
78
+
79
+ // We don't set Content-Encoding and we avoid SigV4 streaming (aws-chunked).
80
+ // With AWS SigV4 streaming uploads (Content-Encoding: aws-chunked[,gzip]), servers require
81
+ // x-amz-decoded-content-length (the size of the decoded payload) and an exact Content-Length
82
+ // that includes chunk metadata. For on-the-fly compression, providing
83
+ // those values without buffering or a pre-pass is impractical. Instead, we pre-gzip to a temp file
84
+ // to know ContentLength up-front and upload the gzipped bytes as-is, omitting Content-Encoding.
85
+ // Reference: AWS SigV4 streaming (chunked upload) requirements —
86
+ // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
87
+ if (shouldCompress) {
88
+ // Pre-gzip to a temp file so we know the exact length for R2/S3 headers
89
+ const tmpDir = await mkdtemp(join(tmpdir(), 's3-upload-'));
90
+ const gzPath = join(tmpDir, `${basename(srcPath)}.gz`);
91
+ const source = createReadStream(srcPath);
92
+ const gz = createGzip();
93
+ const out = createWriteStream(gzPath);
94
+ try {
95
+ await finished(source.pipe(gz).pipe(out));
96
+ const st = await stat(gzPath);
97
+ contentLength = st.size;
98
+ bodyPath = gzPath;
99
+ } catch (err) {
100
+ // Ensure temp file is removed on failure
101
+ await unlink(gzPath).catch(() => undefined);
102
+ throw err;
103
+ }
104
+ } else {
105
+ const st = await stat(srcPath);
106
+ contentLength = st.size;
107
+ bodyPath = srcPath;
108
+ }
109
+
110
+ const bodyStream = createReadStream(bodyPath);
111
+ const contentType = this.detectContentType(key, shouldCompress);
112
+ try {
113
+ const put = new PutObjectCommand({
114
+ Bucket: this.bucketName,
115
+ Key: key,
116
+ Body: bodyStream as any,
117
+ ContentType: contentType,
118
+ CacheControl: opts.metadata?.['Cache-control'],
119
+ Metadata: this.extractUserMetadata(opts.metadata),
120
+ // Explicitly set ContentLength so R2 can compute x-amz-decoded-content-length correctly
121
+ ContentLength: contentLength,
122
+ } as any);
123
+ await this.s3.send(put);
124
+ } finally {
125
+ if (shouldCompress && bodyPath !== srcPath) {
126
+ await unlink(bodyPath).catch(() => undefined);
127
+ }
128
+ }
129
+ return this.buildReturnedUrl(key, !!opts.public);
130
+ }
131
+
132
+ public async read(pathOrUrlStr: string): Promise<Buffer> {
133
+ const { bucket, key } = this.getBucketAndKey(pathOrUrlStr);
134
+ const out: GetObjectCommandOutput = await this.s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
135
+ const stream = out.Body as Readable;
136
+ const chunks: Buffer[] = [];
137
+ for await (const chunk of stream) {
138
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
139
+ }
140
+ return Buffer.concat(chunks);
141
+ }
142
+
143
+ public async download(pathOrUrlStr: string, destPath: string): Promise<void> {
144
+ const { bucket, key } = this.getBucketAndKey(pathOrUrlStr);
145
+ const out: GetObjectCommandOutput = await this.s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
146
+ await mkdir(dirname(destPath), { recursive: true });
147
+ const write = createWriteStream(destPath);
148
+ await finished((out.Body as Readable).pipe(write));
149
+ }
150
+
151
+ public async exists(pathOrUrlStr: string): Promise<boolean> {
152
+ try {
153
+ const { bucket, key } = this.getBucketAndKey(pathOrUrlStr);
154
+ await this.s3.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
155
+ return true;
156
+ } catch (err: any) {
157
+ const code = err?.$metadata?.httpStatusCode ?? err?.name ?? err?.Code;
158
+ if (code === 404 || code === 'NotFound' || code === 'NoSuchKey') {
159
+ return false;
160
+ }
161
+ this.log.warn(`Error checking existence for ${pathOrUrlStr}: ${err?.message ?? String(err)}`);
162
+ return false;
163
+ }
164
+ }
165
+
166
+ private extractUserMetadata(meta?: Record<string, string>): Record<string, string> | undefined {
167
+ if (!meta) {
168
+ return undefined;
169
+ }
170
+ const { ['Cache-control']: _ignored, ...rest } = meta;
171
+ return Object.keys(rest).length ? rest : undefined;
172
+ }
173
+
174
+ private detectContentType(key: string, isCompressed: boolean | undefined): string | undefined {
175
+ // Basic content type inference
176
+ const lower = key.toLowerCase();
177
+ if (lower.endsWith('.json') || lower.endsWith('.json.gz')) {
178
+ return 'application/json';
179
+ }
180
+ if (lower.endsWith('.txt') || lower.endsWith('.log') || lower.endsWith('.csv') || lower.endsWith('.md')) {
181
+ return 'text/plain; charset=utf-8';
182
+ }
183
+ if (lower.endsWith('.db') || lower.endsWith('.sqlite') || lower.endsWith('.bin')) {
184
+ return 'application/octet-stream';
185
+ }
186
+ if (lower.endsWith('.wasm') || lower.endsWith('.wasm.gz')) {
187
+ return 'application/wasm';
188
+ }
189
+ // If compressed, prefer octet-stream unless known
190
+ if (isCompressed) {
191
+ return 'application/octet-stream';
192
+ }
193
+ return undefined;
194
+ }
195
+
196
+ private buildReturnedUrl(key: string, makePublic: boolean): string {
197
+ if (!makePublic) {
198
+ return `s3://${this.bucketName}/${key}`;
199
+ }
200
+
201
+ if (this.publicBaseUrl) {
202
+ const base = this.publicBaseUrl.replace(/\/$/, '');
203
+ // key already includes basePath via getFullPath, so do not prefix basePath again
204
+ const full = key.replace(/^\/+/, '');
205
+ return `${base}/${full}`;
206
+ }
207
+
208
+ // Try to synthesize a URL from endpoint if available (works for public R2 buckets)
209
+ if (this.endpoint) {
210
+ try {
211
+ const url = new URL(this.endpoint);
212
+ return `https://${this.bucketName}.${url.host}/${key}`;
213
+ } catch {
214
+ // fallthrough
215
+ }
216
+ }
217
+
218
+ // Fallback to AWS style URL if region looks valid
219
+ return `https://${this.bucketName}.s3.${this.region}.amazonaws.com/${key}`;
220
+ }
221
+
222
+ private getBucketAndKey(pathOrUrlStr: string): { bucket: string; key: string } {
223
+ if (URL.canParse(pathOrUrlStr)) {
224
+ const url = new URL(pathOrUrlStr);
225
+ if (url.protocol === 's3:') {
226
+ return { bucket: url.host, key: url.pathname.replace(/^\/+/, '') };
227
+ }
228
+ // For https URLs, try to infer virtual-hosted or path-style
229
+ if (url.protocol === 'https:' || url.protocol === 'http:') {
230
+ // If the URL matches the configured publicBaseUrl host, map back to our bucket and key
231
+ if (this.publicBaseUrl && url.host === new URL(this.publicBaseUrl).host) {
232
+ return { bucket: this.bucketName, key: url.pathname.replace(/^\/+/, '') };
233
+ }
234
+ const hostParts = url.host.split('.');
235
+ if (hostParts.length > 3 && (hostParts[1] === 's3' || hostParts[hostParts.length - 2] === 'r2')) {
236
+ // virtual hosted
237
+ return { bucket: hostParts[0], key: url.pathname.replace(/^\/+/, '') };
238
+ } else if (this.endpoint && url.host === new URL(this.endpoint).host) {
239
+ // path-style at custom endpoint
240
+ const [bucket, ...rest] = url.pathname.replace(/^\/+/, '').split('/');
241
+ return { bucket, key: rest.join('/') };
242
+ }
243
+ }
244
+ }
245
+ // Treat as path
246
+ return { bucket: this.bucketName, key: this.getFullPath(pathOrUrlStr) };
247
+ }
248
+
249
+ private getFullPath(path: string): string {
250
+ const base = normalizeBasePath(this.basePath);
251
+ const rel = path.replace(/^\/+/, '');
252
+ return base ? join(base, rel) : rel;
253
+ }
254
+ }
@@ -2,6 +2,12 @@ import { fromEntries, getEntries, maxBy } from '@aztec/foundation/collection';
2
2
  import { jsonParseWithSchema } from '@aztec/foundation/json-rpc';
3
3
  import type { ReadOnlyFileStore } from '@aztec/stdlib/file-store';
4
4
 
5
+ import { createReadStream, createWriteStream } from 'fs';
6
+ import fs from 'fs/promises';
7
+ import pathMod from 'path';
8
+ import { pipeline } from 'stream/promises';
9
+ import { createGunzip, gunzipSync } from 'zlib';
10
+
5
11
  import {
6
12
  SnapshotDataKeys,
7
13
  type SnapshotDataUrls,
@@ -20,7 +26,8 @@ export async function getSnapshotIndex(
20
26
  try {
21
27
  if (await store.exists(snapshotIndexPath)) {
22
28
  const snapshotIndexData = await store.read(snapshotIndexPath);
23
- return jsonParseWithSchema(snapshotIndexData.toString(), SnapshotsIndexSchema);
29
+ const buf = maybeGunzip(snapshotIndexData);
30
+ return jsonParseWithSchema(buf.toString('utf-8'), SnapshotsIndexSchema);
24
31
  } else {
25
32
  return undefined;
26
33
  }
@@ -50,10 +57,67 @@ export function makeSnapshotPaths(baseDir: string): SnapshotDataUrls {
50
57
  return fromEntries(SnapshotDataKeys.map(key => [key, `${baseDir}/${key}.db`]));
51
58
  }
52
59
 
60
+ function isGzipMagic(data: Buffer): boolean {
61
+ return data.length >= 2 && data[0] === 0x1f && data[1] === 0x8b;
62
+ }
63
+
64
+ function maybeGunzip(data: Buffer): Buffer {
65
+ const magicNumberIndicatesGzip = isGzipMagic(data);
66
+
67
+ if (magicNumberIndicatesGzip) {
68
+ try {
69
+ const out = gunzipSync(data);
70
+ return out;
71
+ } catch (err) {
72
+ throw new Error(`Decompression of gzipped data failed: ${(err as Error).message}`);
73
+ }
74
+ }
75
+ return data;
76
+ }
77
+
78
+ async function detectGzip(localFilePathToPeek: string): Promise<boolean> {
79
+ // Peek the actual bytes we downloaded.
80
+ try {
81
+ const fd = await fs.open(localFilePathToPeek, 'r');
82
+ try {
83
+ const header = Buffer.alloc(2);
84
+ const { bytesRead } = await fd.read(header, 0, 2, 0);
85
+ return bytesRead >= 2 && isGzipMagic(header);
86
+ } finally {
87
+ await fd.close();
88
+ }
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+
53
94
  export async function downloadSnapshot(
54
95
  snapshot: Pick<SnapshotMetadata, 'dataUrls'>,
55
96
  localPaths: Record<SnapshotDataKeys, string>,
56
97
  store: ReadOnlyFileStore,
57
98
  ): Promise<void> {
58
- await Promise.all(getEntries(localPaths).map(([key, path]) => store.download(snapshot.dataUrls[key], path)));
99
+ await Promise.all(
100
+ getEntries(localPaths).map(async ([key, path]) => {
101
+ await fs.mkdir(pathMod.dirname(path), { recursive: true });
102
+
103
+ const tmpPath = `${path}.download`;
104
+ try {
105
+ const url = snapshot.dataUrls[key];
106
+ await store.download(url, tmpPath);
107
+
108
+ const isGzip = await detectGzip(tmpPath);
109
+
110
+ const read = createReadStream(tmpPath);
111
+ const write = createWriteStream(path);
112
+ if (isGzip) {
113
+ const gunzip = createGunzip();
114
+ await pipeline(read, gunzip, write);
115
+ } else {
116
+ await pipeline(read, write);
117
+ }
118
+ } finally {
119
+ await fs.unlink(tmpPath).catch(() => undefined);
120
+ }
121
+ }),
122
+ );
59
123
  }
@@ -48,6 +48,7 @@ export async function uploadSnapshotToIndex(
48
48
 
49
49
  await store.save(getSnapshotIndexPath(metadata), Buffer.from(jsonStringify(snapshotsIndex, true)), {
50
50
  public: true, // Make the index publicly accessible
51
+ compress: false, // Ensure index.json is not gzipped
51
52
  metadata: { ['Cache-control']: 'no-store' }, // Do not cache object versions
52
53
  });
53
54
  return newSnapshotMetadata;