@aztec/archiver 4.0.0-nightly.20250907 → 4.0.0-nightly.20260108

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 (133) hide show
  1. package/README.md +27 -6
  2. package/dest/archiver/archiver.d.ts +127 -84
  3. package/dest/archiver/archiver.d.ts.map +1 -1
  4. package/dest/archiver/archiver.js +1150 -382
  5. package/dest/archiver/archiver_store.d.ts +122 -45
  6. package/dest/archiver/archiver_store.d.ts.map +1 -1
  7. package/dest/archiver/archiver_store_test_suite.d.ts +1 -1
  8. package/dest/archiver/archiver_store_test_suite.d.ts.map +1 -1
  9. package/dest/archiver/archiver_store_test_suite.js +2013 -343
  10. package/dest/archiver/config.d.ts +7 -20
  11. package/dest/archiver/config.d.ts.map +1 -1
  12. package/dest/archiver/config.js +21 -5
  13. package/dest/archiver/errors.d.ts +25 -1
  14. package/dest/archiver/errors.d.ts.map +1 -1
  15. package/dest/archiver/errors.js +37 -0
  16. package/dest/archiver/index.d.ts +2 -2
  17. package/dest/archiver/index.d.ts.map +1 -1
  18. package/dest/archiver/instrumentation.d.ts +5 -3
  19. package/dest/archiver/instrumentation.d.ts.map +1 -1
  20. package/dest/archiver/instrumentation.js +14 -0
  21. package/dest/archiver/kv_archiver_store/block_store.d.ts +83 -15
  22. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  23. package/dest/archiver/kv_archiver_store/block_store.js +396 -73
  24. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +2 -2
  25. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +1 -1
  26. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  27. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +2 -2
  28. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +1 -1
  29. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +51 -55
  30. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  31. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +82 -46
  32. package/dest/archiver/kv_archiver_store/log_store.d.ts +12 -16
  33. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +1 -1
  34. package/dest/archiver/kv_archiver_store/log_store.js +149 -84
  35. package/dest/archiver/kv_archiver_store/message_store.d.ts +6 -5
  36. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +1 -1
  37. package/dest/archiver/kv_archiver_store/message_store.js +15 -14
  38. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  39. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  40. package/dest/archiver/l1/bin/retrieve-calldata.js +149 -0
  41. package/dest/archiver/l1/calldata_retriever.d.ts +112 -0
  42. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  43. package/dest/archiver/l1/calldata_retriever.js +471 -0
  44. package/dest/archiver/l1/data_retrieval.d.ts +90 -0
  45. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  46. package/dest/archiver/l1/data_retrieval.js +331 -0
  47. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  48. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  49. package/dest/archiver/l1/debug_tx.js +73 -0
  50. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  51. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  52. package/dest/archiver/l1/spire_proposer.js +157 -0
  53. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  54. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  55. package/dest/archiver/l1/trace_tx.js +91 -0
  56. package/dest/archiver/l1/types.d.ts +12 -0
  57. package/dest/archiver/l1/types.d.ts.map +1 -0
  58. package/dest/archiver/l1/types.js +3 -0
  59. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  60. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  61. package/dest/archiver/l1/validate_trace.js +150 -0
  62. package/dest/archiver/structs/data_retrieval.d.ts +1 -1
  63. package/dest/archiver/structs/inbox_message.d.ts +4 -4
  64. package/dest/archiver/structs/inbox_message.d.ts.map +1 -1
  65. package/dest/archiver/structs/inbox_message.js +6 -5
  66. package/dest/archiver/structs/published.d.ts +2 -2
  67. package/dest/archiver/structs/published.d.ts.map +1 -1
  68. package/dest/archiver/validation.d.ts +10 -4
  69. package/dest/archiver/validation.d.ts.map +1 -1
  70. package/dest/archiver/validation.js +66 -44
  71. package/dest/factory.d.ts +4 -6
  72. package/dest/factory.d.ts.map +1 -1
  73. package/dest/factory.js +5 -4
  74. package/dest/index.d.ts +2 -2
  75. package/dest/index.d.ts.map +1 -1
  76. package/dest/index.js +1 -1
  77. package/dest/rpc/index.d.ts +2 -2
  78. package/dest/test/index.d.ts +1 -1
  79. package/dest/test/mock_archiver.d.ts +16 -8
  80. package/dest/test/mock_archiver.d.ts.map +1 -1
  81. package/dest/test/mock_archiver.js +19 -14
  82. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  83. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  84. package/dest/test/mock_l1_to_l2_message_source.js +10 -9
  85. package/dest/test/mock_l2_block_source.d.ts +31 -20
  86. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  87. package/dest/test/mock_l2_block_source.js +85 -18
  88. package/dest/test/mock_structs.d.ts +3 -2
  89. package/dest/test/mock_structs.d.ts.map +1 -1
  90. package/dest/test/mock_structs.js +9 -8
  91. package/package.json +18 -17
  92. package/src/archiver/archiver.ts +990 -481
  93. package/src/archiver/archiver_store.ts +141 -44
  94. package/src/archiver/archiver_store_test_suite.ts +2114 -331
  95. package/src/archiver/config.ts +30 -35
  96. package/src/archiver/errors.ts +64 -0
  97. package/src/archiver/index.ts +1 -1
  98. package/src/archiver/instrumentation.ts +19 -2
  99. package/src/archiver/kv_archiver_store/block_store.ts +541 -83
  100. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  101. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  102. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +107 -67
  103. package/src/archiver/kv_archiver_store/log_store.ts +209 -99
  104. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  105. package/src/archiver/l1/README.md +98 -0
  106. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  107. package/src/archiver/l1/calldata_retriever.ts +641 -0
  108. package/src/archiver/l1/data_retrieval.ts +512 -0
  109. package/src/archiver/l1/debug_tx.ts +99 -0
  110. package/src/archiver/l1/spire_proposer.ts +160 -0
  111. package/src/archiver/l1/trace_tx.ts +128 -0
  112. package/src/archiver/l1/types.ts +13 -0
  113. package/src/archiver/l1/validate_trace.ts +211 -0
  114. package/src/archiver/structs/inbox_message.ts +8 -8
  115. package/src/archiver/structs/published.ts +1 -1
  116. package/src/archiver/validation.ts +86 -32
  117. package/src/factory.ts +6 -7
  118. package/src/index.ts +1 -1
  119. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  120. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  121. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  122. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  123. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  124. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  125. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  126. package/src/test/mock_archiver.ts +22 -16
  127. package/src/test/mock_l1_to_l2_message_source.ts +10 -9
  128. package/src/test/mock_l2_block_source.ts +114 -27
  129. package/src/test/mock_structs.ts +10 -9
  130. package/dest/archiver/data_retrieval.d.ts +0 -78
  131. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  132. package/dest/archiver/data_retrieval.js +0 -354
  133. package/src/archiver/data_retrieval.ts +0 -535
@@ -1,75 +1,492 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1
+ function applyDecs2203RFactory() {
2
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
+ return function addInitializer(initializer) {
4
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
5
+ assertCallable(initializer, "An initializer");
6
+ initializers.push(initializer);
7
+ };
8
+ }
9
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
10
+ var kindStr;
11
+ switch(kind){
12
+ case 1:
13
+ kindStr = "accessor";
14
+ break;
15
+ case 2:
16
+ kindStr = "method";
17
+ break;
18
+ case 3:
19
+ kindStr = "getter";
20
+ break;
21
+ case 4:
22
+ kindStr = "setter";
23
+ break;
24
+ default:
25
+ kindStr = "field";
26
+ }
27
+ var ctx = {
28
+ kind: kindStr,
29
+ name: isPrivate ? "#" + name : name,
30
+ static: isStatic,
31
+ private: isPrivate,
32
+ metadata: metadata
33
+ };
34
+ var decoratorFinishedRef = {
35
+ v: false
36
+ };
37
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
38
+ var get, set;
39
+ if (kind === 0) {
40
+ if (isPrivate) {
41
+ get = desc.get;
42
+ set = desc.set;
43
+ } else {
44
+ get = function() {
45
+ return this[name];
46
+ };
47
+ set = function(v) {
48
+ this[name] = v;
49
+ };
50
+ }
51
+ } else if (kind === 2) {
52
+ get = function() {
53
+ return desc.value;
54
+ };
55
+ } else {
56
+ if (kind === 1 || kind === 3) {
57
+ get = function() {
58
+ return desc.get.call(this);
59
+ };
60
+ }
61
+ if (kind === 1 || kind === 4) {
62
+ set = function(v) {
63
+ desc.set.call(this, v);
64
+ };
65
+ }
66
+ }
67
+ ctx.access = get && set ? {
68
+ get: get,
69
+ set: set
70
+ } : get ? {
71
+ get: get
72
+ } : {
73
+ set: set
74
+ };
75
+ try {
76
+ return dec(value, ctx);
77
+ } finally{
78
+ decoratorFinishedRef.v = true;
79
+ }
80
+ }
81
+ function assertNotFinished(decoratorFinishedRef, fnName) {
82
+ if (decoratorFinishedRef.v) {
83
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
84
+ }
85
+ }
86
+ function assertCallable(fn, hint) {
87
+ if (typeof fn !== "function") {
88
+ throw new TypeError(hint + " must be a function");
89
+ }
90
+ }
91
+ function assertValidReturnValue(kind, value) {
92
+ var type = typeof value;
93
+ if (kind === 1) {
94
+ if (type !== "object" || value === null) {
95
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
96
+ }
97
+ if (value.get !== undefined) {
98
+ assertCallable(value.get, "accessor.get");
99
+ }
100
+ if (value.set !== undefined) {
101
+ assertCallable(value.set, "accessor.set");
102
+ }
103
+ if (value.init !== undefined) {
104
+ assertCallable(value.init, "accessor.init");
105
+ }
106
+ } else if (type !== "function") {
107
+ var hint;
108
+ if (kind === 0) {
109
+ hint = "field";
110
+ } else if (kind === 10) {
111
+ hint = "class";
112
+ } else {
113
+ hint = "method";
114
+ }
115
+ throw new TypeError(hint + " decorators must return a function or void 0");
116
+ }
117
+ }
118
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
119
+ var decs = decInfo[0];
120
+ var desc, init, value;
121
+ if (isPrivate) {
122
+ if (kind === 0 || kind === 1) {
123
+ desc = {
124
+ get: decInfo[3],
125
+ set: decInfo[4]
126
+ };
127
+ } else if (kind === 3) {
128
+ desc = {
129
+ get: decInfo[3]
130
+ };
131
+ } else if (kind === 4) {
132
+ desc = {
133
+ set: decInfo[3]
134
+ };
135
+ } else {
136
+ desc = {
137
+ value: decInfo[3]
138
+ };
139
+ }
140
+ } else if (kind !== 0) {
141
+ desc = Object.getOwnPropertyDescriptor(base, name);
142
+ }
143
+ if (kind === 1) {
144
+ value = {
145
+ get: desc.get,
146
+ set: desc.set
147
+ };
148
+ } else if (kind === 2) {
149
+ value = desc.value;
150
+ } else if (kind === 3) {
151
+ value = desc.get;
152
+ } else if (kind === 4) {
153
+ value = desc.set;
154
+ }
155
+ var newValue, get, set;
156
+ if (typeof decs === "function") {
157
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
158
+ if (newValue !== void 0) {
159
+ assertValidReturnValue(kind, newValue);
160
+ if (kind === 0) {
161
+ init = newValue;
162
+ } else if (kind === 1) {
163
+ init = newValue.init;
164
+ get = newValue.get || value.get;
165
+ set = newValue.set || value.set;
166
+ value = {
167
+ get: get,
168
+ set: set
169
+ };
170
+ } else {
171
+ value = newValue;
172
+ }
173
+ }
174
+ } else {
175
+ for(var i = decs.length - 1; i >= 0; i--){
176
+ var dec = decs[i];
177
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
178
+ if (newValue !== void 0) {
179
+ assertValidReturnValue(kind, newValue);
180
+ var newInit;
181
+ if (kind === 0) {
182
+ newInit = newValue;
183
+ } else if (kind === 1) {
184
+ newInit = newValue.init;
185
+ get = newValue.get || value.get;
186
+ set = newValue.set || value.set;
187
+ value = {
188
+ get: get,
189
+ set: set
190
+ };
191
+ } else {
192
+ value = newValue;
193
+ }
194
+ if (newInit !== void 0) {
195
+ if (init === void 0) {
196
+ init = newInit;
197
+ } else if (typeof init === "function") {
198
+ init = [
199
+ init,
200
+ newInit
201
+ ];
202
+ } else {
203
+ init.push(newInit);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ if (kind === 0 || kind === 1) {
210
+ if (init === void 0) {
211
+ init = function(instance, init) {
212
+ return init;
213
+ };
214
+ } else if (typeof init !== "function") {
215
+ var ownInitializers = init;
216
+ init = function(instance, init) {
217
+ var value = init;
218
+ for(var i = 0; i < ownInitializers.length; i++){
219
+ value = ownInitializers[i].call(instance, value);
220
+ }
221
+ return value;
222
+ };
223
+ } else {
224
+ var originalInitializer = init;
225
+ init = function(instance, init) {
226
+ return originalInitializer.call(instance, init);
227
+ };
228
+ }
229
+ ret.push(init);
230
+ }
231
+ if (kind !== 0) {
232
+ if (kind === 1) {
233
+ desc.get = value.get;
234
+ desc.set = value.set;
235
+ } else if (kind === 2) {
236
+ desc.value = value;
237
+ } else if (kind === 3) {
238
+ desc.get = value;
239
+ } else if (kind === 4) {
240
+ desc.set = value;
241
+ }
242
+ if (isPrivate) {
243
+ if (kind === 1) {
244
+ ret.push(function(instance, args) {
245
+ return value.get.call(instance, args);
246
+ });
247
+ ret.push(function(instance, args) {
248
+ return value.set.call(instance, args);
249
+ });
250
+ } else if (kind === 2) {
251
+ ret.push(value);
252
+ } else {
253
+ ret.push(function(instance, args) {
254
+ return value.call(instance, args);
255
+ });
256
+ }
257
+ } else {
258
+ Object.defineProperty(base, name, desc);
259
+ }
260
+ }
261
+ }
262
+ function applyMemberDecs(Class, decInfos, metadata) {
263
+ var ret = [];
264
+ var protoInitializers;
265
+ var staticInitializers;
266
+ var existingProtoNonFields = new Map();
267
+ var existingStaticNonFields = new Map();
268
+ for(var i = 0; i < decInfos.length; i++){
269
+ var decInfo = decInfos[i];
270
+ if (!Array.isArray(decInfo)) continue;
271
+ var kind = decInfo[1];
272
+ var name = decInfo[2];
273
+ var isPrivate = decInfo.length > 3;
274
+ var isStatic = kind >= 5;
275
+ var base;
276
+ var initializers;
277
+ if (isStatic) {
278
+ base = Class;
279
+ kind = kind - 5;
280
+ staticInitializers = staticInitializers || [];
281
+ initializers = staticInitializers;
282
+ } else {
283
+ base = Class.prototype;
284
+ protoInitializers = protoInitializers || [];
285
+ initializers = protoInitializers;
286
+ }
287
+ if (kind !== 0 && !isPrivate) {
288
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
289
+ var existingKind = existingNonFields.get(name) || 0;
290
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
291
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
292
+ } else if (!existingKind && kind > 2) {
293
+ existingNonFields.set(name, kind);
294
+ } else {
295
+ existingNonFields.set(name, true);
296
+ }
297
+ }
298
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
299
+ }
300
+ pushInitializers(ret, protoInitializers);
301
+ pushInitializers(ret, staticInitializers);
302
+ return ret;
303
+ }
304
+ function pushInitializers(ret, initializers) {
305
+ if (initializers) {
306
+ ret.push(function(instance) {
307
+ for(var i = 0; i < initializers.length; i++){
308
+ initializers[i].call(instance);
309
+ }
310
+ return instance;
311
+ });
312
+ }
313
+ }
314
+ function applyClassDecs(targetClass, classDecs, metadata) {
315
+ if (classDecs.length > 0) {
316
+ var initializers = [];
317
+ var newClass = targetClass;
318
+ var name = targetClass.name;
319
+ for(var i = classDecs.length - 1; i >= 0; i--){
320
+ var decoratorFinishedRef = {
321
+ v: false
322
+ };
323
+ try {
324
+ var nextNewClass = classDecs[i](newClass, {
325
+ kind: "class",
326
+ name: name,
327
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
328
+ metadata
329
+ });
330
+ } finally{
331
+ decoratorFinishedRef.v = true;
332
+ }
333
+ if (nextNewClass !== undefined) {
334
+ assertValidReturnValue(10, nextNewClass);
335
+ newClass = nextNewClass;
336
+ }
337
+ }
338
+ return [
339
+ defineMetadata(newClass, metadata),
340
+ function() {
341
+ for(var i = 0; i < initializers.length; i++){
342
+ initializers[i].call(newClass);
343
+ }
344
+ }
345
+ ];
346
+ }
347
+ }
348
+ function defineMetadata(Class, metadata) {
349
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
350
+ configurable: true,
351
+ enumerable: true,
352
+ value: metadata
353
+ });
354
+ }
355
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
356
+ if (parentClass !== void 0) {
357
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
358
+ }
359
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
360
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
361
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
362
+ return {
363
+ e: e,
364
+ get c () {
365
+ return applyClassDecs(targetClass, classDecs, metadata);
366
+ }
367
+ };
368
+ };
6
369
  }
370
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
+ }
373
+ var _dec, _dec1, _dec2, _dec3, _dec4, _initProto;
374
+ import { GENESIS_BLOCK_HEADER_HASH } from '@aztec/constants';
7
375
  import { EpochCache } from '@aztec/epoch-cache';
8
- import { BlockTagTooOldError, InboxContract, RollupContract, createEthereumChain } from '@aztec/ethereum';
376
+ import { createEthereumChain } from '@aztec/ethereum/chain';
377
+ import { BlockTagTooOldError, InboxContract, RollupContract } from '@aztec/ethereum/contracts';
9
378
  import { maxBigint } from '@aztec/foundation/bigint';
379
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
10
380
  import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
11
- import { pick } from '@aztec/foundation/collection';
12
- import { Fr } from '@aztec/foundation/fields';
381
+ import { merge, pick } from '@aztec/foundation/collection';
382
+ import { Fr } from '@aztec/foundation/curves/bn254';
13
383
  import { createLogger } from '@aztec/foundation/log';
384
+ import { promiseWithResolvers } from '@aztec/foundation/promise';
14
385
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
15
- import { sleep } from '@aztec/foundation/sleep';
16
386
  import { count } from '@aztec/foundation/string';
17
- import { Timer, elapsed } from '@aztec/foundation/timer';
387
+ import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
388
+ import { isDefined } from '@aztec/foundation/types';
18
389
  import { ContractClassPublishedEvent, PrivateFunctionBroadcastedEvent, UtilityFunctionBroadcastedEvent } from '@aztec/protocol-contracts/class-registry';
19
390
  import { ContractInstancePublishedEvent, ContractInstanceUpdatedEvent } from '@aztec/protocol-contracts/instance-registry';
20
- import { L2BlockSourceEvents } from '@aztec/stdlib/block';
391
+ import { CommitteeAttestation, L2Block, L2BlockSourceEvents, PublishedL2Block } from '@aztec/stdlib/block';
392
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
21
393
  import { computePublicBytecodeCommitment, isValidPrivateFunctionMembershipProof, isValidUtilityFunctionMembershipProof } from '@aztec/stdlib/contract';
22
394
  import { getEpochAtSlot, getEpochNumberAtTimestamp, getSlotAtTimestamp, getSlotRangeForEpoch, getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
23
- import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
395
+ import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
396
+ import { execInSpan, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
24
397
  import { EventEmitter } from 'events';
25
398
  import groupBy from 'lodash.groupby';
26
399
  import { createPublicClient, fallback, http } from 'viem';
27
- import { retrieveBlocksFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedBlockToPublishedL2Block } from './data_retrieval.js';
28
- import { InitialBlockNumberNotSequentialError, NoBlobBodiesFoundError } from './errors.js';
400
+ import { InitialCheckpointNumberNotSequentialError, NoBlobBodiesFoundError } from './errors.js';
29
401
  import { ArchiverInstrumentation } from './instrumentation.js';
30
- import { validateBlockAttestations } from './validation.js';
402
+ import { retrieveCheckpointsFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from './l1/data_retrieval.js';
403
+ import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
404
+ import { validateCheckpointAttestations } from './validation.js';
405
+ function mapArchiverConfig(config) {
406
+ return {
407
+ pollingIntervalMs: config.archiverPollingIntervalMS,
408
+ batchSize: config.archiverBatchSize,
409
+ skipValidateBlockAttestations: config.skipValidateBlockAttestations,
410
+ maxAllowedEthClientDriftSeconds: config.maxAllowedEthClientDriftSeconds,
411
+ ethereumAllowNoDebugHosts: config.ethereumAllowNoDebugHosts
412
+ };
413
+ }
414
+ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.sync'), _dec2 = trackSpan('Archiver.handleEpochPrune'), _dec3 = trackSpan('Archiver.handleL1ToL2Messages'), _dec4 = trackSpan('Archiver.handleCheckpoints');
31
415
  /**
32
- * Pulls L2 blocks in a non-blocking manner and provides interface for their retrieval.
416
+ * Pulls checkpoints in a non-blocking manner and provides interface for their retrieval.
33
417
  * Responsible for handling robust L1 polling so that other components do not need to
34
418
  * concern themselves with it.
35
419
  */ export class Archiver extends EventEmitter {
36
420
  publicClient;
421
+ debugClient;
37
422
  l1Addresses;
38
423
  dataStore;
39
424
  config;
40
- blobSinkClient;
425
+ blobClient;
41
426
  epochCache;
427
+ dateProvider;
42
428
  instrumentation;
43
429
  l1constants;
44
430
  log;
45
- /**
46
- * A promise in which we will be continually fetching new L2 blocks.
47
- */ runningPromise;
431
+ static{
432
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
433
+ [
434
+ _dec,
435
+ 2,
436
+ "syncFromL1"
437
+ ],
438
+ [
439
+ _dec1,
440
+ 2,
441
+ "sync"
442
+ ],
443
+ [
444
+ _dec2,
445
+ 2,
446
+ "handleEpochPrune"
447
+ ],
448
+ [
449
+ _dec3,
450
+ 2,
451
+ "handleL1ToL2Messages"
452
+ ],
453
+ [
454
+ _dec4,
455
+ 2,
456
+ "handleCheckpoints"
457
+ ]
458
+ ], []));
459
+ }
460
+ /** A loop in which we will be continually fetching new checkpoints. */ runningPromise;
48
461
  rollup;
49
462
  inbox;
50
463
  store;
51
464
  l1BlockNumber;
52
465
  l1Timestamp;
53
- pendingChainValidationStatus;
54
466
  initialSyncComplete;
467
+ initialSyncPromise;
468
+ /** Queue of blocks to be added to the store, processed by the sync loop. */ blockQueue;
55
469
  tracer;
56
470
  /**
57
471
  * Creates a new instance of the Archiver.
58
472
  * @param publicClient - A client for interacting with the Ethereum node.
473
+ * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
59
474
  * @param rollupAddress - Ethereum address of the rollup contract.
60
475
  * @param inboxAddress - Ethereum address of the inbox contract.
61
476
  * @param registryAddress - Ethereum address of the registry contract.
62
477
  * @param pollingIntervalMs - The interval for polling for L1 logs (in milliseconds).
63
478
  * @param store - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
64
479
  * @param log - A logger.
65
- */ constructor(publicClient, l1Addresses, dataStore, config, blobSinkClient, epochCache, instrumentation, l1constants, log = createLogger('archiver')){
66
- super(), this.publicClient = publicClient, this.l1Addresses = l1Addresses, this.dataStore = dataStore, this.config = config, this.blobSinkClient = blobSinkClient, this.epochCache = epochCache, this.instrumentation = instrumentation, this.l1constants = l1constants, this.log = log, this.pendingChainValidationStatus = {
67
- valid: true
68
- }, this.initialSyncComplete = false;
480
+ */ constructor(publicClient, debugClient, l1Addresses, dataStore, config, blobClient, epochCache, dateProvider, instrumentation, l1constants, log = createLogger('archiver')){
481
+ super(), this.publicClient = publicClient, this.debugClient = debugClient, this.l1Addresses = l1Addresses, this.dataStore = dataStore, this.config = config, this.blobClient = blobClient, this.epochCache = epochCache, this.dateProvider = dateProvider, this.instrumentation = instrumentation, this.l1constants = l1constants, this.log = log, this.initialSyncComplete = (_initProto(this), false), this.blockQueue = [];
69
482
  this.tracer = instrumentation.tracer;
70
483
  this.store = new ArchiverStoreHelper(dataStore);
71
484
  this.rollup = new RollupContract(publicClient, l1Addresses.rollupAddress);
72
485
  this.inbox = new InboxContract(publicClient, l1Addresses.inboxAddress);
486
+ this.initialSyncPromise = promiseWithResolvers();
487
+ // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
488
+ // are done as fast as possible. This then gets updated once the initial sync completes.
489
+ this.runningPromise = new RunningPromise(()=>this.sync(), this.log, this.config.pollingIntervalMs / 10, makeLoggingErrorHandler(this.log, NoBlobBodiesFoundError, BlockTagTooOldError));
73
490
  }
74
491
  /**
75
492
  * Creates a new instance of the Archiver and blocks until it syncs from chain.
@@ -81,14 +498,27 @@ import { validateBlockAttestations } from './validation.js';
81
498
  const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
82
499
  const publicClient = createPublicClient({
83
500
  chain: chain.chainInfo,
84
- transport: fallback(config.l1RpcUrls.map((url)=>http(url))),
501
+ transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
502
+ batch: false
503
+ }))),
504
+ pollingInterval: config.viemPollingIntervalMS
505
+ });
506
+ // Create debug client using debug RPC URLs if available, otherwise fall back to regular RPC URLs
507
+ const debugRpcUrls = config.l1DebugRpcUrls.length > 0 ? config.l1DebugRpcUrls : config.l1RpcUrls;
508
+ const debugClient = createPublicClient({
509
+ chain: chain.chainInfo,
510
+ transport: fallback(debugRpcUrls.map((url)=>http(url, {
511
+ batch: false
512
+ }))),
85
513
  pollingInterval: config.viemPollingIntervalMS
86
514
  });
87
515
  const rollup = new RollupContract(publicClient, config.l1Contracts.rollupAddress);
88
- const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs] = await Promise.all([
516
+ const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, genesisArchiveRoot, slashingProposerAddress] = await Promise.all([
89
517
  rollup.getL1StartBlock(),
90
518
  rollup.getL1GenesisTime(),
91
- rollup.getProofSubmissionEpochs()
519
+ rollup.getProofSubmissionEpochs(),
520
+ rollup.getGenesisArchiveTreeRoot(),
521
+ rollup.getSlashingProposerAddress()
92
522
  ]);
93
523
  const l1StartBlockHash = await publicClient.getBlock({
94
524
  blockNumber: l1StartBlock,
@@ -102,61 +532,117 @@ import { validateBlockAttestations } from './validation.js';
102
532
  epochDuration,
103
533
  slotDuration,
104
534
  ethereumSlotDuration,
105
- proofSubmissionEpochs: Number(proofSubmissionEpochs)
106
- };
107
- const opts = {
108
- pollingIntervalMs: config.archiverPollingIntervalMS ?? 10_000,
109
- batchSize: config.archiverBatchSize ?? 100
535
+ proofSubmissionEpochs: Number(proofSubmissionEpochs),
536
+ genesisArchiveRoot: Fr.fromString(genesisArchiveRoot.toString())
110
537
  };
538
+ const opts = merge({
539
+ pollingIntervalMs: 10_000,
540
+ batchSize: 100,
541
+ maxAllowedEthClientDriftSeconds: 300,
542
+ ethereumAllowNoDebugHosts: false
543
+ }, mapArchiverConfig(config));
111
544
  const epochCache = deps.epochCache ?? await EpochCache.create(config.l1Contracts.rollupAddress, config, deps);
112
545
  const telemetry = deps.telemetry ?? getTelemetryClient();
113
- const archiver = new Archiver(publicClient, config.l1Contracts, archiverStore, opts, deps.blobSinkClient, epochCache, await ArchiverInstrumentation.new(telemetry, ()=>archiverStore.estimateSize()), l1Constants);
546
+ const archiver = new Archiver(publicClient, debugClient, {
547
+ ...config.l1Contracts,
548
+ slashingProposerAddress
549
+ }, archiverStore, opts, deps.blobClient, epochCache, deps.dateProvider ?? new DateProvider(), await ArchiverInstrumentation.new(telemetry, ()=>archiverStore.estimateSize()), l1Constants);
114
550
  await archiver.start(blockUntilSynced);
115
551
  return archiver;
116
552
  }
553
+ /** Updates archiver config */ updateConfig(newConfig) {
554
+ this.config = merge(this.config, mapArchiverConfig(newConfig));
555
+ }
117
556
  /**
118
557
  * Starts sync process.
119
558
  * @param blockUntilSynced - If true, blocks until the archiver has fully synced.
120
559
  */ async start(blockUntilSynced) {
121
- if (this.runningPromise) {
560
+ if (this.runningPromise.isRunning()) {
122
561
  throw new Error('Archiver is already running');
123
562
  }
124
- await this.blobSinkClient.testSources();
563
+ await this.blobClient.testSources();
564
+ await this.testEthereumNodeSynced();
565
+ await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false);
566
+ // Log initial state for the archiver
567
+ const { l1StartBlock } = this.l1constants;
568
+ const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await this.store.getSynchPoint();
569
+ const currentL2Checkpoint = await this.getSynchedCheckpointNumber();
570
+ this.log.info(`Starting archiver sync to rollup contract ${this.l1Addresses.rollupAddress.toString()} from L1 block ${blocksSynchedTo} and L2 checkpoint ${currentL2Checkpoint}`, {
571
+ blocksSynchedTo,
572
+ messagesSynchedTo,
573
+ currentL2Checkpoint
574
+ });
575
+ // Start sync loop, and return the wait for initial sync if we are asked to block until synced
576
+ this.runningPromise.start();
125
577
  if (blockUntilSynced) {
126
- while(!await this.syncSafe(true)){
127
- this.log.info(`Retrying initial archiver sync in ${this.config.pollingIntervalMs}ms`);
128
- await sleep(this.config.pollingIntervalMs);
129
- }
578
+ return this.waitForInitialSync();
130
579
  }
131
- this.runningPromise = new RunningPromise(()=>this.sync(false), this.log, this.config.pollingIntervalMs, makeLoggingErrorHandler(this.log, // Ignored errors will not log to the console
132
- // We ignore NoBlobBodiesFound as the message may not have been passed to the blob sink yet
133
- NoBlobBodiesFoundError));
134
- this.runningPromise.start();
135
580
  }
136
581
  syncImmediate() {
137
- if (!this.runningPromise) {
138
- throw new Error('Archiver is not running');
139
- }
140
582
  return this.runningPromise.trigger();
141
583
  }
142
- async syncSafe(initialRun) {
143
- try {
144
- await this.sync(initialRun);
145
- return true;
146
- } catch (error) {
147
- if (error instanceof NoBlobBodiesFoundError) {
148
- this.log.error(`Error syncing archiver: ${error.message}`);
149
- } else if (error instanceof BlockTagTooOldError) {
150
- this.log.warn(`Re-running archiver sync: ${error.message}`);
151
- } else {
152
- this.log.error('Error during archiver sync', error);
584
+ /**
585
+ * Queues a block to be added to the archiver store and triggers processing.
586
+ * The block will be processed by the sync loop.
587
+ * Implements the L2BlockSink interface.
588
+ * @param block - The L2 block to add.
589
+ * @returns A promise that resolves when the block has been added to the store, or rejects on error.
590
+ */ addBlock(block) {
591
+ return new Promise((resolve, reject)=>{
592
+ this.blockQueue.push({
593
+ block,
594
+ resolve,
595
+ reject
596
+ });
597
+ this.log.debug(`Queued block ${block.number} for processing`);
598
+ // Trigger an immediate sync, but don't wait for it - the promise resolves when the block is processed
599
+ this.syncImmediate().catch((err)=>{
600
+ this.log.error(`Sync immediate call failed: ${err}`);
601
+ });
602
+ });
603
+ }
604
+ /**
605
+ * Processes all queued blocks, adding them to the store.
606
+ * Called at the beginning of each sync iteration.
607
+ * Blocks are processed in the order they were queued.
608
+ */ async processQueuedBlocks() {
609
+ if (this.blockQueue.length === 0) {
610
+ return;
611
+ }
612
+ // Take all blocks from the queue
613
+ const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
614
+ this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
615
+ // Process each block individually to properly resolve/reject each promise
616
+ for (const { block, resolve, reject } of queuedItems){
617
+ try {
618
+ await this.store.addBlocks([
619
+ block
620
+ ]);
621
+ this.log.debug(`Added block ${block.number} to store`);
622
+ resolve();
623
+ } catch (err) {
624
+ this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
625
+ reject(err);
153
626
  }
154
- return false;
155
627
  }
156
628
  }
157
- /**
158
- * Fetches logs from L1 contracts and processes them.
159
- */ async sync(initialRun) {
629
+ waitForInitialSync() {
630
+ return this.initialSyncPromise.promise;
631
+ }
632
+ /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */ async testEthereumNodeSynced() {
633
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
634
+ if (maxAllowedDelay === 0) {
635
+ return;
636
+ }
637
+ const { number, timestamp: l1Timestamp } = await this.publicClient.getBlock({
638
+ includeTransactions: false
639
+ });
640
+ const currentTime = BigInt(this.dateProvider.nowInSeconds());
641
+ if (currentTime - l1Timestamp > BigInt(maxAllowedDelay)) {
642
+ throw new Error(`Ethereum node is out of sync (last block synced ${number} at ${l1Timestamp} vs current time ${currentTime})`);
643
+ }
644
+ }
645
+ async syncFromL1() {
160
646
  /**
161
647
  * We keep track of three "pointers" to L1 blocks:
162
648
  * 1. the last L1 block that published an L2 block
@@ -166,8 +652,6 @@ import { validateBlockAttestations } from './validation.js';
166
652
  * We do this to deal with L1 data providers that are eventually consistent (e.g. Infura).
167
653
  * We guard against seeing block X with no data at one point, and later, the provider processes the block and it has data.
168
654
  * The archiver will stay back, until there's data on L1 that will move the pointers forward.
169
- *
170
- * This code does not handle reorgs.
171
655
  */ const { l1StartBlock, l1StartBlockHash } = this.l1constants;
172
656
  const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = {
173
657
  l1BlockNumber: l1StartBlock,
@@ -178,12 +662,12 @@ import { validateBlockAttestations } from './validation.js';
178
662
  });
179
663
  const currentL1BlockNumber = currentL1Block.number;
180
664
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
181
- if (initialRun) {
182
- this.log.info(`Starting archiver sync to rollup contract ${this.l1Addresses.rollupAddress.toString()} from L1 block ${blocksSynchedTo}` + ` to current L1 block ${currentL1BlockNumber} with hash ${currentL1BlockHash.toString()}`, {
183
- blocksSynchedTo,
184
- messagesSynchedTo
185
- });
186
- }
665
+ this.log.trace(`Starting new archiver sync iteration`, {
666
+ blocksSynchedTo,
667
+ messagesSynchedTo,
668
+ currentL1BlockNumber,
669
+ currentL1BlockHash
670
+ });
187
671
  // ********** Ensuring Consistency of data pulled from L1 **********
188
672
  /**
189
673
  * There are a number of calls in this sync operation to L1 for retrieving
@@ -206,28 +690,40 @@ import { validateBlockAttestations } from './validation.js';
206
690
  const currentL1Timestamp = !this.l1Timestamp || !this.l1BlockNumber || this.l1BlockNumber !== currentL1BlockNumber ? (await this.publicClient.getBlock({
207
691
  blockNumber: currentL1BlockNumber
208
692
  })).timestamp : this.l1Timestamp;
209
- // ********** Events that are processed per L2 block **********
693
+ // Warn if the latest L1 block timestamp is too old
694
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
695
+ const now = this.dateProvider.nowInSeconds();
696
+ if (maxAllowedDelay > 0 && Number(currentL1Timestamp) <= now - maxAllowedDelay) {
697
+ this.log.warn(`Latest L1 block ${currentL1BlockNumber} timestamp ${currentL1Timestamp} is too old. Make sure your Ethereum node is synced.`, {
698
+ currentL1BlockNumber,
699
+ currentL1Timestamp,
700
+ now,
701
+ maxAllowedDelay
702
+ });
703
+ }
704
+ // ********** Events that are processed per checkpoint **********
210
705
  if (currentL1BlockNumber > blocksSynchedTo) {
211
- // First we retrieve new L2 blocks
212
- const rollupStatus = await this.handleL2blocks(blocksSynchedTo, currentL1BlockNumber);
706
+ // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
707
+ // pending chain validation status, proven checkpoint number, and synched L1 block number.
708
+ const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber);
213
709
  // Then we prune the current epoch if it'd reorg on next submission.
214
- // Note that we don't do this before retrieving L2 blocks because we may need to retrieve
215
- // blocks from more than 2 epochs ago, so we want to make sure we have the latest view of
710
+ // Note that we don't do this before retrieving checkpoints because we may need to retrieve
711
+ // checkpoints from more than 2 epochs ago, so we want to make sure we have the latest view of
216
712
  // the chain locally before we start unwinding stuff. This can be optimized by figuring out
217
- // up to which point we're pruning, and then requesting L2 blocks up to that point only.
218
- const { rollupCanPrune } = await this.handleEpochPrune(rollupStatus.provenBlockNumber, currentL1BlockNumber, currentL1Timestamp);
219
- // Update the pending chain validation status with the last block validation result.
220
- // Again, we only update if validation status changed, so in a sequence of invalid blocks
221
- // we keep track of the first invalid block so we can invalidate that one if needed.
222
- if (rollupStatus.validationResult && rollupStatus.validationResult?.valid !== this.pendingChainValidationStatus.valid) {
223
- this.pendingChainValidationStatus = rollupStatus.validationResult;
713
+ // up to which point we're pruning, and then requesting checkpoints up to that point only.
714
+ const { rollupCanPrune } = await this.handleEpochPrune(rollupStatus.provenCheckpointNumber, currentL1BlockNumber, currentL1Timestamp);
715
+ // If the last checkpoint we processed had an invalid attestation, we manually advance the L1 syncpoint
716
+ // past it, since otherwise we'll keep downloading it and reprocessing it on every iteration until
717
+ // we get a valid checkpoint to advance the syncpoint.
718
+ if (!rollupStatus.validationResult?.valid && rollupStatus.lastL1BlockWithCheckpoint !== undefined) {
719
+ await this.store.setCheckpointSynchedL1BlockNumber(rollupStatus.lastL1BlockWithCheckpoint);
224
720
  }
225
- // And lastly we check if we are missing any L2 blocks behind us due to a possible L1 reorg.
721
+ // And lastly we check if we are missing any checkpoints behind us due to a possible L1 reorg.
226
722
  // We only do this if rollup cant prune on the next submission. Otherwise we will end up
227
- // re-syncing the blocks we have just unwound above. We also dont do this if the last block is invalid,
723
+ // re-syncing the checkpoints we have just unwound above. We also dont do this if the last checkpoint is invalid,
228
724
  // since the archiver will rightfully refuse to sync up to it.
229
- if (!rollupCanPrune && this.pendingChainValidationStatus.valid) {
230
- await this.checkForNewBlocksBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
725
+ if (!rollupCanPrune && rollupStatus.validationResult?.valid) {
726
+ await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
231
727
  }
232
728
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
233
729
  }
@@ -236,15 +732,27 @@ import { validateBlockAttestations } from './validation.js';
236
732
  // but the corresponding blocks have not been processed (see #12631).
237
733
  this.l1Timestamp = currentL1Timestamp;
238
734
  this.l1BlockNumber = currentL1BlockNumber;
239
- this.initialSyncComplete = true;
240
- if (initialRun) {
241
- this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete.`, {
735
+ // We resolve the initial sync only once we've caught up with the latest L1 block number (with 1 block grace)
736
+ // so if the initial sync took too long, we still go for another iteration.
737
+ if (!this.initialSyncComplete && currentL1BlockNumber + 1n >= await this.publicClient.getBlockNumber()) {
738
+ this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete`, {
242
739
  l1BlockNumber: currentL1BlockNumber,
243
740
  syncPoint: await this.store.getSynchPoint(),
244
741
  ...await this.getL2Tips()
245
742
  });
743
+ this.runningPromise.setPollingIntervalMS(this.config.pollingIntervalMs);
744
+ this.initialSyncComplete = true;
745
+ this.initialSyncPromise.resolve();
246
746
  }
247
747
  }
748
+ /**
749
+ * Fetches logs from L1 contracts and processes them.
750
+ */ async sync() {
751
+ // Process any queued blocks first, before doing L1 sync
752
+ await this.processQueuedBlocks();
753
+ // Now perform L1 sync
754
+ await this.syncFromL1();
755
+ }
248
756
  /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
249
757
  const time = (currentL1Timestamp ?? 0n) + BigInt(this.l1constants.ethereumSlotDuration);
250
758
  const result = await this.rollup.canPruneAtTime(time, {
@@ -259,30 +767,37 @@ import { validateBlockAttestations } from './validation.js';
259
767
  }
260
768
  return result;
261
769
  }
262
- /** Checks if there'd be a reorg for the next block submission and start pruning now. */ async handleEpochPrune(provenBlockNumber, currentL1BlockNumber, currentL1Timestamp) {
770
+ /** Checks if there'd be a reorg for the next checkpoint submission and start pruning now. */ async handleEpochPrune(provenCheckpointNumber, currentL1BlockNumber, currentL1Timestamp) {
263
771
  const rollupCanPrune = await this.canPrune(currentL1BlockNumber, currentL1Timestamp);
264
- const localPendingBlockNumber = await this.getBlockNumber();
265
- const canPrune = localPendingBlockNumber > provenBlockNumber && rollupCanPrune;
772
+ const localPendingCheckpointNumber = await this.getSynchedCheckpointNumber();
773
+ const canPrune = localPendingCheckpointNumber > provenCheckpointNumber && rollupCanPrune;
266
774
  if (canPrune) {
267
775
  const timer = new Timer();
268
- const pruneFrom = provenBlockNumber + 1;
269
- const header = await this.getBlockHeader(Number(pruneFrom));
776
+ const pruneFrom = CheckpointNumber(provenCheckpointNumber + 1);
777
+ const header = await this.getCheckpointHeader(pruneFrom);
270
778
  if (header === undefined) {
271
- throw new Error(`Missing block header ${pruneFrom}`);
779
+ throw new Error(`Missing checkpoint header ${pruneFrom}`);
272
780
  }
273
- const pruneFromSlotNumber = header.globalVariables.slotNumber.toBigInt();
781
+ const pruneFromSlotNumber = header.slotNumber;
274
782
  const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1constants);
275
- const blocksToUnwind = localPendingBlockNumber - provenBlockNumber;
276
- const blocks = await this.getBlocks(Number(provenBlockNumber) + 1, Number(blocksToUnwind));
783
+ const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
784
+ const checkpointPromises = Array.from({
785
+ length: checkpointsToUnwind
786
+ }).fill(0).map((_, i)=>this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
787
+ const checkpoints = await Promise.all(checkpointPromises);
788
+ const blockPromises = await Promise.all(checkpoints.filter(isDefined).map((cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))));
789
+ const newBlocks = blockPromises.filter(isDefined).flat();
790
+ // TODO(pw/mbps): Don't convert to legacy blocks here
791
+ const blocks = (await Promise.all(newBlocks.map((x)=>this.getBlock(x.number)))).filter(isDefined);
277
792
  // Emit an event for listening services to react to the chain prune
278
793
  this.emit(L2BlockSourceEvents.L2PruneDetected, {
279
794
  type: L2BlockSourceEvents.L2PruneDetected,
280
795
  epochNumber: pruneFromEpochNumber,
281
796
  blocks
282
797
  });
283
- this.log.debug(`L2 prune from ${provenBlockNumber + 1} to ${localPendingBlockNumber} will occur on next block submission.`);
284
- await this.store.unwindBlocks(Number(localPendingBlockNumber), Number(blocksToUnwind));
285
- this.log.warn(`Unwound ${count(blocksToUnwind, 'block')} from L2 block ${localPendingBlockNumber} ` + `to ${provenBlockNumber} due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest block is ${await this.getBlockNumber()}.`);
798
+ this.log.debug(`L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`);
799
+ await this.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
800
+ this.log.warn(`Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` + `to ${provenCheckpointNumber} due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated latest checkpoint is ${await this.getSynchedCheckpointNumber()}.`);
286
801
  this.instrumentation.processPrune(timer.ms());
287
802
  // TODO(palla/reorg): Do we need to set the block synched L1 block number here?
288
803
  // Seems like the next iteration should handle this.
@@ -325,7 +840,7 @@ import { validateBlockAttestations } from './validation.js';
325
840
  });
326
841
  // Compare message count and rolling hash. If they match, no need to retrieve anything.
327
842
  if (remoteMessagesState.totalMessagesInserted === localMessagesInserted && remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)) {
328
- this.log.debug(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
843
+ this.log.trace(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
329
844
  return;
330
845
  }
331
846
  // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
@@ -374,7 +889,7 @@ import { validateBlockAttestations } from './validation.js';
374
889
  }while (searchEndBlock < currentL1BlockNumber)
375
890
  // Log stats for messages retrieved (if any).
376
891
  if (messageCount > 0) {
377
- this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for L2 block ${lastMessage?.l2BlockNumber}`, {
892
+ this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
378
893
  lastMessage,
379
894
  messageCount
380
895
  });
@@ -451,156 +966,171 @@ import { validateBlockAttestations } from './validation.js';
451
966
  }
452
967
  return Buffer32.fromString(block.hash);
453
968
  }
454
- async handleL2blocks(blocksSynchedTo, currentL1BlockNumber) {
455
- const localPendingBlockNumber = await this.getBlockNumber();
456
- const [provenBlockNumber, provenArchive, pendingBlockNumber, pendingArchive, archiveForLocalPendingBlockNumber] = await this.rollup.status(BigInt(localPendingBlockNumber), {
457
- blockNumber: currentL1BlockNumber
458
- });
969
+ async handleCheckpoints(blocksSynchedTo, currentL1BlockNumber) {
970
+ const localPendingCheckpointNumber = await this.getSynchedCheckpointNumber();
971
+ const initialValidationResult = await this.store.getPendingChainValidationStatus();
972
+ const { provenCheckpointNumber, provenArchive, pendingCheckpointNumber, pendingArchive, archiveOfMyCheckpoint: archiveForLocalPendingCheckpointNumber } = await execInSpan(this.tracer, 'Archiver.getRollupStatus', ()=>this.rollup.status(localPendingCheckpointNumber, {
973
+ blockNumber: currentL1BlockNumber
974
+ }));
459
975
  const rollupStatus = {
460
- provenBlockNumber: Number(provenBlockNumber),
461
- provenArchive,
462
- pendingBlockNumber: Number(pendingBlockNumber),
463
- pendingArchive,
464
- validationResult: undefined
976
+ provenCheckpointNumber,
977
+ provenArchive: provenArchive.toString(),
978
+ pendingCheckpointNumber,
979
+ pendingArchive: pendingArchive.toString(),
980
+ validationResult: initialValidationResult
465
981
  };
466
982
  this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
467
- localPendingBlockNumber,
983
+ localPendingCheckpointNumber,
468
984
  blocksSynchedTo,
469
985
  currentL1BlockNumber,
470
- archiveForLocalPendingBlockNumber,
986
+ archiveForLocalPendingCheckpointNumber,
471
987
  ...rollupStatus
472
988
  });
473
- const updateProvenBlock = async ()=>{
474
- // Annoying edge case: if proven block is moved back to 0 due to a reorg at the beginning of the chain,
475
- // we need to set it to zero. This is an edge case because we dont have a block zero (initial block is one),
476
- // so localBlockForDestinationProvenBlockNumber would not be found below.
477
- if (provenBlockNumber === 0n) {
478
- const localProvenBlockNumber = await this.store.getProvenL2BlockNumber();
479
- if (localProvenBlockNumber !== Number(provenBlockNumber)) {
480
- await this.store.setProvenL2BlockNumber(Number(provenBlockNumber));
481
- this.log.info(`Rolled back proven chain to block ${provenBlockNumber}`, {
482
- provenBlockNumber
989
+ const updateProvenCheckpoint = async ()=>{
990
+ // Annoying edge case: if proven checkpoint is moved back to 0 due to a reorg at the beginning of the chain,
991
+ // we need to set it to zero. This is an edge case because we dont have a checkpoint zero (initial checkpoint is one),
992
+ // so localCheckpointForDestinationProvenCheckpointNumber would not be found below.
993
+ if (provenCheckpointNumber === 0) {
994
+ const localProvenCheckpointNumber = await this.getProvenCheckpointNumber();
995
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
996
+ await this.setProvenCheckpointNumber(provenCheckpointNumber);
997
+ this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, {
998
+ provenCheckpointNumber
483
999
  });
484
1000
  }
485
1001
  }
486
- const localBlockForDestinationProvenBlockNumber = await this.getBlock(Number(provenBlockNumber));
487
- // Sanity check. I've hit what seems to be a state where the proven block is set to a value greater than the latest
488
- // synched block when requesting L2Tips from the archiver. This is the only place where the proven block is set.
489
- const synched = await this.store.getSynchedL2BlockNumber();
490
- if (localBlockForDestinationProvenBlockNumber && synched < localBlockForDestinationProvenBlockNumber?.number) {
491
- this.log.error(`Hit local block greater than last synched block: ${localBlockForDestinationProvenBlockNumber.number} > ${synched}`);
1002
+ const localCheckpointForDestinationProvenCheckpointNumber = await this.store.getCheckpointData(provenCheckpointNumber);
1003
+ // Sanity check. I've hit what seems to be a state where the proven checkpoint is set to a value greater than the latest
1004
+ // synched checkpoint when requesting L2Tips from the archiver. This is the only place where the proven checkpoint is set.
1005
+ const synched = await this.getSynchedCheckpointNumber();
1006
+ if (localCheckpointForDestinationProvenCheckpointNumber && synched < localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber) {
1007
+ this.log.error(`Hit local checkpoint greater than last synched checkpoint: ${localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber} > ${synched}`);
492
1008
  }
493
- this.log.trace(`Local block for remote proven block ${provenBlockNumber} is ${localBlockForDestinationProvenBlockNumber?.archive.root.toString() ?? 'undefined'}`);
494
- if (localBlockForDestinationProvenBlockNumber && provenArchive === localBlockForDestinationProvenBlockNumber.archive.root.toString()) {
495
- const localProvenBlockNumber = await this.store.getProvenL2BlockNumber();
496
- if (localProvenBlockNumber !== Number(provenBlockNumber)) {
497
- await this.store.setProvenL2BlockNumber(Number(provenBlockNumber));
498
- this.log.info(`Updated proven chain to block ${provenBlockNumber}`, {
499
- provenBlockNumber
1009
+ this.log.trace(`Local checkpoint for remote proven checkpoint ${provenCheckpointNumber} is ${localCheckpointForDestinationProvenCheckpointNumber?.archive.root.toString() ?? 'undefined'}`);
1010
+ if (localCheckpointForDestinationProvenCheckpointNumber && provenArchive.equals(localCheckpointForDestinationProvenCheckpointNumber.archive.root)) {
1011
+ const localProvenCheckpointNumber = await this.getProvenCheckpointNumber();
1012
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
1013
+ await this.setProvenCheckpointNumber(provenCheckpointNumber);
1014
+ this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, {
1015
+ provenCheckpointNumber
500
1016
  });
501
- const provenSlotNumber = localBlockForDestinationProvenBlockNumber.header.globalVariables.slotNumber.toBigInt();
1017
+ const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
502
1018
  const provenEpochNumber = getEpochAtSlot(provenSlotNumber, this.l1constants);
1019
+ const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.numBlocks - 1;
503
1020
  this.emit(L2BlockSourceEvents.L2BlockProven, {
504
1021
  type: L2BlockSourceEvents.L2BlockProven,
505
- blockNumber: provenBlockNumber,
1022
+ blockNumber: BlockNumber(lastBlockNumberInCheckpoint),
506
1023
  slotNumber: provenSlotNumber,
507
1024
  epochNumber: provenEpochNumber
508
1025
  });
1026
+ this.instrumentation.updateLastProvenBlock(lastBlockNumberInCheckpoint);
509
1027
  } else {
510
- this.log.trace(`Proven block ${provenBlockNumber} already stored.`);
1028
+ this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
511
1029
  }
512
1030
  }
513
- this.instrumentation.updateLastProvenBlock(Number(provenBlockNumber));
514
1031
  };
515
- // This is an edge case that we only hit if there are no proposed blocks.
516
- // If we have 0 blocks locally and there are no blocks onchain there is nothing to do.
517
- const noBlocks = localPendingBlockNumber === 0 && pendingBlockNumber === 0n;
518
- if (noBlocks) {
519
- await this.store.setBlockSynchedL1BlockNumber(currentL1BlockNumber);
520
- this.log.debug(`No blocks to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no blocks on chain`);
1032
+ // This is an edge case that we only hit if there are no proposed checkpoints.
1033
+ // If we have 0 checkpoints locally and there are no checkpoints onchain there is nothing to do.
1034
+ const noCheckpoints = localPendingCheckpointNumber === 0 && pendingCheckpointNumber === 0;
1035
+ if (noCheckpoints) {
1036
+ await this.store.setCheckpointSynchedL1BlockNumber(currentL1BlockNumber);
1037
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`);
521
1038
  return rollupStatus;
522
1039
  }
523
- await updateProvenBlock();
1040
+ await updateProvenCheckpoint();
524
1041
  // Related to the L2 reorgs of the pending chain. We are only interested in actually addressing a reorg if there
525
- // are any state that could be impacted by it. If we have no blocks, there is no impact.
526
- if (localPendingBlockNumber > 0) {
527
- const localPendingBlock = await this.getBlock(localPendingBlockNumber);
528
- if (localPendingBlock === undefined) {
529
- throw new Error(`Missing block ${localPendingBlockNumber}`);
1042
+ // are any state that could be impacted by it. If we have no checkpoints, there is no impact.
1043
+ if (localPendingCheckpointNumber > 0) {
1044
+ const localPendingCheckpoint = await this.store.getCheckpointData(localPendingCheckpointNumber);
1045
+ if (localPendingCheckpoint === undefined) {
1046
+ throw new Error(`Missing checkpoint ${localPendingCheckpointNumber}`);
530
1047
  }
531
- const localPendingArchiveRoot = localPendingBlock.archive.root.toString();
532
- const noBlockSinceLast = localPendingBlock && pendingArchive === localPendingArchiveRoot;
533
- if (noBlockSinceLast) {
1048
+ const localPendingArchiveRoot = localPendingCheckpoint.archive.root.toString();
1049
+ const noCheckpointSinceLast = localPendingCheckpoint && pendingArchive.toString() === localPendingArchiveRoot;
1050
+ if (noCheckpointSinceLast) {
534
1051
  // We believe the following line causes a problem when we encounter L1 re-orgs.
535
1052
  // Basically, by setting the synched L1 block number here, we are saying that we have
536
- // processed all blocks up to the current L1 block number and we will not attempt to retrieve logs from
1053
+ // processed all checkpoints up to the current L1 block number and we will not attempt to retrieve logs from
537
1054
  // this block again (or any blocks before).
538
- // However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing blocks
1055
+ // However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing checkpoints.
539
1056
  // We must only set this block number based on actually retrieved logs.
540
1057
  // TODO(#8621): Tackle this properly when we handle L1 Re-orgs.
541
1058
  // await this.store.setBlockSynchedL1BlockNumber(currentL1BlockNumber);
542
- this.log.debug(`No blocks to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
1059
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
543
1060
  return rollupStatus;
544
1061
  }
545
- const localPendingBlockInChain = archiveForLocalPendingBlockNumber === localPendingArchiveRoot;
546
- if (!localPendingBlockInChain) {
547
- // If our local pending block tip is not in the chain on L1 a "prune" must have happened
1062
+ const localPendingCheckpointInChain = archiveForLocalPendingCheckpointNumber.equals(localPendingCheckpoint.archive.root);
1063
+ if (!localPendingCheckpointInChain) {
1064
+ // If our local pending checkpoint tip is not in the chain on L1 a "prune" must have happened
548
1065
  // or the L1 have reorged.
549
1066
  // In any case, we have to figure out how far into the past the action will take us.
550
- // For simplicity here, we will simply rewind until we end in a block that is also on the chain on L1.
551
- this.log.debug(`L2 prune has been detected due to local pending block ${localPendingBlockNumber} not in chain`, {
552
- localPendingBlockNumber,
1067
+ // For simplicity here, we will simply rewind until we end in a checkpoint that is also on the chain on L1.
1068
+ this.log.debug(`L2 prune has been detected due to local pending checkpoint ${localPendingCheckpointNumber} not in chain`, {
1069
+ localPendingCheckpointNumber,
553
1070
  localPendingArchiveRoot,
554
- archiveForLocalPendingBlockNumber
1071
+ archiveForLocalPendingCheckpointNumber
555
1072
  });
556
- let tipAfterUnwind = localPendingBlockNumber;
1073
+ let tipAfterUnwind = localPendingCheckpointNumber;
557
1074
  while(true){
558
- const candidateBlock = await this.getBlock(Number(tipAfterUnwind));
559
- if (candidateBlock === undefined) {
1075
+ const candidateCheckpoint = await this.store.getCheckpointData(tipAfterUnwind);
1076
+ if (candidateCheckpoint === undefined) {
560
1077
  break;
561
1078
  }
562
- const archiveAtContract = await this.rollup.archiveAt(BigInt(candidateBlock.number));
563
- if (archiveAtContract === candidateBlock.archive.root.toString()) {
1079
+ const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.checkpointNumber);
1080
+ this.log.trace(`Checking local checkpoint ${candidateCheckpoint.checkpointNumber} with archive ${candidateCheckpoint.archive.root}`, {
1081
+ archiveAtContract,
1082
+ archiveLocal: candidateCheckpoint.archive.root.toString()
1083
+ });
1084
+ if (archiveAtContract.equals(candidateCheckpoint.archive.root)) {
564
1085
  break;
565
1086
  }
566
1087
  tipAfterUnwind--;
567
1088
  }
568
- const blocksToUnwind = localPendingBlockNumber - tipAfterUnwind;
569
- await this.store.unwindBlocks(Number(localPendingBlockNumber), Number(blocksToUnwind));
570
- this.log.warn(`Unwound ${count(blocksToUnwind, 'block')} from L2 block ${localPendingBlockNumber} ` + `due to mismatched block hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest block is ${await this.getBlockNumber()}.`);
1089
+ const checkpointsToUnwind = localPendingCheckpointNumber - tipAfterUnwind;
1090
+ await this.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
1091
+ this.log.warn(`Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` + `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest checkpoint is ${await this.getSynchedCheckpointNumber()}.`);
571
1092
  }
572
1093
  }
573
- // Retrieve L2 blocks in batches. Each batch is estimated to accommodate up to L2 'blockBatchSize' blocks,
1094
+ // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
574
1095
  // computed using the L2 block time vs the L1 block time.
575
1096
  let searchStartBlock = blocksSynchedTo;
576
1097
  let searchEndBlock = blocksSynchedTo;
577
- let lastRetrievedBlock;
1098
+ let lastRetrievedCheckpoint;
1099
+ let lastL1BlockWithCheckpoint = undefined;
578
1100
  do {
579
1101
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
580
- this.log.trace(`Retrieving L2 blocks from L1 block ${searchStartBlock} to ${searchEndBlock}`);
581
- // TODO(md): Retrieve from blob sink then from consensus client, then from peers
582
- const retrievedBlocks = await retrieveBlocksFromRollup(this.rollup.getContract(), this.publicClient, this.blobSinkClient, searchStartBlock, searchEndBlock, this.log);
583
- if (retrievedBlocks.length === 0) {
1102
+ this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
1103
+ // TODO(md): Retrieve from blob client then from consensus client, then from peers
1104
+ const retrievedCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointsFromRollup', ()=>retrieveCheckpointsFromRollup(this.rollup.getContract(), this.publicClient, this.debugClient, this.blobClient, searchStartBlock, searchEndBlock, this.l1Addresses, this.instrumentation, this.log, !this.initialSyncComplete));
1105
+ if (retrievedCheckpoints.length === 0) {
584
1106
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
585
1107
  // See further details in earlier comments.
586
- this.log.trace(`Retrieved no new L2 blocks from L1 block ${searchStartBlock} to ${searchEndBlock}`);
1108
+ this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
587
1109
  continue;
588
1110
  }
589
- const lastProcessedL1BlockNumber = retrievedBlocks[retrievedBlocks.length - 1].l1.blockNumber;
590
- this.log.debug(`Retrieved ${retrievedBlocks.length} new L2 blocks between L1 blocks ${searchStartBlock} and ${searchEndBlock} with last processed L1 block ${lastProcessedL1BlockNumber}.`);
591
- const publishedBlocks = retrievedBlocks.map((b)=>retrievedBlockToPublishedL2Block(b));
592
- const validBlocks = [];
593
- for (const block of publishedBlocks){
594
- const validationResult = await validateBlockAttestations(block, this.epochCache, this.l1constants, this.log);
595
- // Only update the validation result if it has changed, so we can keep track of the first invalid block
596
- // in case there is a sequence of more than one invalid block, as we need to invalidate the first one.
597
- if (rollupStatus.validationResult?.valid !== validationResult.valid) {
1111
+ this.log.debug(`Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
1112
+ lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
1113
+ searchStartBlock,
1114
+ searchEndBlock
1115
+ });
1116
+ const publishedCheckpoints = await Promise.all(retrievedCheckpoints.map((b)=>retrievedToPublishedCheckpoint(b)));
1117
+ const validCheckpoints = [];
1118
+ for (const published of publishedCheckpoints){
1119
+ const validationResult = this.config.skipValidateBlockAttestations ? {
1120
+ valid: true
1121
+ } : await validateCheckpointAttestations(published, this.epochCache, this.l1constants, this.log);
1122
+ // Only update the validation result if it has changed, so we can keep track of the first invalid checkpoint
1123
+ // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
1124
+ // There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
1125
+ // we need to update the validation result, since we need to be able to invalidate the new one.
1126
+ // See test 'chain progresses if an invalid checkpoint is invalidated with an invalid one' for more info.
1127
+ if (rollupStatus.validationResult?.valid !== validationResult.valid || !rollupStatus.validationResult.valid && !validationResult.valid && rollupStatus.validationResult.block.blockNumber === validationResult.block.blockNumber) {
598
1128
  rollupStatus.validationResult = validationResult;
599
1129
  }
600
1130
  if (!validationResult.valid) {
601
- this.log.warn(`Skipping block ${block.block.number} due to invalid attestations`, {
602
- blockHash: block.block.hash(),
603
- l1BlockNumber: block.l1.blockNumber,
1131
+ this.log.warn(`Skipping checkpoint ${published.checkpoint.number} due to invalid attestations`, {
1132
+ checkpointHash: published.checkpoint.hash(),
1133
+ l1BlockNumber: published.l1.blockNumber,
604
1134
  ...pick(validationResult, 'reason')
605
1135
  });
606
1136
  // Emit event for invalid block detection
@@ -610,84 +1140,107 @@ import { validateBlockAttestations } from './validation.js';
610
1140
  });
611
1141
  continue;
612
1142
  }
613
- validBlocks.push(block);
614
- this.log.debug(`Ingesting new L2 block ${block.block.number} with ${block.block.body.txEffects.length} txs`, {
615
- blockHash: block.block.hash(),
616
- l1BlockNumber: block.l1.blockNumber,
617
- ...block.block.header.globalVariables.toInspect(),
618
- ...block.block.getStats()
1143
+ // Check the inHash of the checkpoint against the l1->l2 messages.
1144
+ // The messages should've been synced up to the currentL1BlockNumber and must be available for the published
1145
+ // checkpoints we just retrieved.
1146
+ const l1ToL2Messages = await this.getL1ToL2Messages(published.checkpoint.number);
1147
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
1148
+ const publishedInHash = published.checkpoint.header.contentCommitment.inHash;
1149
+ if (!computedInHash.equals(publishedInHash)) {
1150
+ this.log.fatal(`Mismatch inHash for checkpoint ${published.checkpoint.number}`, {
1151
+ checkpointHash: published.checkpoint.hash(),
1152
+ l1BlockNumber: published.l1.blockNumber,
1153
+ computedInHash,
1154
+ publishedInHash
1155
+ });
1156
+ // Throwing an error since this is most likely caused by a bug.
1157
+ throw new Error(`Mismatch inHash for checkpoint ${published.checkpoint.number}. Expected ${computedInHash} but got ${publishedInHash}`);
1158
+ }
1159
+ validCheckpoints.push(published);
1160
+ this.log.debug(`Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`, {
1161
+ checkpointHash: published.checkpoint.hash(),
1162
+ l1BlockNumber: published.l1.blockNumber,
1163
+ ...published.checkpoint.header.toInspect(),
1164
+ blocks: published.checkpoint.blocks.map((b)=>b.getStats())
619
1165
  });
620
1166
  }
621
1167
  try {
622
- const [processDuration] = await elapsed(()=>this.store.addBlocks(validBlocks));
623
- this.instrumentation.processNewBlocks(processDuration / validBlocks.length, validBlocks.map((b)=>b.block));
1168
+ const updatedValidationResult = rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1169
+ const [processDuration] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.addCheckpoints', ()=>this.addCheckpoints(validCheckpoints, updatedValidationResult)));
1170
+ this.instrumentation.processNewBlocks(processDuration / validCheckpoints.length, validCheckpoints.flatMap((c)=>c.checkpoint.blocks));
624
1171
  } catch (err) {
625
- if (err instanceof InitialBlockNumberNotSequentialError) {
626
- const { previousBlockNumber, newBlockNumber } = err;
627
- const previousBlock = previousBlockNumber ? await this.store.getPublishedBlock(previousBlockNumber) : undefined;
628
- const updatedL1SyncPoint = previousBlock?.l1.blockNumber ?? this.l1constants.l1StartBlock;
1172
+ if (err instanceof InitialCheckpointNumberNotSequentialError) {
1173
+ const { previousCheckpointNumber, newCheckpointNumber } = err;
1174
+ const previousCheckpoint = previousCheckpointNumber ? await this.store.getCheckpointData(CheckpointNumber(previousCheckpointNumber)) : undefined;
1175
+ const updatedL1SyncPoint = previousCheckpoint?.l1.blockNumber ?? this.l1constants.l1StartBlock;
629
1176
  await this.store.setBlockSynchedL1BlockNumber(updatedL1SyncPoint);
630
- this.log.warn(`Attempting to insert block ${newBlockNumber} with previous block ${previousBlockNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`, {
631
- previousBlockNumber,
632
- previousBlockHash: await previousBlock?.block.hash(),
633
- newBlockNumber,
1177
+ this.log.warn(`Attempting to insert checkpoint ${newCheckpointNumber} with previous block ${previousCheckpointNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`, {
1178
+ previousCheckpointNumber,
1179
+ newCheckpointNumber,
634
1180
  updatedL1SyncPoint
635
1181
  });
636
1182
  }
637
1183
  throw err;
638
1184
  }
639
- for (const block of validBlocks){
640
- this.log.info(`Downloaded L2 block ${block.block.number}`, {
641
- blockHash: await block.block.hash(),
642
- blockNumber: block.block.number,
643
- txCount: block.block.body.txEffects.length,
644
- globalVariables: block.block.header.globalVariables.toInspect(),
645
- archiveRoot: block.block.archive.root.toString(),
646
- archiveNextLeafIndex: block.block.archive.nextAvailableLeafIndex
1185
+ for (const checkpoint of validCheckpoints){
1186
+ this.log.info(`Downloaded checkpoint ${checkpoint.checkpoint.number}`, {
1187
+ checkpointHash: checkpoint.checkpoint.hash(),
1188
+ checkpointNumber: checkpoint.checkpoint.number,
1189
+ blockCount: checkpoint.checkpoint.blocks.length,
1190
+ txCount: checkpoint.checkpoint.blocks.reduce((acc, b)=>acc + b.body.txEffects.length, 0),
1191
+ header: checkpoint.checkpoint.header.toInspect(),
1192
+ archiveRoot: checkpoint.checkpoint.archive.root.toString(),
1193
+ archiveNextLeafIndex: checkpoint.checkpoint.archive.nextAvailableLeafIndex
647
1194
  });
648
1195
  }
649
- lastRetrievedBlock = validBlocks.at(-1) ?? lastRetrievedBlock;
1196
+ lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1197
+ lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
650
1198
  }while (searchEndBlock < currentL1BlockNumber)
651
1199
  // Important that we update AFTER inserting the blocks.
652
- await updateProvenBlock();
1200
+ await updateProvenCheckpoint();
653
1201
  return {
654
1202
  ...rollupStatus,
655
- lastRetrievedBlock
1203
+ lastRetrievedCheckpoint,
1204
+ lastL1BlockWithCheckpoint
656
1205
  };
657
1206
  }
658
- async checkForNewBlocksBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
659
- const { lastRetrievedBlock, pendingBlockNumber } = status;
660
- // Compare the last L2 block we have (either retrieved in this round or loaded from store) with what the
1207
+ async checkForNewCheckpointsBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
1208
+ const { lastRetrievedCheckpoint, pendingCheckpointNumber } = status;
1209
+ // Compare the last checkpoint we have (either retrieved in this round or loaded from store) with what the
661
1210
  // rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
662
- const latestLocalL2BlockNumber = lastRetrievedBlock?.block.number ?? await this.store.getSynchedL2BlockNumber();
663
- if (latestLocalL2BlockNumber < pendingBlockNumber) {
1211
+ const latestLocalCheckpointNumber = lastRetrievedCheckpoint?.checkpoint.number ?? await this.getSynchedCheckpointNumber();
1212
+ if (latestLocalCheckpointNumber < pendingCheckpointNumber) {
664
1213
  // Here we have consumed all logs until the `currentL1Block` we pinned at the beginning of the archiver loop,
665
- // but still havent reached the pending block according to the call to the rollup contract.
666
- // We suspect an L1 reorg that added blocks *behind* us. If that is the case, it must have happened between the
667
- // last L2 block we saw and the current one, so we reset the last synched L1 block number. In the edge case we
668
- // don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
669
- const latestLocalL2Block = lastRetrievedBlock ?? (latestLocalL2BlockNumber > 0 ? await this.store.getPublishedBlocks(latestLocalL2BlockNumber, 1).then(([b])=>b) : undefined);
670
- const targetL1BlockNumber = latestLocalL2Block?.l1.blockNumber ?? maxBigint(currentL1BlockNumber - 64n, 0n);
671
- const latestLocalL2BlockArchive = latestLocalL2Block?.block.archive.root.toString();
672
- this.log.warn(`Failed to reach L2 block ${pendingBlockNumber} at ${currentL1BlockNumber} (latest is ${latestLocalL2BlockNumber}). ` + `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`, {
673
- latestLocalL2BlockNumber,
674
- latestLocalL2BlockArchive,
1214
+ // but still haven't reached the pending checkpoint according to the call to the rollup contract.
1215
+ // We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
1216
+ // the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
1217
+ // we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
1218
+ let latestLocalCheckpointArchive = undefined;
1219
+ let targetL1BlockNumber = maxBigint(currentL1BlockNumber - 64n, 0n);
1220
+ if (lastRetrievedCheckpoint) {
1221
+ latestLocalCheckpointArchive = lastRetrievedCheckpoint.checkpoint.archive.root.toString();
1222
+ targetL1BlockNumber = lastRetrievedCheckpoint.l1.blockNumber;
1223
+ } else if (latestLocalCheckpointNumber > 0) {
1224
+ const checkpoint = await this.store.getRangeOfCheckpoints(latestLocalCheckpointNumber, 1).then(([c])=>c);
1225
+ latestLocalCheckpointArchive = checkpoint.archive.root.toString();
1226
+ targetL1BlockNumber = checkpoint.l1.blockNumber;
1227
+ }
1228
+ this.log.warn(`Failed to reach checkpoint ${pendingCheckpointNumber} at ${currentL1BlockNumber} (latest is ${latestLocalCheckpointNumber}). ` + `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`, {
1229
+ latestLocalCheckpointNumber,
1230
+ latestLocalCheckpointArchive,
675
1231
  blocksSynchedTo,
676
1232
  currentL1BlockNumber,
677
1233
  ...status
678
1234
  });
679
1235
  await this.store.setBlockSynchedL1BlockNumber(targetL1BlockNumber);
680
1236
  } else {
681
- this.log.trace(`No new blocks behind L1 sync point to retrieve.`, {
682
- latestLocalL2BlockNumber,
683
- pendingBlockNumber
1237
+ this.log.trace(`No new checkpoints behind L1 sync point to retrieve.`, {
1238
+ latestLocalCheckpointNumber,
1239
+ pendingCheckpointNumber
684
1240
  });
685
1241
  }
686
1242
  }
687
1243
  /** Resumes the archiver after a stop. */ resume() {
688
- if (!this.runningPromise) {
689
- throw new Error(`Archiver was never started`);
690
- }
691
1244
  if (this.runningPromise.isRunning()) {
692
1245
  this.log.warn(`Archiver already running`);
693
1246
  }
@@ -699,7 +1252,7 @@ import { validateBlockAttestations } from './validation.js';
699
1252
  * @returns A promise signalling completion of the stop process.
700
1253
  */ async stop() {
701
1254
  this.log.debug('Stopping...');
702
- await this.runningPromise?.stop();
1255
+ await this.runningPromise.stop();
703
1256
  this.log.info('Stopped.');
704
1257
  return Promise.resolve();
705
1258
  }
@@ -709,6 +1262,11 @@ import { validateBlockAttestations } from './validation.js';
709
1262
  getL1Constants() {
710
1263
  return Promise.resolve(this.l1constants);
711
1264
  }
1265
+ getGenesisValues() {
1266
+ return Promise.resolve({
1267
+ genesisArchiveRoot: this.l1constants.genesisArchiveRoot
1268
+ });
1269
+ }
712
1270
  getRollupAddress() {
713
1271
  return Promise.resolve(this.l1Addresses.rollupAddress);
714
1272
  }
@@ -716,60 +1274,65 @@ import { validateBlockAttestations } from './validation.js';
716
1274
  return Promise.resolve(this.l1Addresses.registryAddress);
717
1275
  }
718
1276
  getL1BlockNumber() {
719
- const l1BlockNumber = this.l1BlockNumber;
720
- if (!l1BlockNumber) {
721
- throw new Error('L1 block number not yet available. Complete an initial sync first.');
722
- }
723
- return l1BlockNumber;
1277
+ return this.l1BlockNumber;
724
1278
  }
725
1279
  getL1Timestamp() {
726
- const l1Timestamp = this.l1Timestamp;
727
- if (!l1Timestamp) {
728
- throw new Error('L1 timestamp not yet available. Complete an initial sync first.');
729
- }
730
- return Promise.resolve(l1Timestamp);
1280
+ return Promise.resolve(this.l1Timestamp);
731
1281
  }
732
- async getL2SlotNumber() {
733
- return getSlotAtTimestamp(await this.getL1Timestamp(), this.l1constants);
1282
+ getL2SlotNumber() {
1283
+ return Promise.resolve(this.l1Timestamp === undefined ? undefined : getSlotAtTimestamp(this.l1Timestamp, this.l1constants));
734
1284
  }
735
- async getL2EpochNumber() {
736
- return getEpochNumberAtTimestamp(await this.getL1Timestamp(), this.l1constants);
1285
+ getL2EpochNumber() {
1286
+ return Promise.resolve(this.l1Timestamp === undefined ? undefined : getEpochNumberAtTimestamp(this.l1Timestamp, this.l1constants));
737
1287
  }
738
1288
  async getBlocksForEpoch(epochNumber) {
739
1289
  const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
740
1290
  const blocks = [];
741
- // Walk the list of blocks backwards and filter by slots matching the requested epoch.
742
- // We'll typically ask for blocks for a very recent epoch, so we shouldn't need an index here.
743
- let block = await this.getBlock(await this.store.getSynchedL2BlockNumber());
744
- const slot = (b)=>b.header.globalVariables.slotNumber.toBigInt();
745
- while(block && slot(block) >= start){
746
- if (slot(block) <= end) {
747
- blocks.push(block);
1291
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
1292
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
1293
+ let checkpoint = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
1294
+ const slot = (b)=>b.header.slotNumber;
1295
+ while(checkpoint && slot(checkpoint) >= start){
1296
+ if (slot(checkpoint) <= end) {
1297
+ // push the blocks on backwards
1298
+ const endBlock = checkpoint.startBlock + checkpoint.numBlocks - 1;
1299
+ for(let i = endBlock; i >= checkpoint.startBlock; i--){
1300
+ const block = await this.getBlock(BlockNumber(i));
1301
+ if (block) {
1302
+ blocks.push(block);
1303
+ }
1304
+ }
748
1305
  }
749
- block = await this.getBlock(block.number - 1);
1306
+ checkpoint = await this.store.getCheckpointData(CheckpointNumber(checkpoint.checkpointNumber - 1));
750
1307
  }
751
1308
  return blocks.reverse();
752
1309
  }
753
1310
  async getBlockHeadersForEpoch(epochNumber) {
754
1311
  const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
755
1312
  const blocks = [];
756
- // Walk the list of blocks backwards and filter by slots matching the requested epoch.
757
- // We'll typically ask for blocks for a very recent epoch, so we shouldn't need an index here.
758
- let number = await this.store.getSynchedL2BlockNumber();
759
- let header = await this.getBlockHeader(number);
760
- const slot = (b)=>b.globalVariables.slotNumber.toBigInt();
761
- while(header && slot(header) >= start){
762
- if (slot(header) <= end) {
763
- blocks.push(header);
1313
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
1314
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
1315
+ let checkpoint = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
1316
+ const slot = (b)=>b.header.slotNumber;
1317
+ while(checkpoint && slot(checkpoint) >= start){
1318
+ if (slot(checkpoint) <= end) {
1319
+ // push the blocks on backwards
1320
+ const endBlock = checkpoint.startBlock + checkpoint.numBlocks - 1;
1321
+ for(let i = endBlock; i >= checkpoint.startBlock; i--){
1322
+ const block = await this.getBlockHeader(BlockNumber(i));
1323
+ if (block) {
1324
+ blocks.push(block);
1325
+ }
1326
+ }
764
1327
  }
765
- header = await this.getBlockHeader(--number);
1328
+ checkpoint = await this.store.getCheckpointData(CheckpointNumber(checkpoint.checkpointNumber - 1));
766
1329
  }
767
1330
  return blocks.reverse();
768
1331
  }
769
1332
  async isEpochComplete(epochNumber) {
770
1333
  // The epoch is complete if the current L2 block is the last one in the epoch (or later)
771
1334
  const header = await this.getBlockHeader('latest');
772
- const slot = header?.globalVariables.slotNumber.toBigInt();
1335
+ const slot = header ? header.globalVariables.slotNumber : undefined;
773
1336
  const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1constants);
774
1337
  if (slot && slot >= endSlot) {
775
1338
  return true;
@@ -793,24 +1356,55 @@ import { validateBlockAttestations } from './validation.js';
793
1356
  /** Returns whether the archiver has completed an initial sync run successfully. */ isInitialSyncComplete() {
794
1357
  return this.initialSyncComplete;
795
1358
  }
796
- /**
797
- * Gets up to `limit` amount of L2 blocks starting from `from`.
798
- * @param from - Number of the first block to return (inclusive).
799
- * @param limit - The number of blocks to return.
800
- * @param proven - If true, only return blocks that have been proven.
801
- * @returns The requested L2 blocks.
802
- */ getBlocks(from, limit, proven) {
803
- return this.getPublishedBlocks(from, limit, proven).then((blocks)=>blocks.map((b)=>b.block));
1359
+ async getCheckpointHeader(number) {
1360
+ if (number === 'latest') {
1361
+ number = await this.getSynchedCheckpointNumber();
1362
+ }
1363
+ if (number === 0) {
1364
+ return undefined;
1365
+ }
1366
+ const checkpoint = await this.store.getCheckpointData(number);
1367
+ if (!checkpoint) {
1368
+ return undefined;
1369
+ }
1370
+ return checkpoint.header;
1371
+ }
1372
+ getCheckpointNumber() {
1373
+ return this.getSynchedCheckpointNumber();
1374
+ }
1375
+ getSynchedCheckpointNumber() {
1376
+ return this.store.getSynchedCheckpointNumber();
1377
+ }
1378
+ getProvenCheckpointNumber() {
1379
+ return this.store.getProvenCheckpointNumber();
1380
+ }
1381
+ setProvenCheckpointNumber(checkpointNumber) {
1382
+ return this.store.setProvenCheckpointNumber(checkpointNumber);
1383
+ }
1384
+ unwindCheckpoints(from, checkpointsToUnwind) {
1385
+ return this.store.unwindCheckpoints(from, checkpointsToUnwind);
1386
+ }
1387
+ async getLastBlockNumberInCheckpoint(checkpointNumber) {
1388
+ const checkpointData = await this.store.getCheckpointData(checkpointNumber);
1389
+ if (!checkpointData) {
1390
+ return undefined;
1391
+ }
1392
+ return BlockNumber(checkpointData.startBlock + checkpointData.numBlocks - 1);
1393
+ }
1394
+ addCheckpoints(checkpoints, pendingChainValidationStatus) {
1395
+ return this.store.addCheckpoints(checkpoints, pendingChainValidationStatus);
804
1396
  }
805
- /** Equivalent to getBlocks but includes publish data. */ async getPublishedBlocks(from, limit, proven) {
806
- const limitWithProven = proven ? Math.min(limit, Math.max(await this.store.getProvenL2BlockNumber() - from + 1, 0)) : limit;
807
- return limitWithProven === 0 ? [] : await this.store.getPublishedBlocks(from, limitWithProven);
1397
+ getBlockHeaderByHash(blockHash) {
1398
+ return this.store.getBlockHeaderByHash(blockHash);
1399
+ }
1400
+ getBlockHeaderByArchive(archive) {
1401
+ return this.store.getBlockHeaderByArchive(archive);
808
1402
  }
809
1403
  /**
810
1404
  * Gets an l2 block.
811
1405
  * @param number - The block number to return.
812
1406
  * @returns The requested L2 block.
813
- */ async getBlock(number) {
1407
+ */ async getL2BlockNew(number) {
814
1408
  // If the number provided is -ve, then return the latest block.
815
1409
  if (number < 0) {
816
1410
  number = await this.store.getSynchedL2BlockNumber();
@@ -818,8 +1412,8 @@ import { validateBlockAttestations } from './validation.js';
818
1412
  if (number === 0) {
819
1413
  return undefined;
820
1414
  }
821
- const publishedBlock = await this.store.getPublishedBlock(number);
822
- return publishedBlock?.block;
1415
+ const publishedBlock = await this.store.store.getBlock(number);
1416
+ return publishedBlock;
823
1417
  }
824
1418
  async getBlockHeader(number) {
825
1419
  if (number === 'latest') {
@@ -831,27 +1425,29 @@ import { validateBlockAttestations } from './validation.js';
831
1425
  const headers = await this.store.getBlockHeaders(number, 1);
832
1426
  return headers.length === 0 ? undefined : headers[0];
833
1427
  }
1428
+ getCheckpointedBlock(number) {
1429
+ return this.store.getCheckpointedBlock(number);
1430
+ }
1431
+ getCheckpointedBlockByHash(blockHash) {
1432
+ return this.store.getCheckpointedBlockByHash(blockHash);
1433
+ }
1434
+ getProvenBlockNumber() {
1435
+ return this.store.getProvenBlockNumber();
1436
+ }
1437
+ getCheckpointedBlockByArchive(archive) {
1438
+ return this.store.getCheckpointedBlockByArchive(archive);
1439
+ }
834
1440
  getTxEffect(txHash) {
835
1441
  return this.store.getTxEffect(txHash);
836
1442
  }
837
1443
  getSettledTxReceipt(txHash) {
838
1444
  return this.store.getSettledTxReceipt(txHash);
839
1445
  }
840
- /**
841
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
842
- * @param from - The block number from which to begin retrieving logs.
843
- * @param limit - The maximum number of blocks to retrieve logs from.
844
- * @returns An array of private logs from the specified range of blocks.
845
- */ getPrivateLogs(from, limit) {
846
- return this.store.getPrivateLogs(from, limit);
1446
+ getPrivateLogsByTags(tags) {
1447
+ return this.store.getPrivateLogsByTags(tags);
847
1448
  }
848
- /**
849
- * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
850
- * @param tags - The tags to filter the logs by.
851
- * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
852
- * that tag.
853
- */ getLogsByTags(tags) {
854
- return this.store.getLogsByTags(tags);
1449
+ getPublicLogsByTagsFromContract(contractAddress, tags) {
1450
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags);
855
1451
  }
856
1452
  /**
857
1453
  * Gets public logs based on the provided filter.
@@ -869,15 +1465,10 @@ import { validateBlockAttestations } from './validation.js';
869
1465
  }
870
1466
  /**
871
1467
  * Gets the number of the latest L2 block processed by the block source implementation.
1468
+ * This includes both checkpointed and uncheckpointed blocks.
872
1469
  * @returns The number of the latest L2 block processed by the block source implementation.
873
1470
  */ getBlockNumber() {
874
- return this.store.getSynchedL2BlockNumber();
875
- }
876
- getProvenBlockNumber() {
877
- return this.store.getProvenL2BlockNumber();
878
- }
879
- /** Forcefully updates the last proven block number. Use for testing. */ setProvenBlockNumber(blockNumber) {
880
- return this.store.setProvenL2BlockNumber(blockNumber);
1471
+ return this.store.getLatestBlockNumber();
881
1472
  }
882
1473
  getContractClass(id) {
883
1474
  return this.store.getContractClass(id);
@@ -897,11 +1488,11 @@ import { validateBlockAttestations } from './validation.js';
897
1488
  return this.store.getContractInstance(address, timestamp);
898
1489
  }
899
1490
  /**
900
- * Gets L1 to L2 message (to be) included in a given block.
901
- * @param blockNumber - L2 block number to get messages for.
1491
+ * Gets L1 to L2 message (to be) included in a given checkpoint.
1492
+ * @param checkpointNumber - Checkpoint number to get messages for.
902
1493
  * @returns The L1 to L2 messages/leaves of the messages subtree (throws if not found).
903
- */ getL1ToL2Messages(blockNumber) {
904
- return this.store.getL1ToL2Messages(blockNumber);
1494
+ */ getL1ToL2Messages(checkpointNumber) {
1495
+ return this.store.getL1ToL2Messages(checkpointNumber);
905
1496
  }
906
1497
  /**
907
1498
  * Gets the L1 to L2 message index in the L1 to L2 message tree.
@@ -919,11 +1510,13 @@ import { validateBlockAttestations } from './validation.js';
919
1510
  getDebugFunctionName(address, selector) {
920
1511
  return this.store.getDebugFunctionName(address, selector);
921
1512
  }
922
- getPendingChainValidationStatus() {
923
- return Promise.resolve(this.pendingChainValidationStatus);
1513
+ async getPendingChainValidationStatus() {
1514
+ return await this.store.getPendingChainValidationStatus() ?? {
1515
+ valid: true
1516
+ };
924
1517
  }
925
1518
  isPendingChainInvalid() {
926
- return Promise.resolve(this.pendingChainValidationStatus.valid === false);
1519
+ return this.getPendingChainValidationStatus().then((status)=>!status.valid);
927
1520
  }
928
1521
  async getL2Tips() {
929
1522
  const [latestBlockNumber, provenBlockNumber] = await Promise.all([
@@ -933,7 +1526,7 @@ import { validateBlockAttestations } from './validation.js';
933
1526
  // TODO(#13569): Compute proper finalized block number based on L1 finalized block.
934
1527
  // We just force it 2 epochs worth of proven data for now.
935
1528
  // NOTE: update end-to-end/src/e2e_epochs/epochs_empty_blocks.test.ts as that uses finalized blocks in computations
936
- const finalizedBlockNumber = Math.max(provenBlockNumber - this.l1constants.epochDuration * 2, 0);
1529
+ const finalizedBlockNumber = BlockNumber(Math.max(provenBlockNumber - this.l1constants.epochDuration * 2, 0));
937
1530
  const [latestBlockHeader, provenBlockHeader, finalizedBlockHeader] = await Promise.all([
938
1531
  latestBlockNumber > 0 ? this.getBlockHeader(latestBlockNumber) : undefined,
939
1532
  provenBlockNumber > 0 ? this.getBlockHeader(provenBlockNumber) : undefined,
@@ -948,43 +1541,44 @@ import { validateBlockAttestations } from './validation.js';
948
1541
  if (finalizedBlockNumber > 0 && !finalizedBlockHeader) {
949
1542
  throw new Error(`Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`);
950
1543
  }
951
- const latestBlockHeaderHash = await latestBlockHeader?.hash();
952
- const provenBlockHeaderHash = await provenBlockHeader?.hash();
953
- const finalizedBlockHeaderHash = await finalizedBlockHeader?.hash();
1544
+ const latestBlockHeaderHash = await latestBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1545
+ const provenBlockHeaderHash = await provenBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1546
+ const finalizedBlockHeaderHash = await finalizedBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
954
1547
  return {
955
1548
  latest: {
956
1549
  number: latestBlockNumber,
957
- hash: latestBlockHeaderHash?.toString()
1550
+ hash: latestBlockHeaderHash.toString()
958
1551
  },
959
1552
  proven: {
960
1553
  number: provenBlockNumber,
961
- hash: provenBlockHeaderHash?.toString()
1554
+ hash: provenBlockHeaderHash.toString()
962
1555
  },
963
1556
  finalized: {
964
1557
  number: finalizedBlockNumber,
965
- hash: finalizedBlockHeaderHash?.toString()
1558
+ hash: finalizedBlockHeaderHash.toString()
966
1559
  }
967
1560
  };
968
1561
  }
969
1562
  async rollbackTo(targetL2BlockNumber) {
1563
+ // TODO(pw/mbps): This still assumes 1 block per checkpoint
970
1564
  const currentBlocks = await this.getL2Tips();
971
1565
  const currentL2Block = currentBlocks.latest.number;
972
1566
  const currentProvenBlock = currentBlocks.proven.number;
973
- // const currentFinalizedBlock = currentBlocks.finalized.number;
974
1567
  if (targetL2BlockNumber >= currentL2Block) {
975
1568
  throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
976
1569
  }
977
1570
  const blocksToUnwind = currentL2Block - targetL2BlockNumber;
978
- const targetL2Block = await this.store.getPublishedBlock(targetL2BlockNumber);
1571
+ const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
979
1572
  if (!targetL2Block) {
980
1573
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
981
1574
  }
982
1575
  const targetL1BlockNumber = targetL2Block.l1.blockNumber;
1576
+ const targetCheckpointNumber = CheckpointNumber.fromBlockNumber(targetL2BlockNumber);
983
1577
  const targetL1BlockHash = await this.getL1BlockHash(targetL1BlockNumber);
984
- this.log.info(`Unwinding ${blocksToUnwind} blocks from L2 block ${currentL2Block}`);
985
- await this.store.unwindBlocks(currentL2Block, blocksToUnwind);
986
- this.log.info(`Unwinding L1 to L2 messages to ${targetL2BlockNumber}`);
987
- await this.store.rollbackL1ToL2MessagesToL2Block(targetL2BlockNumber);
1578
+ this.log.info(`Unwinding ${blocksToUnwind} checkpoints from L2 block ${currentL2Block}`);
1579
+ await this.store.unwindCheckpoints(CheckpointNumber(currentL2Block), blocksToUnwind);
1580
+ this.log.info(`Unwinding L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
1581
+ await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
988
1582
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
989
1583
  await this.store.setBlockSynchedL1BlockNumber(targetL1BlockNumber);
990
1584
  await this.store.setMessageSynchedL1Block({
@@ -993,7 +1587,7 @@ import { validateBlockAttestations } from './validation.js';
993
1587
  });
994
1588
  if (targetL2BlockNumber < currentProvenBlock) {
995
1589
  this.log.info(`Clearing proven L2 block number`);
996
- await this.store.setProvenL2BlockNumber(0);
1590
+ await this.store.setProvenCheckpointNumber(CheckpointNumber.ZERO);
997
1591
  }
998
1592
  // TODO(palla/reorg): Set the finalized block when we add support for it.
999
1593
  // if (targetL2BlockNumber < currentFinalizedBlock) {
@@ -1001,12 +1595,104 @@ import { validateBlockAttestations } from './validation.js';
1001
1595
  // await this.store.setFinalizedL2BlockNumber(0);
1002
1596
  // }
1003
1597
  }
1598
+ async getPublishedCheckpoints(checkpointNumber, limit) {
1599
+ const checkpoints = await this.store.getRangeOfCheckpoints(checkpointNumber, limit);
1600
+ const blocks = (await Promise.all(checkpoints.map((ch)=>this.store.getBlocksForCheckpoint(ch.checkpointNumber)))).filter(isDefined);
1601
+ const fullCheckpoints = [];
1602
+ for(let i = 0; i < checkpoints.length; i++){
1603
+ const blocksForCheckpoint = blocks[i];
1604
+ const checkpoint = checkpoints[i];
1605
+ const fullCheckpoint = new Checkpoint(checkpoint.archive, checkpoint.header, blocksForCheckpoint, checkpoint.checkpointNumber);
1606
+ const publishedCheckpoint = new PublishedCheckpoint(fullCheckpoint, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
1607
+ fullCheckpoints.push(publishedCheckpoint);
1608
+ }
1609
+ return fullCheckpoints;
1610
+ }
1611
+ async getCheckpointsForEpoch(epochNumber) {
1612
+ const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
1613
+ const checkpoints = [];
1614
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
1615
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
1616
+ let checkpointData = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
1617
+ const slot = (b)=>b.header.slotNumber;
1618
+ while(checkpointData && slot(checkpointData) >= start){
1619
+ if (slot(checkpointData) <= end) {
1620
+ // push the checkpoints on backwards
1621
+ const [checkpoint] = await this.getPublishedCheckpoints(checkpointData.checkpointNumber, 1);
1622
+ checkpoints.push(checkpoint.checkpoint);
1623
+ }
1624
+ checkpointData = await this.store.getCheckpointData(CheckpointNumber(checkpointData.checkpointNumber - 1));
1625
+ }
1626
+ return checkpoints.reverse();
1627
+ }
1628
+ /* Legacy APIs */ async getPublishedBlockByHash(blockHash) {
1629
+ const checkpointedBlock = await this.store.getCheckpointedBlockByHash(blockHash);
1630
+ return this.buildOldBlockFromCheckpointedBlock(checkpointedBlock);
1631
+ }
1632
+ async getPublishedBlockByArchive(archive) {
1633
+ const checkpointedBlock = await this.store.getCheckpointedBlockByArchive(archive);
1634
+ return this.buildOldBlockFromCheckpointedBlock(checkpointedBlock);
1635
+ }
1636
+ /**
1637
+ * Gets up to `limit` amount of L2 blocks starting from `from`.
1638
+ * @param from - Number of the first block to return (inclusive).
1639
+ * @param limit - The number of blocks to return.
1640
+ * @param proven - If true, only return blocks that have been proven.
1641
+ * @returns The requested L2 blocks.
1642
+ */ async getBlocks(from, limit, proven) {
1643
+ const publishedBlocks = await this.getPublishedBlocks(from, limit, proven);
1644
+ return publishedBlocks.map((x)=>x.block);
1645
+ }
1646
+ async getPublishedBlocks(from, limit, proven) {
1647
+ const checkpoints = await this.store.getRangeOfCheckpoints(CheckpointNumber(from), limit);
1648
+ const provenCheckpointNumber = await this.getProvenCheckpointNumber();
1649
+ const blocks = (await Promise.all(checkpoints.map((ch)=>this.store.getBlocksForCheckpoint(ch.checkpointNumber)))).filter(isDefined);
1650
+ const olbBlocks = [];
1651
+ for(let i = 0; i < checkpoints.length; i++){
1652
+ const blockForCheckpoint = blocks[i][0];
1653
+ const checkpoint = checkpoints[i];
1654
+ if (checkpoint.checkpointNumber > provenCheckpointNumber && proven === true) {
1655
+ continue;
1656
+ }
1657
+ const oldCheckpoint = new Checkpoint(blockForCheckpoint.archive, checkpoint.header, [
1658
+ blockForCheckpoint
1659
+ ], checkpoint.checkpointNumber);
1660
+ const oldBlock = L2Block.fromCheckpoint(oldCheckpoint);
1661
+ const publishedBlock = new PublishedL2Block(oldBlock, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
1662
+ olbBlocks.push(publishedBlock);
1663
+ }
1664
+ return olbBlocks;
1665
+ }
1666
+ async buildOldBlockFromCheckpointedBlock(checkpointedBlock) {
1667
+ if (!checkpointedBlock) {
1668
+ return undefined;
1669
+ }
1670
+ const checkpoint = await this.store.getCheckpointData(checkpointedBlock.checkpointNumber);
1671
+ if (!checkpoint) {
1672
+ return checkpoint;
1673
+ }
1674
+ const fullCheckpoint = new Checkpoint(checkpointedBlock?.block.archive, checkpoint?.header, [
1675
+ checkpointedBlock.block
1676
+ ], checkpoint.checkpointNumber);
1677
+ const oldBlock = L2Block.fromCheckpoint(fullCheckpoint);
1678
+ const published = new PublishedL2Block(oldBlock, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
1679
+ return published;
1680
+ }
1681
+ async getBlock(number) {
1682
+ // If the number provided is -ve, then return the latest block.
1683
+ if (number < 0) {
1684
+ number = await this.store.getSynchedL2BlockNumber();
1685
+ }
1686
+ if (number === 0) {
1687
+ return undefined;
1688
+ }
1689
+ const publishedBlocks = await this.getPublishedBlocks(number, 1);
1690
+ if (publishedBlocks.length === 0) {
1691
+ return undefined;
1692
+ }
1693
+ return publishedBlocks[0].block;
1694
+ }
1004
1695
  }
1005
- _ts_decorate([
1006
- trackSpan('Archiver.sync', (initialRun)=>({
1007
- [Attributes.INITIAL_SYNC]: initialRun
1008
- }))
1009
- ], Archiver.prototype, "sync", null);
1010
1696
  var Operation = /*#__PURE__*/ function(Operation) {
1011
1697
  Operation[Operation["Store"] = 0] = "Store";
1012
1698
  Operation[Operation["Delete"] = 1] = "Delete";
@@ -1124,67 +1810,139 @@ var Operation = /*#__PURE__*/ function(Operation) {
1124
1810
  }
1125
1811
  return true;
1126
1812
  }
1127
- addBlocks(blocks) {
1813
+ async addBlockDataToDB(block) {
1814
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1815
+ // ContractInstancePublished event logs are broadcast in privateLogs.
1816
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1817
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1818
+ return (await Promise.all([
1819
+ this.#updatePublishedContractClasses(contractClassLogs, block.number, 0),
1820
+ this.#updateDeployedContractInstances(privateLogs, block.number, 0),
1821
+ this.#updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, 0),
1822
+ this.#storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
1823
+ ])).every(Boolean);
1824
+ }
1825
+ addBlocks(blocks, pendingChainValidationStatus) {
1128
1826
  // Add the blocks to the store. Store will throw if the blocks are not in order, there are gaps,
1129
1827
  // or if the previous block is not in the store.
1130
1828
  return this.store.transactionAsync(async ()=>{
1131
1829
  await this.store.addBlocks(blocks);
1132
1830
  const opResults = await Promise.all([
1133
- this.store.addLogs(blocks.map((block)=>block.block)),
1831
+ // Update the pending chain validation status if provided
1832
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
1833
+ // Add any logs emitted during the retrieved blocks
1834
+ this.store.addLogs(blocks),
1134
1835
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1135
- ...blocks.map(async (block)=>{
1136
- const contractClassLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1137
- // ContractInstancePublished event logs are broadcast in privateLogs.
1138
- const privateLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1139
- const publicLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1140
- return (await Promise.all([
1141
- this.#updatePublishedContractClasses(contractClassLogs, block.block.number, 0),
1142
- this.#updateDeployedContractInstances(privateLogs, block.block.number, 0),
1143
- this.#updateUpdatedContractInstances(publicLogs, block.block.header.globalVariables.timestamp, 0),
1144
- this.#storeBroadcastedIndividualFunctions(contractClassLogs, block.block.number)
1145
- ])).every(Boolean);
1836
+ ...blocks.map((block)=>{
1837
+ return this.addBlockDataToDB(block);
1146
1838
  })
1147
1839
  ]);
1148
1840
  return opResults.every(Boolean);
1149
1841
  });
1150
1842
  }
1151
- async unwindBlocks(from, blocksToUnwind) {
1152
- const last = await this.getSynchedL2BlockNumber();
1843
+ addCheckpoints(checkpoints, pendingChainValidationStatus) {
1844
+ // Add the blocks to the store. Store will throw if the blocks are not in order, there are gaps,
1845
+ // or if the previous block is not in the store.
1846
+ return this.store.transactionAsync(async ()=>{
1847
+ await this.store.addCheckpoints(checkpoints);
1848
+ const allBlocks = checkpoints.flatMap((ch)=>ch.checkpoint.blocks);
1849
+ const opResults = await Promise.all([
1850
+ // Update the pending chain validation status if provided
1851
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
1852
+ // Add any logs emitted during the retrieved blocks
1853
+ this.store.addLogs(allBlocks),
1854
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1855
+ ...allBlocks.map((block)=>{
1856
+ return this.addBlockDataToDB(block);
1857
+ })
1858
+ ]);
1859
+ return opResults.every(Boolean);
1860
+ });
1861
+ }
1862
+ async unwindCheckpoints(from, checkpointsToUnwind) {
1863
+ if (checkpointsToUnwind <= 0) {
1864
+ throw new Error(`Cannot unwind ${checkpointsToUnwind} blocks`);
1865
+ }
1866
+ const last = await this.getSynchedCheckpointNumber();
1153
1867
  if (from != last) {
1154
- throw new Error(`Cannot unwind blocks from block ${from} when the last block is ${last}`);
1868
+ throw new Error(`Cannot unwind checkpoints from checkpoint ${from} when the last checkpoint is ${last}`);
1155
1869
  }
1156
- if (blocksToUnwind <= 0) {
1157
- throw new Error(`Cannot unwind ${blocksToUnwind} blocks`);
1870
+ const blocks = [];
1871
+ const lastCheckpointNumber = from + checkpointsToUnwind - 1;
1872
+ for(let checkpointNumber = from; checkpointNumber <= lastCheckpointNumber; checkpointNumber++){
1873
+ const blocksForCheckpoint = await this.store.getBlocksForCheckpoint(checkpointNumber);
1874
+ if (!blocksForCheckpoint) {
1875
+ continue;
1876
+ }
1877
+ blocks.push(...blocksForCheckpoint);
1158
1878
  }
1159
- // from - blocksToUnwind = the new head, so + 1 for what we need to remove
1160
- const blocks = await this.getPublishedBlocks(from - blocksToUnwind + 1, blocksToUnwind);
1161
1879
  const opResults = await Promise.all([
1880
+ // Prune rolls back to the last proven block, which is by definition valid
1881
+ this.store.setPendingChainValidationStatus({
1882
+ valid: true
1883
+ }),
1162
1884
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1163
1885
  ...blocks.map(async (block)=>{
1164
- const contractClassLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1886
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1165
1887
  // ContractInstancePublished event logs are broadcast in privateLogs.
1166
- const privateLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1167
- const publicLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1888
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1889
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1168
1890
  return (await Promise.all([
1169
- this.#updatePublishedContractClasses(contractClassLogs, block.block.number, 1),
1170
- this.#updateDeployedContractInstances(privateLogs, block.block.number, 1),
1171
- this.#updateUpdatedContractInstances(publicLogs, block.block.header.globalVariables.timestamp, 1)
1891
+ this.#updatePublishedContractClasses(contractClassLogs, block.number, 1),
1892
+ this.#updateDeployedContractInstances(privateLogs, block.number, 1),
1893
+ this.#updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, 1)
1172
1894
  ])).every(Boolean);
1173
1895
  }),
1174
- this.store.deleteLogs(blocks.map((b)=>b.block)),
1175
- this.store.unwindBlocks(from, blocksToUnwind)
1896
+ this.store.deleteLogs(blocks),
1897
+ this.store.unwindCheckpoints(from, checkpointsToUnwind)
1176
1898
  ]);
1177
1899
  return opResults.every(Boolean);
1178
1900
  }
1179
- getPublishedBlocks(from, limit) {
1180
- return this.store.getPublishedBlocks(from, limit);
1901
+ getCheckpointData(checkpointNumber) {
1902
+ return this.store.getCheckpointData(checkpointNumber);
1903
+ }
1904
+ getRangeOfCheckpoints(from, limit) {
1905
+ return this.store.getRangeOfCheckpoints(from, limit);
1906
+ }
1907
+ getCheckpointedL2BlockNumber() {
1908
+ return this.store.getCheckpointedL2BlockNumber();
1181
1909
  }
1182
- getPublishedBlock(number) {
1183
- return this.store.getPublishedBlock(number);
1910
+ getSynchedCheckpointNumber() {
1911
+ return this.store.getSynchedCheckpointNumber();
1912
+ }
1913
+ setCheckpointSynchedL1BlockNumber(l1BlockNumber) {
1914
+ return this.store.setCheckpointSynchedL1BlockNumber(l1BlockNumber);
1915
+ }
1916
+ getCheckpointedBlock(number) {
1917
+ return this.store.getCheckpointedBlock(number);
1918
+ }
1919
+ getCheckpointedBlockByHash(blockHash) {
1920
+ return this.store.getCheckpointedBlockByHash(blockHash);
1921
+ }
1922
+ getCheckpointedBlockByArchive(archive) {
1923
+ return this.store.getCheckpointedBlockByArchive(archive);
1184
1924
  }
1185
1925
  getBlockHeaders(from, limit) {
1186
1926
  return this.store.getBlockHeaders(from, limit);
1187
1927
  }
1928
+ getBlockHeaderByHash(blockHash) {
1929
+ return this.store.getBlockHeaderByHash(blockHash);
1930
+ }
1931
+ getBlockHeaderByArchive(archive) {
1932
+ return this.store.getBlockHeaderByArchive(archive);
1933
+ }
1934
+ getBlockByHash(blockHash) {
1935
+ return this.store.getBlockByHash(blockHash);
1936
+ }
1937
+ getBlockByArchive(archive) {
1938
+ return this.store.getBlockByArchive(archive);
1939
+ }
1940
+ getLatestBlockNumber() {
1941
+ return this.store.getLatestBlockNumber();
1942
+ }
1943
+ getBlocksForCheckpoint(checkpointNumber) {
1944
+ return this.store.getBlocksForCheckpoint(checkpointNumber);
1945
+ }
1188
1946
  getTxEffect(txHash) {
1189
1947
  return this.store.getTxEffect(txHash);
1190
1948
  }
@@ -1194,17 +1952,17 @@ var Operation = /*#__PURE__*/ function(Operation) {
1194
1952
  addL1ToL2Messages(messages) {
1195
1953
  return this.store.addL1ToL2Messages(messages);
1196
1954
  }
1197
- getL1ToL2Messages(blockNumber) {
1198
- return this.store.getL1ToL2Messages(blockNumber);
1955
+ getL1ToL2Messages(checkpointNumber) {
1956
+ return this.store.getL1ToL2Messages(checkpointNumber);
1199
1957
  }
1200
1958
  getL1ToL2MessageIndex(l1ToL2Message) {
1201
1959
  return this.store.getL1ToL2MessageIndex(l1ToL2Message);
1202
1960
  }
1203
- getPrivateLogs(from, limit) {
1204
- return this.store.getPrivateLogs(from, limit);
1961
+ getPrivateLogsByTags(tags) {
1962
+ return this.store.getPrivateLogsByTags(tags);
1205
1963
  }
1206
- getLogsByTags(tags, logsPerTag) {
1207
- return this.store.getLogsByTags(tags, logsPerTag);
1964
+ getPublicLogsByTagsFromContract(contractAddress, tags) {
1965
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags);
1208
1966
  }
1209
1967
  getPublicLogs(filter) {
1210
1968
  return this.store.getPublicLogs(filter);
@@ -1213,16 +1971,19 @@ var Operation = /*#__PURE__*/ function(Operation) {
1213
1971
  return this.store.getContractClassLogs(filter);
1214
1972
  }
1215
1973
  getSynchedL2BlockNumber() {
1216
- return this.store.getSynchedL2BlockNumber();
1974
+ return this.store.getCheckpointedL2BlockNumber();
1217
1975
  }
1218
- getProvenL2BlockNumber() {
1219
- return this.store.getProvenL2BlockNumber();
1976
+ getProvenCheckpointNumber() {
1977
+ return this.store.getProvenCheckpointNumber();
1978
+ }
1979
+ getProvenBlockNumber() {
1980
+ return this.store.getProvenBlockNumber();
1220
1981
  }
1221
- setProvenL2BlockNumber(l2BlockNumber) {
1222
- return this.store.setProvenL2BlockNumber(l2BlockNumber);
1982
+ setProvenCheckpointNumber(checkpointNumber) {
1983
+ return this.store.setProvenCheckpointNumber(checkpointNumber);
1223
1984
  }
1224
1985
  setBlockSynchedL1BlockNumber(l1BlockNumber) {
1225
- return this.store.setBlockSynchedL1BlockNumber(l1BlockNumber);
1986
+ return this.store.setCheckpointSynchedL1BlockNumber(l1BlockNumber);
1226
1987
  }
1227
1988
  setMessageSynchedL1Block(l1Block) {
1228
1989
  return this.store.setMessageSynchedL1Block(l1Block);
@@ -1254,8 +2015,8 @@ var Operation = /*#__PURE__*/ function(Operation) {
1254
2015
  estimateSize() {
1255
2016
  return this.store.estimateSize();
1256
2017
  }
1257
- rollbackL1ToL2MessagesToL2Block(targetBlockNumber) {
1258
- return this.store.rollbackL1ToL2MessagesToL2Block(targetBlockNumber);
2018
+ rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber) {
2019
+ return this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
1259
2020
  }
1260
2021
  iterateL1ToL2Messages(range = {}) {
1261
2022
  return this.store.iterateL1ToL2Messages(range);
@@ -1266,4 +2027,11 @@ var Operation = /*#__PURE__*/ function(Operation) {
1266
2027
  getLastL1ToL2Message() {
1267
2028
  return this.store.getLastL1ToL2Message();
1268
2029
  }
2030
+ getPendingChainValidationStatus() {
2031
+ return this.store.getPendingChainValidationStatus();
2032
+ }
2033
+ setPendingChainValidationStatus(status) {
2034
+ this.#log.debug(`Setting pending chain validation status to valid ${status?.valid}`, status);
2035
+ return this.store.setPendingChainValidationStatus(status);
2036
+ }
1269
2037
  }