@aztec/archiver 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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 (218) hide show
  1. package/README.md +162 -22
  2. package/dest/archiver.d.ts +147 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +788 -0
  5. package/dest/config.d.ts +32 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +83 -0
  8. package/dest/errors.d.ts +92 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +136 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +100 -15
  14. package/dest/index.d.ts +12 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +136 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +408 -0
  26. package/dest/l1/data_retrieval.d.ts +97 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +86 -165
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_historical_logs.d.ts +23 -0
  42. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  43. package/dest/l1/validate_historical_logs.js +108 -0
  44. package/dest/l1/validate_trace.d.ts +32 -0
  45. package/dest/l1/validate_trace.d.ts.map +1 -0
  46. package/dest/l1/validate_trace.js +154 -0
  47. package/dest/modules/data_source_base.d.ts +95 -0
  48. package/dest/modules/data_source_base.d.ts.map +1 -0
  49. package/dest/modules/data_source_base.js +234 -0
  50. package/dest/modules/data_store_updater.d.ts +93 -0
  51. package/dest/modules/data_store_updater.d.ts.map +1 -0
  52. package/dest/modules/data_store_updater.js +345 -0
  53. package/dest/modules/instrumentation.d.ts +55 -0
  54. package/dest/modules/instrumentation.d.ts.map +1 -0
  55. package/dest/modules/instrumentation.js +143 -0
  56. package/dest/modules/l1_synchronizer.d.ts +77 -0
  57. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  58. package/dest/modules/l1_synchronizer.js +1265 -0
  59. package/dest/modules/validation.d.ts +18 -0
  60. package/dest/modules/validation.d.ts.map +1 -0
  61. package/dest/{archiver → modules}/validation.js +13 -7
  62. package/dest/store/block_store.d.ts +262 -0
  63. package/dest/store/block_store.d.ts.map +1 -0
  64. package/dest/store/block_store.js +1048 -0
  65. package/dest/store/contract_class_store.d.ts +17 -0
  66. package/dest/store/contract_class_store.d.ts.map +1 -0
  67. package/dest/store/contract_class_store.js +64 -0
  68. package/dest/store/contract_instance_store.d.ts +24 -0
  69. package/dest/store/contract_instance_store.d.ts.map +1 -0
  70. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +7 -3
  71. package/dest/store/kv_archiver_store.d.ts +401 -0
  72. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  73. package/dest/store/kv_archiver_store.js +525 -0
  74. package/dest/store/l2_tips_cache.d.ts +20 -0
  75. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  76. package/dest/store/l2_tips_cache.js +109 -0
  77. package/dest/store/log_store.d.ts +57 -0
  78. package/dest/store/log_store.d.ts.map +1 -0
  79. package/dest/store/log_store.js +531 -0
  80. package/dest/store/message_store.d.ts +44 -0
  81. package/dest/store/message_store.d.ts.map +1 -0
  82. package/dest/{archiver/kv_archiver_store → store}/message_store.js +36 -23
  83. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  84. package/dest/structs/data_retrieval.d.ts.map +1 -0
  85. package/dest/structs/inbox_message.d.ts +15 -0
  86. package/dest/structs/inbox_message.d.ts.map +1 -0
  87. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  88. package/dest/structs/published.d.ts +2 -0
  89. package/dest/structs/published.d.ts.map +1 -0
  90. package/dest/test/fake_l1_state.d.ts +214 -0
  91. package/dest/test/fake_l1_state.d.ts.map +1 -0
  92. package/dest/test/fake_l1_state.js +517 -0
  93. package/dest/test/index.d.ts +2 -1
  94. package/dest/test/index.d.ts.map +1 -1
  95. package/dest/test/index.js +4 -1
  96. package/dest/test/mock_archiver.d.ts +16 -8
  97. package/dest/test/mock_archiver.d.ts.map +1 -1
  98. package/dest/test/mock_archiver.js +19 -14
  99. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  100. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  101. package/dest/test/mock_l1_to_l2_message_source.js +23 -12
  102. package/dest/test/mock_l2_block_source.d.ts +68 -20
  103. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  104. package/dest/test/mock_l2_block_source.js +298 -85
  105. package/dest/test/mock_structs.d.ts +83 -4
  106. package/dest/test/mock_structs.d.ts.map +1 -1
  107. package/dest/test/mock_structs.js +157 -11
  108. package/dest/test/noop_l1_archiver.d.ts +26 -0
  109. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  110. package/dest/test/noop_l1_archiver.js +74 -0
  111. package/package.json +20 -20
  112. package/src/archiver.ts +566 -0
  113. package/src/{archiver/config.ts → config.ts} +51 -14
  114. package/src/errors.ts +213 -0
  115. package/src/factory.ts +155 -17
  116. package/src/index.ts +12 -3
  117. package/src/interfaces.ts +9 -0
  118. package/src/l1/README.md +55 -0
  119. package/src/l1/bin/retrieve-calldata.ts +194 -0
  120. package/src/l1/calldata_retriever.ts +523 -0
  121. package/src/{archiver → l1}/data_retrieval.ts +155 -247
  122. package/src/l1/debug_tx.ts +99 -0
  123. package/src/l1/spire_proposer.ts +152 -0
  124. package/src/l1/trace_tx.ts +128 -0
  125. package/src/l1/types.ts +13 -0
  126. package/src/l1/validate_historical_logs.ts +140 -0
  127. package/src/l1/validate_trace.ts +229 -0
  128. package/src/modules/data_source_base.ts +364 -0
  129. package/src/modules/data_store_updater.ts +465 -0
  130. package/src/modules/instrumentation.ts +204 -0
  131. package/src/modules/l1_synchronizer.ts +1126 -0
  132. package/src/{archiver → modules}/validation.ts +21 -15
  133. package/src/store/block_store.ts +1361 -0
  134. package/src/store/contract_class_store.ts +82 -0
  135. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +10 -7
  136. package/src/store/kv_archiver_store.ts +765 -0
  137. package/src/store/l2_tips_cache.ts +134 -0
  138. package/src/store/log_store.ts +733 -0
  139. package/src/{archiver/kv_archiver_store → store}/message_store.ts +48 -28
  140. package/src/{archiver/structs → structs}/inbox_message.ts +7 -7
  141. package/src/{archiver/structs → structs}/published.ts +0 -1
  142. package/src/test/fake_l1_state.ts +770 -0
  143. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  144. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  145. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  146. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  147. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  148. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  149. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  150. package/src/test/index.ts +4 -0
  151. package/src/test/mock_archiver.ts +23 -16
  152. package/src/test/mock_l1_to_l2_message_source.ts +19 -11
  153. package/src/test/mock_l2_block_source.ts +367 -93
  154. package/src/test/mock_structs.ts +289 -13
  155. package/src/test/noop_l1_archiver.ts +117 -0
  156. package/dest/archiver/archiver.d.ts +0 -287
  157. package/dest/archiver/archiver.d.ts.map +0 -1
  158. package/dest/archiver/archiver.js +0 -1408
  159. package/dest/archiver/archiver_store.d.ts +0 -255
  160. package/dest/archiver/archiver_store.d.ts.map +0 -1
  161. package/dest/archiver/archiver_store.js +0 -4
  162. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  163. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  164. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  165. package/dest/archiver/config.d.ts +0 -21
  166. package/dest/archiver/config.d.ts.map +0 -1
  167. package/dest/archiver/config.js +0 -55
  168. package/dest/archiver/data_retrieval.d.ts +0 -79
  169. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  170. package/dest/archiver/errors.d.ts +0 -12
  171. package/dest/archiver/errors.d.ts.map +0 -1
  172. package/dest/archiver/errors.js +0 -17
  173. package/dest/archiver/index.d.ts +0 -7
  174. package/dest/archiver/index.d.ts.map +0 -1
  175. package/dest/archiver/index.js +0 -4
  176. package/dest/archiver/instrumentation.d.ts +0 -35
  177. package/dest/archiver/instrumentation.d.ts.map +0 -1
  178. package/dest/archiver/instrumentation.js +0 -140
  179. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  180. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  181. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  182. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  183. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  184. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  185. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  186. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  187. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  188. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  189. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  190. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  191. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  192. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  193. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  194. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  195. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  196. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  197. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  198. package/dest/archiver/structs/published.d.ts +0 -3
  199. package/dest/archiver/structs/published.d.ts.map +0 -1
  200. package/dest/archiver/validation.d.ts +0 -17
  201. package/dest/archiver/validation.d.ts.map +0 -1
  202. package/dest/rpc/index.d.ts +0 -9
  203. package/dest/rpc/index.d.ts.map +0 -1
  204. package/dest/rpc/index.js +0 -15
  205. package/src/archiver/archiver.ts +0 -1858
  206. package/src/archiver/archiver_store.ts +0 -305
  207. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  208. package/src/archiver/errors.ts +0 -26
  209. package/src/archiver/index.ts +0 -6
  210. package/src/archiver/instrumentation.ts +0 -187
  211. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  212. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  213. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  214. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  215. package/src/rpc/index.ts +0 -16
  216. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  217. /package/dest/{archiver/structs → structs}/published.js +0 -0
  218. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,1265 @@
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
+ };
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, _initProto;
374
+ import { getFinalizedL1Block } from '@aztec/ethereum/queries';
375
+ import { asyncPool } from '@aztec/foundation/async-pool';
376
+ import { maxBigint } from '@aztec/foundation/bigint';
377
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
378
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
379
+ import { partition, pick } from '@aztec/foundation/collection';
380
+ import { EthAddress } from '@aztec/foundation/eth-address';
381
+ import { createLogger } from '@aztec/foundation/log';
382
+ import { retryTimes } from '@aztec/foundation/retry';
383
+ import { count } from '@aztec/foundation/string';
384
+ import { Timer, elapsed } from '@aztec/foundation/timer';
385
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
386
+ import { L2BlockSourceEvents } from '@aztec/stdlib/block';
387
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
388
+ import { getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
389
+ import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
390
+ import { execInSpan, trackSpan } from '@aztec/telemetry-client';
391
+ import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
392
+ import { getCheckpointBlobDataFromBlobs, retrieveCheckpointCalldataFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from '../l1/data_retrieval.js';
393
+ import { MessageStoreError } from '../store/message_store.js';
394
+ import { ArchiverDataStoreUpdater } from './data_store_updater.js';
395
+ import { validateCheckpointAttestations } from './validation.js';
396
+ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpochPrune'), _dec2 = trackSpan('Archiver.handleL1ToL2Messages'), _dec3 = trackSpan('Archiver.handleCheckpoints');
397
+ /**
398
+ * Handles L1 synchronization for the archiver.
399
+ * Responsible for fetching checkpoints, L1→L2 messages, and handling L1 reorgs.
400
+ */ export class ArchiverL1Synchronizer {
401
+ publicClient;
402
+ debugClient;
403
+ rollup;
404
+ inbox;
405
+ store;
406
+ config;
407
+ blobClient;
408
+ epochCache;
409
+ dateProvider;
410
+ instrumentation;
411
+ l1Constants;
412
+ events;
413
+ log;
414
+ static{
415
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
416
+ [
417
+ _dec,
418
+ 2,
419
+ "syncFromL1"
420
+ ],
421
+ [
422
+ _dec1,
423
+ 2,
424
+ "handleEpochPrune"
425
+ ],
426
+ [
427
+ _dec2,
428
+ 2,
429
+ "handleL1ToL2Messages"
430
+ ],
431
+ [
432
+ _dec3,
433
+ 2,
434
+ "handleCheckpoints"
435
+ ]
436
+ ], []));
437
+ }
438
+ l1BlockNumber;
439
+ l1BlockHash;
440
+ l1Timestamp;
441
+ updater;
442
+ tracer;
443
+ constructor(publicClient, debugClient, rollup, inbox, store, config, blobClient, epochCache, dateProvider, instrumentation, l1Constants, events, tracer, l2TipsCache, log = createLogger('archiver:l1-sync')){
444
+ this.publicClient = publicClient;
445
+ this.debugClient = debugClient;
446
+ this.rollup = rollup;
447
+ this.inbox = inbox;
448
+ this.store = store;
449
+ this.config = config;
450
+ this.blobClient = blobClient;
451
+ this.epochCache = epochCache;
452
+ this.dateProvider = dateProvider;
453
+ this.instrumentation = instrumentation;
454
+ this.l1Constants = l1Constants;
455
+ this.events = events;
456
+ this.log = log;
457
+ _initProto(this);
458
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
459
+ rollupManaLimit: l1Constants.rollupManaLimit
460
+ });
461
+ this.tracer = tracer;
462
+ }
463
+ /** Sets new config */ setConfig(newConfig) {
464
+ this.config = newConfig;
465
+ }
466
+ /** Returns the last L1 block number that was synced. */ getL1BlockNumber() {
467
+ return this.l1BlockNumber;
468
+ }
469
+ /** Returns the last L1 timestamp that was synced. */ getL1Timestamp() {
470
+ return this.l1Timestamp;
471
+ }
472
+ getSignatureContext() {
473
+ return {
474
+ chainId: this.publicClient.chain.id,
475
+ rollupAddress: EthAddress.fromString(this.rollup.address)
476
+ };
477
+ }
478
+ /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */ async testEthereumNodeSynced() {
479
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
480
+ if (maxAllowedDelay === 0) {
481
+ return;
482
+ }
483
+ const { number, timestamp: l1Timestamp } = await this.publicClient.getBlock({
484
+ includeTransactions: false
485
+ });
486
+ const currentTime = BigInt(this.dateProvider.nowInSeconds());
487
+ if (currentTime - l1Timestamp > BigInt(maxAllowedDelay)) {
488
+ throw new Error(`Ethereum node is out of sync (last block synced ${number} at ${l1Timestamp} vs current time ${currentTime})`);
489
+ }
490
+ }
491
+ async syncFromL1(initialSyncComplete) {
492
+ // In between the various calls to L1, the block number can move meaning some of the following
493
+ // calls will return data for blocks that were not present during earlier calls. To combat this
494
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
495
+ // captured at the top of this function.
496
+ const currentL1Block = await this.publicClient.getBlock({
497
+ includeTransactions: false
498
+ });
499
+ const currentL1BlockNumber = currentL1Block.number;
500
+ const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
501
+ const currentL1Timestamp = currentL1Block.timestamp;
502
+ const currentL1BlockData = {
503
+ l1BlockNumber: currentL1BlockNumber,
504
+ l1BlockHash: currentL1BlockHash
505
+ };
506
+ if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
507
+ this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
508
+ return;
509
+ }
510
+ // Warn if the latest L1 block timestamp is too old
511
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
512
+ const now = this.dateProvider.nowInSeconds();
513
+ if (maxAllowedDelay > 0 && Number(currentL1Timestamp) <= now - maxAllowedDelay) {
514
+ this.log.warn(`Latest L1 block ${currentL1BlockNumber} timestamp ${currentL1Timestamp} is too old. Make sure your Ethereum node is synced.`, {
515
+ currentL1BlockNumber,
516
+ currentL1Timestamp,
517
+ now,
518
+ maxAllowedDelay
519
+ });
520
+ }
521
+ // Load sync point for blocks defaulting to start block
522
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await this.store.getSynchPoint();
523
+ this.log.debug(`Starting new archiver sync iteration`, {
524
+ blocksSynchedTo,
525
+ currentL1BlockData
526
+ });
527
+ // Sync L1 to L2 messages. We retry this a few times since there are error conditions that reset the sync point, requiring a new iteration.
528
+ // Note that we cannot just wait for the l1 synchronizer to loop again, since the synchronizer would report as synced up to the current L1
529
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
530
+ await retryTimes(()=>this.handleL1ToL2Messages(currentL1BlockData), 'Handling L1 to L2 messages', 3, 0.1);
531
+ if (currentL1BlockNumber > blocksSynchedTo) {
532
+ // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
533
+ // pending chain validation status, proven checkpoint number, and synched L1 block number.
534
+ const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete);
535
+ // Then we try pruning uncheckpointed blocks if a new slot was mined without checkpoints
536
+ await this.pruneUncheckpointedBlocks(currentL1Timestamp);
537
+ // Then we prune the current epoch if it'd reorg on next submission.
538
+ // Note that we don't do this before retrieving checkpoints because we may need to retrieve
539
+ // checkpoints from more than 2 epochs ago, so we want to make sure we have the latest view of
540
+ // the chain locally before we start unwinding stuff. This can be optimized by figuring out
541
+ // up to which point we're pruning, and then requesting checkpoints up to that point only.
542
+ const { rollupCanPrune } = await this.handleEpochPrune(rollupStatus.provenCheckpointNumber, currentL1BlockNumber, currentL1Timestamp);
543
+ // If the last checkpoint we processed had an invalid attestation, we manually advance the L1 syncpoint
544
+ // past it, since otherwise we'll keep downloading it and reprocessing it on every iteration until
545
+ // we get a valid checkpoint to advance the syncpoint.
546
+ if (!rollupStatus.validationResult?.valid && rollupStatus.lastL1BlockWithCheckpoint !== undefined) {
547
+ await this.store.setCheckpointSynchedL1BlockNumber(rollupStatus.lastL1BlockWithCheckpoint);
548
+ }
549
+ // And lastly we check if we are missing any checkpoints behind us due to a possible L1 reorg.
550
+ // We only do this if rollup cant prune on the next submission. Otherwise we will end up
551
+ // re-syncing the checkpoints we have just unwound above. We also dont do this if the last checkpoint is invalid,
552
+ // since the archiver will rightfully refuse to sync up to it.
553
+ if (!rollupCanPrune && rollupStatus.validationResult?.valid) {
554
+ await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
555
+ }
556
+ this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
557
+ }
558
+ // Update the finalized L2 checkpoint based on L1 finality.
559
+ await this.updateFinalizedCheckpoint();
560
+ // After syncing has completed, update the current l1 block number and timestamp,
561
+ // otherwise we risk announcing to the world that we've synced to a given point,
562
+ // but the corresponding blocks have not been processed (see #12631).
563
+ this.l1Timestamp = currentL1Timestamp;
564
+ this.l1BlockNumber = currentL1BlockNumber;
565
+ this.l1BlockHash = currentL1BlockHash;
566
+ const l1BlockNumberAtEnd = await this.publicClient.getBlockNumber();
567
+ this.log.debug(`Archiver sync iteration complete`, {
568
+ l1BlockNumberAtStart: currentL1BlockNumber,
569
+ l1TimestampAtStart: currentL1Timestamp,
570
+ l1BlockNumberAtEnd
571
+ });
572
+ }
573
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */ async updateFinalizedCheckpoint() {
574
+ try {
575
+ const finalizedL1Block = await getFinalizedL1Block(this.publicClient);
576
+ if (!finalizedL1Block) {
577
+ this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
578
+ return;
579
+ }
580
+ const finalizedL1BlockNumber = finalizedL1Block.number;
581
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
582
+ blockNumber: finalizedL1BlockNumber
583
+ });
584
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
585
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
586
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
587
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
588
+ finalizedCheckpointNumber,
589
+ finalizedL1BlockNumber
590
+ });
591
+ }
592
+ } catch (err) {
593
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
594
+ if (!err?.message?.includes('returned no data')) {
595
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
596
+ }
597
+ }
598
+ }
599
+ /** Prune all proposed local blocks that should have been checkpointed by now. */ async pruneUncheckpointedBlocks(currentL1Timestamp) {
600
+ const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
601
+ this.store.getCheckpointedL2BlockNumber(),
602
+ this.store.getLatestBlockNumber()
603
+ ]);
604
+ // If there are no uncheckpointed blocks, we got nothing to do
605
+ if (lastProposedBlockNumber === lastCheckpointedBlockNumber) {
606
+ this.log.trace(`No uncheckpointed blocks to prune.`);
607
+ return;
608
+ }
609
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
610
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
611
+ const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
612
+ // What's the slot of the first uncheckpointed block?
613
+ const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
614
+ const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
615
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
616
+ return;
617
+ }
618
+ // Prune provisional blocks from slots that have ended without being checkpointed.
619
+ // This also clears any proposed checkpoint whose blocks are being pruned.
620
+ this.log.warn(`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`, {
621
+ firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(),
622
+ slotAtNextL1Block
623
+ });
624
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
625
+ if (prunedBlocks.length > 0) {
626
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
627
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
628
+ slotNumber: firstUncheckpointedBlockSlot,
629
+ blocks: prunedBlocks
630
+ });
631
+ }
632
+ }
633
+ /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
634
+ const time = (currentL1Timestamp ?? 0n) + BigInt(this.l1Constants.ethereumSlotDuration);
635
+ const result = await this.rollup.canPruneAtTime(time, {
636
+ blockNumber: currentL1BlockNumber
637
+ });
638
+ if (result) {
639
+ this.log.debug(`Rollup contract allows pruning at L1 block ${currentL1BlockNumber} time ${time}`, {
640
+ currentL1Timestamp,
641
+ pruneTime: time,
642
+ currentL1BlockNumber
643
+ });
644
+ }
645
+ return result;
646
+ }
647
+ /** Checks if there'd be a reorg for the next checkpoint submission and start pruning now. */ async handleEpochPrune(provenCheckpointNumber, currentL1BlockNumber, currentL1Timestamp) {
648
+ const rollupCanPrune = await this.canPrune(currentL1BlockNumber, currentL1Timestamp);
649
+ const localPendingCheckpointNumber = await this.store.getSynchedCheckpointNumber();
650
+ const canPrune = localPendingCheckpointNumber > provenCheckpointNumber && rollupCanPrune;
651
+ if (canPrune) {
652
+ const timer = new Timer();
653
+ const pruneFrom = CheckpointNumber(provenCheckpointNumber + 1);
654
+ const header = await this.getCheckpointHeader(pruneFrom);
655
+ if (header === undefined) {
656
+ throw new Error(`Missing checkpoint header ${pruneFrom}`);
657
+ }
658
+ const pruneFromSlotNumber = header.slotNumber;
659
+ const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1Constants);
660
+ const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
661
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
662
+ // promises when the gap between local pending and proven checkpoint numbers is large.
663
+ const BATCH_SIZE = 10;
664
+ const indices = Array.from({
665
+ length: checkpointsToUnwind
666
+ }, (_, i)=>CheckpointNumber(i + pruneFrom));
667
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, (idx)=>this.store.getCheckpointData(idx))).filter(isDefined);
668
+ const newBlocks = (await asyncPool(BATCH_SIZE, checkpoints, (cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)))).filter(isDefined).flat();
669
+ // Emit an event for listening services to react to the chain prune
670
+ this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
671
+ type: L2BlockSourceEvents.L2PruneUnproven,
672
+ epochNumber: pruneFromEpochNumber,
673
+ blocks: newBlocks
674
+ });
675
+ this.log.debug(`L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`);
676
+ await this.updater.removeCheckpointsAfter(provenCheckpointNumber);
677
+ this.log.warn(`Removed ${count(checkpointsToUnwind, 'checkpoint')} after checkpoint ${provenCheckpointNumber} ` + `due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`);
678
+ this.instrumentation.processPrune(timer.ms());
679
+ // TODO(palla/reorg): Do we need to set the block synched L1 block number here?
680
+ // Seems like the next iteration should handle this.
681
+ // await this.store.setCheckpointSynchedL1BlockNumber(currentL1BlockNumber);
682
+ }
683
+ return {
684
+ rollupCanPrune
685
+ };
686
+ }
687
+ nextRange(end, limit) {
688
+ const batchSize = this.config.batchSize * this.l1Constants.slotDuration / this.l1Constants.ethereumSlotDuration;
689
+ const nextStart = end + 1n;
690
+ const nextEnd = nextStart + BigInt(batchSize);
691
+ if (nextEnd > limit) {
692
+ return [
693
+ nextStart,
694
+ limit
695
+ ];
696
+ }
697
+ return [
698
+ nextStart,
699
+ nextEnd
700
+ ];
701
+ }
702
+ async handleL1ToL2Messages(currentL1Block) {
703
+ // Load the syncpoint, which may have been updated in a previous iteration
704
+ const { messagesSynchedTo = {
705
+ l1BlockNumber: this.l1Constants.l1StartBlock,
706
+ l1BlockHash: this.l1Constants.l1StartBlockHash
707
+ } } = await this.store.getSynchPoint();
708
+ // Nothing to do if L1 block number has not moved forward
709
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
710
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
711
+ return true;
712
+ }
713
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
714
+ const remoteMessagesState = await this.inbox.getState({
715
+ blockNumber: currentL1BlockNumber
716
+ });
717
+ const localLastMessage = await this.store.getLastL1ToL2Message();
718
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
719
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
720
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
721
+ return true;
722
+ }
723
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
724
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
725
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
726
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
727
+ try {
728
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
729
+ } catch (error) {
730
+ if (isErrorClass(error, MessageStoreError)) {
731
+ this.log.warn(`Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`, {
732
+ inboxMessage: error.inboxMessage
733
+ });
734
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
735
+ return false;
736
+ }
737
+ throw error;
738
+ }
739
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
740
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
741
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
742
+ const localLastMessageAfterSync = await this.store.getLastL1ToL2Message();
743
+ if (!await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState)) {
744
+ this.log.warn(`Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`, {
745
+ localLastMessageAfterSync,
746
+ remoteMessagesState
747
+ });
748
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
749
+ return false;
750
+ }
751
+ // Advance the syncpoint after a successful sync
752
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
753
+ return true;
754
+ }
755
+ /** Checks if the local rolling hash and message count matches the remote state */ async localStateMatches(localLastMessage, remoteState) {
756
+ const localMessageCount = await this.store.getTotalL1ToL2MessageCount();
757
+ this.log.trace(`Comparing local and remote inbox state`, {
758
+ localMessageCount,
759
+ localLastMessage,
760
+ remoteState
761
+ });
762
+ return remoteState.totalMessagesInserted === localMessageCount && remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO);
763
+ }
764
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */ async retrieveAndStoreMessages(fromL1Block, toL1Block) {
765
+ let searchStartBlock = 0n;
766
+ let searchEndBlock = fromL1Block;
767
+ let lastMessage;
768
+ let messageCount = 0;
769
+ do {
770
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
771
+ this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
772
+ const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
773
+ const timer = new Timer();
774
+ await this.store.addL1ToL2Messages(messages);
775
+ const perMsg = timer.ms() / messages.length;
776
+ this.instrumentation.processNewMessages(messages.length, perMsg);
777
+ for (const msg of messages){
778
+ this.log.debug(`Downloaded L1 to L2 message`, {
779
+ ...msg,
780
+ leaf: msg.leaf.toString()
781
+ });
782
+ lastMessage = msg;
783
+ messageCount++;
784
+ }
785
+ }while (searchEndBlock < toL1Block)
786
+ if (messageCount > 0) {
787
+ this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
788
+ lastMessage,
789
+ messageCount
790
+ });
791
+ }
792
+ }
793
+ /**
794
+ * Rolls back local L1 to L2 messages to the last common message with L1, and updates the syncpoint to the L1 block of that message.
795
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
796
+ */ async rollbackL1ToL2Messages(remoteMessagesState) {
797
+ const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
798
+ // Slowly go back through our messages until we find the last common message. We could query the logs in
799
+ // batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
800
+ // so it's fine to query one log at a time.
801
+ let commonMsg;
802
+ let messagesToDelete = 0;
803
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
804
+ for await (const localMsg of this.store.iterateL1ToL2Messages({
805
+ reverse: true
806
+ })){
807
+ const logCtx = {
808
+ remoteMsg: undefined,
809
+ localMsg,
810
+ remoteMessagesState
811
+ };
812
+ // First check if the local message rolling hash matches the current rolling hash of the inbox contract,
813
+ // which means we just need to rollback some local messages and we should be back in sync. This means there
814
+ // was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
815
+ if (localMsg.rollingHash.equals(remoteRollingHash)) {
816
+ this.log.info(`Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`, logCtx);
817
+ commonMsg = localMsg;
818
+ break;
819
+ }
820
+ // If there's no match with the current remote state, check if the message exists on the inbox contract at all
821
+ // by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
822
+ // then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
823
+ // of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
824
+ // an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
825
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
826
+ logCtx.remoteMsg = remoteMsg;
827
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
828
+ this.log.info(`Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`, logCtx);
829
+ commonMsg = remoteMsg;
830
+ break;
831
+ } else if (remoteMsg) {
832
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
833
+ messagesToDelete++;
834
+ } else {
835
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
836
+ messagesToDelete++;
837
+ }
838
+ }
839
+ // Delete everything after the common message we found, if anything needs to be deleted.
840
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
841
+ if (messagesToDelete > 0) {
842
+ const lastGoodIndex = commonMsg?.index;
843
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
844
+ await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
845
+ }
846
+ // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
847
+ // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
848
+ // after the last common message.
849
+ const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
850
+ const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
851
+ const messagesSyncPoint = {
852
+ l1BlockNumber: syncPointL1BlockNumber,
853
+ l1BlockHash: syncPointL1BlockHash
854
+ };
855
+ await this.store.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
856
+ this.log.verbose(`Updated messages syncpoint to L1 block ${syncPointL1BlockNumber}`, {
857
+ ...messagesSyncPoint,
858
+ remoteTreeInProgress
859
+ });
860
+ return messagesSyncPoint;
861
+ }
862
+ async getL1BlockHash(l1BlockNumber) {
863
+ const block = await this.publicClient.getBlock({
864
+ blockNumber: l1BlockNumber,
865
+ includeTransactions: false
866
+ });
867
+ if (!block) {
868
+ throw new Error(`Missing L1 block ${l1BlockNumber}`);
869
+ }
870
+ return Buffer32.fromString(block.hash);
871
+ }
872
+ async handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete) {
873
+ const localPendingCheckpointNumber = await this.store.getSynchedCheckpointNumber();
874
+ const initialValidationResult = await this.store.getPendingChainValidationStatus();
875
+ const { provenCheckpointNumber, provenArchive, pendingCheckpointNumber, pendingArchive, archiveOfMyCheckpoint: archiveForLocalPendingCheckpointNumber } = await execInSpan(this.tracer, 'Archiver.getRollupStatus', ()=>this.rollup.status(localPendingCheckpointNumber, {
876
+ blockNumber: currentL1BlockNumber
877
+ }));
878
+ const rollupStatus = {
879
+ provenCheckpointNumber,
880
+ provenArchive: provenArchive.toString(),
881
+ pendingCheckpointNumber,
882
+ pendingArchive: pendingArchive.toString(),
883
+ validationResult: initialValidationResult
884
+ };
885
+ this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
886
+ localPendingCheckpointNumber,
887
+ blocksSynchedTo,
888
+ currentL1BlockNumber,
889
+ archiveForLocalPendingCheckpointNumber,
890
+ ...rollupStatus
891
+ });
892
+ const updateProvenCheckpoint = async ()=>{
893
+ // Annoying edge case: if proven checkpoint is moved back to 0 due to a reorg at the beginning of the chain,
894
+ // we need to set it to zero. This is an edge case because we dont have a checkpoint zero (initial checkpoint is one),
895
+ // so localCheckpointForDestinationProvenCheckpointNumber would not be found below.
896
+ if (provenCheckpointNumber === 0) {
897
+ const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
898
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
899
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
900
+ this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, {
901
+ provenCheckpointNumber
902
+ });
903
+ }
904
+ }
905
+ const localCheckpointForDestinationProvenCheckpointNumber = await this.store.getCheckpointData(provenCheckpointNumber);
906
+ // Sanity check. I've hit what seems to be a state where the proven checkpoint is set to a value greater than the latest
907
+ // synched checkpoint when requesting L2Tips from the archiver. This is the only place where the proven checkpoint is set.
908
+ const synched = await this.store.getSynchedCheckpointNumber();
909
+ if (localCheckpointForDestinationProvenCheckpointNumber && synched < localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber) {
910
+ this.log.error(`Hit local checkpoint greater than last synched checkpoint: ${localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber} > ${synched}`);
911
+ }
912
+ this.log.trace(`Local checkpoint for remote proven checkpoint ${provenCheckpointNumber} is ${localCheckpointForDestinationProvenCheckpointNumber?.archive.root.toString() ?? 'undefined'}`);
913
+ if (localCheckpointForDestinationProvenCheckpointNumber && provenArchive.equals(localCheckpointForDestinationProvenCheckpointNumber.archive.root)) {
914
+ const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
915
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
916
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
917
+ this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, {
918
+ provenCheckpointNumber
919
+ });
920
+ const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
921
+ const provenEpochNumber = getEpochAtSlot(provenSlotNumber, this.l1Constants);
922
+ const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.blockCount - 1;
923
+ this.events.emit(L2BlockSourceEvents.L2BlockProven, {
924
+ type: L2BlockSourceEvents.L2BlockProven,
925
+ blockNumber: BlockNumber(lastBlockNumberInCheckpoint),
926
+ slotNumber: provenSlotNumber,
927
+ epochNumber: provenEpochNumber
928
+ });
929
+ this.instrumentation.updateLastProvenCheckpoint(localCheckpointForDestinationProvenCheckpointNumber);
930
+ } else {
931
+ this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
932
+ }
933
+ }
934
+ };
935
+ // This is an edge case that we only hit if there are no proposed checkpoints.
936
+ // If we have 0 checkpoints locally and there are no checkpoints onchain there is nothing to do.
937
+ const noCheckpoints = localPendingCheckpointNumber === 0 && pendingCheckpointNumber === 0;
938
+ if (noCheckpoints) {
939
+ await this.store.setCheckpointSynchedL1BlockNumber(currentL1BlockNumber);
940
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`);
941
+ return rollupStatus;
942
+ }
943
+ await updateProvenCheckpoint();
944
+ // Related to the L2 reorgs of the pending chain. We are only interested in actually addressing a reorg if there
945
+ // are any state that could be impacted by it. If we have no checkpoints, there is no impact.
946
+ if (localPendingCheckpointNumber > 0) {
947
+ const localPendingCheckpoint = await this.store.getCheckpointData(localPendingCheckpointNumber);
948
+ if (localPendingCheckpoint === undefined) {
949
+ throw new Error(`Missing checkpoint ${localPendingCheckpointNumber}`);
950
+ }
951
+ const localPendingArchiveRoot = localPendingCheckpoint.archive.root.toString();
952
+ const noCheckpointSinceLast = localPendingCheckpoint && pendingArchive.toString() === localPendingArchiveRoot;
953
+ if (noCheckpointSinceLast) {
954
+ // We believe the following line causes a problem when we encounter L1 re-orgs.
955
+ // Basically, by setting the synched L1 block number here, we are saying that we have
956
+ // processed all checkpoints up to the current L1 block number and we will not attempt to retrieve logs from
957
+ // this block again (or any blocks before).
958
+ // However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing checkpoints.
959
+ // We must only set this block number based on actually retrieved logs.
960
+ // TODO(#8621): Tackle this properly when we handle L1 Re-orgs.
961
+ // await this.store.setCheckpointSynchedL1BlockNumber(currentL1BlockNumber);
962
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
963
+ return rollupStatus;
964
+ }
965
+ const localPendingCheckpointInChain = archiveForLocalPendingCheckpointNumber.equals(localPendingCheckpoint.archive.root);
966
+ if (!localPendingCheckpointInChain) {
967
+ // If our local pending checkpoint tip is not in the chain on L1 a "prune" must have happened
968
+ // or the L1 have reorged.
969
+ // In any case, we have to figure out how far into the past the action will take us.
970
+ // For simplicity here, we will simply rewind until we end in a checkpoint that is also on the chain on L1.
971
+ this.log.debug(`L2 prune has been detected due to local pending checkpoint ${localPendingCheckpointNumber} not in chain`, {
972
+ localPendingCheckpointNumber,
973
+ localPendingArchiveRoot,
974
+ archiveForLocalPendingCheckpointNumber
975
+ });
976
+ let tipAfterUnwind = localPendingCheckpointNumber;
977
+ while(true){
978
+ const candidateCheckpoint = await this.store.getCheckpointData(tipAfterUnwind);
979
+ if (candidateCheckpoint === undefined) {
980
+ break;
981
+ }
982
+ const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.checkpointNumber);
983
+ this.log.trace(`Checking local checkpoint ${candidateCheckpoint.checkpointNumber} with archive ${candidateCheckpoint.archive.root}`, {
984
+ archiveAtContract,
985
+ archiveLocal: candidateCheckpoint.archive.root.toString()
986
+ });
987
+ if (archiveAtContract.equals(candidateCheckpoint.archive.root)) {
988
+ break;
989
+ }
990
+ tipAfterUnwind--;
991
+ }
992
+ const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
993
+ await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
994
+ this.log.warn(`Removed ${count(checkpointsToRemove, 'checkpoint')} after checkpoint ${tipAfterUnwind} ` + `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`);
995
+ }
996
+ }
997
+ // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
998
+ // computed using the L2 block time vs the L1 block time.
999
+ let searchStartBlock = blocksSynchedTo;
1000
+ let searchEndBlock = blocksSynchedTo;
1001
+ let lastRetrievedCheckpoint;
1002
+ let lastL1BlockWithCheckpoint = undefined;
1003
+ do {
1004
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
1005
+ this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
1006
+ // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
1007
+ const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', ()=>retrieveCheckpointCalldataFromRollup(this.rollup, this.publicClient, this.debugClient, searchStartBlock, searchEndBlock, this.instrumentation, this.log));
1008
+ if (calldataCheckpoints.length === 0) {
1009
+ // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
1010
+ // See further details in earlier comments.
1011
+ this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
1012
+ continue;
1013
+ }
1014
+ this.log.debug(`Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
1015
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
1016
+ searchStartBlock,
1017
+ searchEndBlock
1018
+ });
1019
+ // Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
1020
+ // We only check the last one; if it matches, the blob fetch is skipped for that entry.
1021
+ // TODO(palla/pipelining): We may have more than a single checkpoint to promote
1022
+ const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
1023
+ const promoteResult = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
1024
+ const checkpointToPromote = promoteResult && !('diverged' in promoteResult) ? promoteResult : undefined;
1025
+ const evictProposedFrom = promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
1026
+ // Then fetch blobs in parallel and build the full published checkpoints
1027
+ const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
1028
+ const blobFetched = await asyncPool(10, toFetchBlobs, async (checkpoint)=>retrievedToPublishedCheckpoint({
1029
+ ...checkpoint,
1030
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(this.blobClient, checkpoint.l1.blockHash, checkpoint.blobHashes, checkpoint.checkpointNumber, this.log, !initialSyncComplete, checkpoint.parentBeaconBlockRoot, checkpoint.l1.timestamp)
1031
+ }));
1032
+ // And add the promoted checkpoint to the list of all checkpoints
1033
+ const publishedCheckpoints = checkpointToPromote ? [
1034
+ ...blobFetched,
1035
+ checkpointToPromote
1036
+ ] : blobFetched;
1037
+ const validCheckpoints = [];
1038
+ // Now loop through all checkpoints and validate their attestations
1039
+ for (const published of publishedCheckpoints){
1040
+ const validationResult = this.config.skipValidateCheckpointAttestations ? {
1041
+ valid: true
1042
+ } : await validateCheckpointAttestations(published, this.epochCache, this.l1Constants, this.getSignatureContext(), this.log);
1043
+ // Only update the validation result if it has changed, so we can keep track of the first invalid checkpoint
1044
+ // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
1045
+ // There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
1046
+ // we need to update the validation result, since we need to be able to invalidate the new one.
1047
+ // See test 'chain progresses if an invalid checkpoint is invalidated with an invalid one' for more info.
1048
+ if (rollupStatus.validationResult?.valid !== validationResult.valid || !rollupStatus.validationResult.valid && !validationResult.valid && rollupStatus.validationResult.checkpoint.checkpointNumber === validationResult.checkpoint.checkpointNumber) {
1049
+ rollupStatus.validationResult = validationResult;
1050
+ }
1051
+ if (!validationResult.valid) {
1052
+ this.log.warn(`Skipping checkpoint ${published.checkpoint.number} due to invalid attestations`, {
1053
+ checkpointHash: published.checkpoint.hash(),
1054
+ l1BlockNumber: published.l1.blockNumber,
1055
+ ...pick(validationResult, 'reason')
1056
+ });
1057
+ // Emit event for invalid checkpoint detection
1058
+ this.events.emit(L2BlockSourceEvents.InvalidAttestationsCheckpointDetected, {
1059
+ type: L2BlockSourceEvents.InvalidAttestationsCheckpointDetected,
1060
+ validationResult
1061
+ });
1062
+ continue;
1063
+ }
1064
+ // Check the inHash of the checkpoint against the l1->l2 messages.
1065
+ // The messages should've been synced up to the currentL1BlockNumber and must be available for the published
1066
+ // checkpoints we just retrieved.
1067
+ const l1ToL2Messages = await this.store.getL1ToL2Messages(published.checkpoint.number);
1068
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
1069
+ const publishedInHash = published.checkpoint.header.inHash;
1070
+ if (!computedInHash.equals(publishedInHash)) {
1071
+ this.log.fatal(`Mismatch inHash for checkpoint ${published.checkpoint.number}`, {
1072
+ checkpointHash: published.checkpoint.hash(),
1073
+ l1BlockNumber: published.l1.blockNumber,
1074
+ computedInHash,
1075
+ publishedInHash
1076
+ });
1077
+ // Throwing an error since this is most likely caused by a bug.
1078
+ throw new Error(`Mismatch inHash for checkpoint ${published.checkpoint.number}. Expected ${computedInHash} but got ${publishedInHash}`);
1079
+ }
1080
+ validCheckpoints.push(published);
1081
+ this.log.debug(`Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`, {
1082
+ checkpointHash: published.checkpoint.hash(),
1083
+ l1BlockNumber: published.l1.blockNumber,
1084
+ ...published.checkpoint.header.toInspect(),
1085
+ blocks: published.checkpoint.blocks.map((b)=>b.getStats())
1086
+ });
1087
+ }
1088
+ for (const published of validCheckpoints){
1089
+ this.instrumentation.processCheckpointL1Timing({
1090
+ slotNumber: published.checkpoint.header.slotNumber,
1091
+ l1Timestamp: published.l1.timestamp,
1092
+ l1Constants: this.l1Constants
1093
+ });
1094
+ }
1095
+ try {
1096
+ const updatedValidationResult = rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1097
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
1098
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
1099
+ const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(validCheckpoints, (c)=>c.checkpoint.number === checkpointToPromote?.checkpoint.number);
1100
+ const [processDuration, result] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.addCheckpoints', ()=>this.updater.addCheckpoints(checkpointsToAdd, updatedValidationResult, maybeValidCheckpointToPromote && {
1101
+ l1: lastCalldataCheckpoint.l1,
1102
+ attestations: lastCalldataCheckpoint.attestations,
1103
+ checkpoint: maybeValidCheckpointToPromote
1104
+ }, evictProposedFrom)));
1105
+ if (checkpointsToAdd.length > 0) {
1106
+ this.instrumentation.processNewCheckpointedBlocks(processDuration / checkpointsToAdd.length, checkpointsToAdd.flatMap((c)=>c.checkpoint.blocks));
1107
+ }
1108
+ // If blocks were pruned due to conflict with L1 checkpoints, emit event
1109
+ if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1110
+ const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
1111
+ const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
1112
+ this.log.info(`Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`, {
1113
+ prunedBlocks: result.prunedBlocks.map((b)=>b.toBlockInfo()),
1114
+ prunedSlotNumber,
1115
+ prunedCheckpointNumber
1116
+ });
1117
+ // Emit event for listening services to react to the prune.
1118
+ // Note: slotNumber comes from the first pruned block. If pruned blocks theoretically spanned multiple slots,
1119
+ // only one slot number would be reported (though in practice all blocks in a checkpoint span a single slot).
1120
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
1121
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
1122
+ slotNumber: prunedSlotNumber,
1123
+ blocks: result.prunedBlocks
1124
+ });
1125
+ }
1126
+ } catch (err) {
1127
+ if (err instanceof InitialCheckpointNumberNotSequentialError) {
1128
+ const { previousCheckpointNumber, newCheckpointNumber } = err;
1129
+ const previousCheckpoint = previousCheckpointNumber ? await this.store.getCheckpointData(CheckpointNumber(previousCheckpointNumber)) : undefined;
1130
+ const updatedL1SyncPoint = previousCheckpoint?.l1.blockNumber ?? this.l1Constants.l1StartBlock;
1131
+ await this.store.setCheckpointSynchedL1BlockNumber(updatedL1SyncPoint);
1132
+ 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.`, {
1133
+ previousCheckpointNumber,
1134
+ newCheckpointNumber,
1135
+ updatedL1SyncPoint
1136
+ });
1137
+ }
1138
+ throw err;
1139
+ }
1140
+ for (const checkpoint of validCheckpoints){
1141
+ this.log.info(`Downloaded checkpoint ${checkpoint.checkpoint.number}`, {
1142
+ checkpointHash: checkpoint.checkpoint.hash(),
1143
+ checkpointNumber: checkpoint.checkpoint.number,
1144
+ blockCount: checkpoint.checkpoint.blocks.length,
1145
+ txCount: checkpoint.checkpoint.blocks.reduce((acc, b)=>acc + b.body.txEffects.length, 0),
1146
+ header: checkpoint.checkpoint.header.toInspect(),
1147
+ archiveRoot: checkpoint.checkpoint.archive.root.toString(),
1148
+ archiveNextLeafIndex: checkpoint.checkpoint.archive.nextAvailableLeafIndex
1149
+ });
1150
+ }
1151
+ lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1152
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1153
+ }while (searchEndBlock < currentL1BlockNumber)
1154
+ // Important that we update AFTER inserting the blocks.
1155
+ await updateProvenCheckpoint();
1156
+ return {
1157
+ ...rollupStatus,
1158
+ lastRetrievedCheckpoint,
1159
+ lastL1BlockWithCheckpoint
1160
+ };
1161
+ }
1162
+ /**
1163
+ * Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
1164
+ * a synthetic published checkpoint (skipping blob fetch).
1165
+ *
1166
+ * Returns { diverged: true, fromCheckpointNumber } when the L1 checkpoint does NOT match local pending
1167
+ * data for that number, so the caller can evict the entire pending suffix >= fromCheckpointNumber
1168
+ * (those entries chain off the now-invalid local state) within the same addCheckpoints transaction.
1169
+ */ async tryBuildPublishedCheckpointFromProposed(calldataCheckpoint) {
1170
+ if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
1171
+ return undefined;
1172
+ }
1173
+ // Look up the specific pending entry for the checkpoint being mined, not just the tip
1174
+ const proposed = await this.store.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
1175
+ if (!proposed) {
1176
+ return undefined;
1177
+ }
1178
+ if (!proposed.header.equals(calldataCheckpoint.header) || !proposed.archive.root.equals(calldataCheckpoint.archiveRoot)) {
1179
+ this.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`, {
1180
+ proposedCheckpointNumber: proposed.checkpointNumber,
1181
+ proposedHeader: proposed.header.toInspect(),
1182
+ proposedArchiveRoot: proposed.archive.root.toString(),
1183
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1184
+ calldataHeader: calldataCheckpoint.header.toInspect(),
1185
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString()
1186
+ });
1187
+ // Return a divergence signal so the caller can evict pending >= this number
1188
+ return {
1189
+ diverged: true,
1190
+ fromCheckpointNumber: proposed.checkpointNumber
1191
+ };
1192
+ }
1193
+ this.log.debug(`Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`, {
1194
+ proposedHeader: proposed.header.toInspect(),
1195
+ proposedArchiveRoot: proposed.archive.root.toString()
1196
+ });
1197
+ const blocks = await this.store.getBlocks(BlockNumber(proposed.startBlock), proposed.blockCount);
1198
+ if (blocks.length !== proposed.blockCount) {
1199
+ this.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`, {
1200
+ proposedCheckpointNumber: proposed.checkpointNumber,
1201
+ proposedStartBlock: proposed.startBlock,
1202
+ proposedBlockCount: proposed.blockCount,
1203
+ retrievedBlocks: blocks.map((b)=>b.number)
1204
+ });
1205
+ return undefined;
1206
+ }
1207
+ const checkpoint = Checkpoint.from({
1208
+ archive: proposed.archive,
1209
+ header: proposed.header,
1210
+ blocks,
1211
+ number: proposed.checkpointNumber,
1212
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier
1213
+ });
1214
+ const promotedCheckpoint = PublishedCheckpoint.from({
1215
+ checkpoint,
1216
+ l1: calldataCheckpoint.l1,
1217
+ attestations: calldataCheckpoint.attestations
1218
+ });
1219
+ this.instrumentation.processCheckpointPromoted();
1220
+ return promotedCheckpoint;
1221
+ }
1222
+ async checkForNewCheckpointsBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
1223
+ const { lastRetrievedCheckpoint, pendingCheckpointNumber } = status;
1224
+ // Compare the last checkpoint we have (either retrieved in this round or loaded from store) with what the
1225
+ // rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
1226
+ const latestLocalCheckpointNumber = lastRetrievedCheckpoint?.checkpoint.number ?? await this.store.getSynchedCheckpointNumber();
1227
+ if (latestLocalCheckpointNumber < pendingCheckpointNumber) {
1228
+ // Here we have consumed all logs until the `currentL1Block` we pinned at the beginning of the archiver loop,
1229
+ // but still haven't reached the pending checkpoint according to the call to the rollup contract.
1230
+ // We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
1231
+ // the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
1232
+ // we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
1233
+ let latestLocalCheckpointArchive = undefined;
1234
+ let targetL1BlockNumber = maxBigint(currentL1BlockNumber - 64n, 0n);
1235
+ if (lastRetrievedCheckpoint) {
1236
+ latestLocalCheckpointArchive = lastRetrievedCheckpoint.checkpoint.archive.root.toString();
1237
+ targetL1BlockNumber = lastRetrievedCheckpoint.l1.blockNumber;
1238
+ } else if (latestLocalCheckpointNumber > 0) {
1239
+ const checkpoint = await this.store.getRangeOfCheckpoints(latestLocalCheckpointNumber, 1).then(([c])=>c);
1240
+ latestLocalCheckpointArchive = checkpoint.archive.root.toString();
1241
+ targetL1BlockNumber = checkpoint.l1.blockNumber;
1242
+ }
1243
+ this.log.warn(`Failed to reach checkpoint ${pendingCheckpointNumber} at ${currentL1BlockNumber} (latest is ${latestLocalCheckpointNumber}). ` + `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`, {
1244
+ latestLocalCheckpointNumber,
1245
+ latestLocalCheckpointArchive,
1246
+ blocksSynchedTo,
1247
+ currentL1BlockNumber,
1248
+ ...status
1249
+ });
1250
+ await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
1251
+ } else {
1252
+ this.log.trace(`No new checkpoints behind L1 sync point to retrieve.`, {
1253
+ latestLocalCheckpointNumber,
1254
+ pendingCheckpointNumber
1255
+ });
1256
+ }
1257
+ }
1258
+ async getCheckpointHeader(number) {
1259
+ const checkpoint = await this.store.getCheckpointData(number);
1260
+ if (!checkpoint) {
1261
+ return undefined;
1262
+ }
1263
+ return checkpoint.header;
1264
+ }
1265
+ }