@aztec/archiver 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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 (236) hide show
  1. package/README.md +164 -22
  2. package/dest/archiver.d.ts +194 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +949 -0
  5. package/dest/config.d.ts +34 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +95 -0
  8. package/dest/errors.d.ts +87 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +129 -0
  11. package/dest/factory.d.ts +16 -10
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +117 -20
  14. package/dest/index.d.ts +19 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +17 -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 +143 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +413 -0
  26. package/dest/l1/data_retrieval.d.ts +102 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +85 -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 +43 -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/contract_data_source_adapter.d.ts +25 -0
  48. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  49. package/dest/modules/contract_data_source_adapter.js +32 -0
  50. package/dest/modules/data_source_base.d.ts +112 -0
  51. package/dest/modules/data_source_base.d.ts.map +1 -0
  52. package/dest/modules/data_source_base.js +322 -0
  53. package/dest/modules/data_store_updater.d.ts +105 -0
  54. package/dest/modules/data_store_updater.d.ts.map +1 -0
  55. package/dest/modules/data_store_updater.js +393 -0
  56. package/dest/modules/instrumentation.d.ts +63 -0
  57. package/dest/modules/instrumentation.d.ts.map +1 -0
  58. package/dest/modules/instrumentation.js +166 -0
  59. package/dest/modules/l1_synchronizer.d.ts +77 -0
  60. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  61. package/dest/modules/l1_synchronizer.js +1381 -0
  62. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  63. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  64. package/dest/modules/outbox_trees_resolver.js +162 -0
  65. package/dest/modules/validation.d.ts +40 -0
  66. package/dest/modules/validation.d.ts.map +1 -0
  67. package/dest/{archiver → modules}/validation.js +41 -17
  68. package/dest/store/block_store.d.ts +303 -0
  69. package/dest/store/block_store.d.ts.map +1 -0
  70. package/dest/store/block_store.js +1206 -0
  71. package/dest/store/contract_class_store.d.ts +31 -0
  72. package/dest/store/contract_class_store.d.ts.map +1 -0
  73. package/dest/store/contract_class_store.js +98 -0
  74. package/dest/store/contract_instance_store.d.ts +51 -0
  75. package/dest/store/contract_instance_store.d.ts.map +1 -0
  76. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +55 -3
  77. package/dest/store/data_stores.d.ts +68 -0
  78. package/dest/store/data_stores.d.ts.map +1 -0
  79. package/dest/store/data_stores.js +54 -0
  80. package/dest/store/function_names_cache.d.ts +17 -0
  81. package/dest/store/function_names_cache.d.ts.map +1 -0
  82. package/dest/store/function_names_cache.js +30 -0
  83. package/dest/store/l2_tips_cache.d.ts +25 -0
  84. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  85. package/dest/store/l2_tips_cache.js +26 -0
  86. package/dest/store/log_store.d.ts +59 -0
  87. package/dest/store/log_store.d.ts.map +1 -0
  88. package/dest/store/log_store.js +310 -0
  89. package/dest/store/log_store_codec.d.ts +78 -0
  90. package/dest/store/log_store_codec.d.ts.map +1 -0
  91. package/dest/store/log_store_codec.js +110 -0
  92. package/dest/store/message_store.d.ts +50 -0
  93. package/dest/store/message_store.d.ts.map +1 -0
  94. package/dest/{archiver/kv_archiver_store → store}/message_store.js +66 -23
  95. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  96. package/dest/structs/data_retrieval.d.ts.map +1 -0
  97. package/dest/structs/inbox_message.d.ts +15 -0
  98. package/dest/structs/inbox_message.d.ts.map +1 -0
  99. package/dest/{archiver/structs → structs}/inbox_message.js +6 -6
  100. package/dest/structs/published.d.ts +2 -0
  101. package/dest/structs/published.d.ts.map +1 -0
  102. package/dest/test/fake_l1_state.d.ts +214 -0
  103. package/dest/test/fake_l1_state.d.ts.map +1 -0
  104. package/dest/test/fake_l1_state.js +517 -0
  105. package/dest/test/index.d.ts +2 -1
  106. package/dest/test/index.d.ts.map +1 -1
  107. package/dest/test/index.js +4 -1
  108. package/dest/test/mock_archiver.d.ts +5 -6
  109. package/dest/test/mock_archiver.d.ts.map +1 -1
  110. package/dest/test/mock_archiver.js +8 -12
  111. package/dest/test/mock_l1_to_l2_message_source.d.ts +6 -7
  112. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  113. package/dest/test/mock_l1_to_l2_message_source.js +19 -14
  114. package/dest/test/mock_l2_block_source.d.ts +68 -40
  115. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  116. package/dest/test/mock_l2_block_source.js +347 -145
  117. package/dest/test/mock_structs.d.ts +83 -4
  118. package/dest/test/mock_structs.d.ts.map +1 -1
  119. package/dest/test/mock_structs.js +157 -12
  120. package/dest/test/noop_l1_archiver.d.ts +34 -0
  121. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  122. package/dest/test/noop_l1_archiver.js +88 -0
  123. package/package.json +18 -18
  124. package/src/archiver.ts +785 -0
  125. package/src/config.ts +125 -0
  126. package/src/errors.ts +203 -0
  127. package/src/factory.ts +185 -22
  128. package/src/index.ts +27 -3
  129. package/src/interfaces.ts +9 -0
  130. package/src/l1/README.md +55 -0
  131. package/src/l1/bin/retrieve-calldata.ts +194 -0
  132. package/src/l1/calldata_retriever.ts +529 -0
  133. package/src/{archiver → l1}/data_retrieval.ts +157 -243
  134. package/src/l1/debug_tx.ts +99 -0
  135. package/src/l1/spire_proposer.ts +152 -0
  136. package/src/l1/trace_tx.ts +128 -0
  137. package/src/l1/types.ts +13 -0
  138. package/src/l1/validate_historical_logs.ts +140 -0
  139. package/src/l1/validate_trace.ts +229 -0
  140. package/src/modules/contract_data_source_adapter.ts +46 -0
  141. package/src/modules/data_source_base.ts +466 -0
  142. package/src/modules/data_store_updater.ts +519 -0
  143. package/src/modules/instrumentation.ts +217 -0
  144. package/src/modules/l1_synchronizer.ts +1320 -0
  145. package/src/modules/outbox_trees_resolver.ts +199 -0
  146. package/src/modules/validation.ts +186 -0
  147. package/src/store/block_store.ts +1551 -0
  148. package/src/store/contract_class_store.ts +126 -0
  149. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +70 -7
  150. package/src/store/data_stores.ts +104 -0
  151. package/src/store/function_names_cache.ts +37 -0
  152. package/src/store/l2_tips_cache.ts +35 -0
  153. package/src/store/log_store.ts +380 -0
  154. package/src/store/log_store_codec.ts +143 -0
  155. package/src/{archiver/kv_archiver_store → store}/message_store.ts +81 -28
  156. package/src/{archiver/structs → structs}/inbox_message.ts +8 -9
  157. package/src/{archiver/structs → structs}/published.ts +0 -1
  158. package/src/test/fake_l1_state.ts +770 -0
  159. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  160. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  161. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  162. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  163. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  164. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  165. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  166. package/src/test/index.ts +4 -0
  167. package/src/test/mock_archiver.ts +10 -14
  168. package/src/test/mock_l1_to_l2_message_source.ts +16 -15
  169. package/src/test/mock_l2_block_source.ts +416 -161
  170. package/src/test/mock_structs.ts +292 -14
  171. package/src/test/noop_l1_archiver.ts +158 -0
  172. package/dest/archiver/archiver.d.ts +0 -290
  173. package/dest/archiver/archiver.d.ts.map +0 -1
  174. package/dest/archiver/archiver.js +0 -1434
  175. package/dest/archiver/archiver_store.d.ts +0 -256
  176. package/dest/archiver/archiver_store.d.ts.map +0 -1
  177. package/dest/archiver/archiver_store.js +0 -4
  178. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  179. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  180. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  181. package/dest/archiver/config.d.ts +0 -21
  182. package/dest/archiver/config.d.ts.map +0 -1
  183. package/dest/archiver/config.js +0 -55
  184. package/dest/archiver/data_retrieval.d.ts +0 -80
  185. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  186. package/dest/archiver/errors.d.ts +0 -12
  187. package/dest/archiver/errors.d.ts.map +0 -1
  188. package/dest/archiver/errors.js +0 -17
  189. package/dest/archiver/index.d.ts +0 -7
  190. package/dest/archiver/index.d.ts.map +0 -1
  191. package/dest/archiver/index.js +0 -4
  192. package/dest/archiver/instrumentation.d.ts +0 -35
  193. package/dest/archiver/instrumentation.d.ts.map +0 -1
  194. package/dest/archiver/instrumentation.js +0 -140
  195. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -125
  196. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  197. package/dest/archiver/kv_archiver_store/block_store.js +0 -371
  198. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  199. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  200. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  201. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  202. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  203. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -169
  204. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  205. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  206. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  207. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  208. package/dest/archiver/kv_archiver_store/log_store.js +0 -337
  209. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  210. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  211. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  212. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  213. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  214. package/dest/archiver/structs/published.d.ts +0 -3
  215. package/dest/archiver/structs/published.d.ts.map +0 -1
  216. package/dest/archiver/validation.d.ts +0 -17
  217. package/dest/archiver/validation.d.ts.map +0 -1
  218. package/dest/rpc/index.d.ts +0 -9
  219. package/dest/rpc/index.d.ts.map +0 -1
  220. package/dest/rpc/index.js +0 -15
  221. package/src/archiver/archiver.ts +0 -1880
  222. package/src/archiver/archiver_store.ts +0 -310
  223. package/src/archiver/archiver_store_test_suite.ts +0 -1295
  224. package/src/archiver/config.ts +0 -79
  225. package/src/archiver/errors.ts +0 -26
  226. package/src/archiver/index.ts +0 -6
  227. package/src/archiver/instrumentation.ts +0 -187
  228. package/src/archiver/kv_archiver_store/block_store.ts +0 -482
  229. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  230. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -423
  231. package/src/archiver/kv_archiver_store/log_store.ts +0 -407
  232. package/src/archiver/validation.ts +0 -124
  233. package/src/rpc/index.ts +0 -16
  234. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  235. /package/dest/{archiver/structs → structs}/published.js +0 -0
  236. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,393 @@
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { filterAsync } from '@aztec/foundation/collection';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import { ContractClassPublishedEvent } from '@aztec/protocol-contracts/class-registry';
5
+ import { ContractInstancePublishedEvent, ContractInstanceUpdatedEvent } from '@aztec/protocol-contracts/instance-registry';
6
+ import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
7
+ import { computeContractAddressFromInstance, computeContractClassId } from '@aztec/stdlib/contract';
8
+ /** Operation type for contract data updates. */ var Operation = /*#__PURE__*/ function(Operation) {
9
+ Operation[Operation["Store"] = 0] = "Store";
10
+ Operation[Operation["Delete"] = 1] = "Delete";
11
+ return Operation;
12
+ }(Operation || {});
13
+ /** Archiver helper module to handle updates to the data store. */ export class ArchiverDataStoreUpdater {
14
+ stores;
15
+ l2TipsCache;
16
+ opts;
17
+ log;
18
+ constructor(stores, l2TipsCache, opts = {}){
19
+ this.stores = stores;
20
+ this.l2TipsCache = l2TipsCache;
21
+ this.opts = opts;
22
+ this.log = createLogger('archiver:store_updater');
23
+ }
24
+ /**
25
+ * Adds a proposed block to the store with contract class/instance extraction from logs.
26
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
27
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
28
+ *
29
+ * @param block - The proposed L2 block to add.
30
+ * @param pendingChainValidationStatus - Optional validation status to set.
31
+ * @returns True if the operation is successful.
32
+ */ async addProposedBlock(block, pendingChainValidationStatus) {
33
+ const result = await this.stores.db.transactionAsync(async ()=>{
34
+ await this.stores.blocks.addProposedBlock(block);
35
+ const opResults = await Promise.all([
36
+ // Update the pending chain validation status if provided
37
+ pendingChainValidationStatus && this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
38
+ // Add any logs emitted during the retrieved block
39
+ this.stores.logs.addLogs([
40
+ block
41
+ ]),
42
+ // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
43
+ this.addContractDataToDb(block)
44
+ ]);
45
+ return opResults.every(Boolean);
46
+ });
47
+ await this.l2TipsCache?.refresh();
48
+ return result;
49
+ }
50
+ /**
51
+ * Reconciles local blocks with incoming checkpoints from L1.
52
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
53
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
54
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
55
+ * If `promoteProposed` is supplied, the proposed-checkpoint promotion runs inside the same transaction
56
+ * as the added checkpoints so both updates are applied atomically.
57
+ *
58
+ * @param checkpoints - The published checkpoints to add (excluding any being promoted from proposed).
59
+ * @param pendingChainValidationStatus - Optional validation status to set.
60
+ * @param promoteProposed - Optional promotion of the current proposed checkpoint (fast path when blocks are already local).
61
+ * @returns Result with information about any pruned blocks.
62
+ */ async addCheckpoints(checkpoints, pendingChainValidationStatus, promoteProposed, evictProposedFrom) {
63
+ for (const checkpoint of checkpoints){
64
+ validateCheckpoint(checkpoint.checkpoint, {
65
+ rollupManaLimit: this.opts?.rollupManaLimit
66
+ });
67
+ }
68
+ if (promoteProposed) {
69
+ validateCheckpoint(promoteProposed.checkpoint.checkpoint, {
70
+ rollupManaLimit: this.opts?.rollupManaLimit
71
+ });
72
+ }
73
+ const result = await this.stores.db.transactionAsync(async ()=>{
74
+ // Before adding checkpoints, check for conflicts with local blocks if any
75
+ const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
76
+ const insertedCheckpoints = await this.stores.blocks.addCheckpoints(checkpoints);
77
+ // Skip blocks already inserted via addProposedBlock() and blocks of already-stored checkpoints
78
+ // re-included by an L1 reorg: their logs/contract data were extracted when first inserted.
79
+ const newBlocks = insertedCheckpoints.flatMap((ch)=>ch.checkpoint.blocks).filter((b)=>lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
80
+ await Promise.all([
81
+ // Update the pending chain validation status if provided
82
+ pendingChainValidationStatus && this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
83
+ // Add any logs emitted during the retrieved blocks
84
+ this.stores.logs.addLogs(newBlocks),
85
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
86
+ ...newBlocks.map((block)=>this.addContractDataToDb(block)),
87
+ // Promote the proposed checkpoint if requested (uses explicit checkpoint number)
88
+ promoteProposed ? this.stores.blocks.promoteProposedToCheckpointed(promoteProposed.checkpoint.checkpoint.number, promoteProposed.l1, promoteProposed.attestations, promoteProposed.checkpoint.checkpoint.archive.root) : undefined,
89
+ // Evict pending checkpoints that diverged from what L1 mined
90
+ evictProposedFrom !== undefined ? this.stores.blocks.evictProposedCheckpointsFrom(evictProposedFrom) : undefined
91
+ ]);
92
+ return {
93
+ prunedBlocks,
94
+ lastAlreadyInsertedBlockNumber
95
+ };
96
+ });
97
+ await this.l2TipsCache?.refresh();
98
+ return result;
99
+ }
100
+ async addProposedCheckpoint(proposedCheckpoint) {
101
+ const result = await this.stores.db.transactionAsync(async ()=>{
102
+ await this.stores.blocks.addProposedCheckpoint(proposedCheckpoint);
103
+ });
104
+ await this.l2TipsCache?.refresh();
105
+ return result;
106
+ }
107
+ /**
108
+ * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
109
+ * Conflict detection is keyed on `blockNumber`: when a local proposed block and an L1
110
+ * checkpointed block share a block number but live at different slots (e.g. a different proposer
111
+ * mined the same block number one slot earlier), we still treat them as a conflict and prune.
112
+ * The trailing per-checkpoint prune that handles "local has extra trailing blocks within the
113
+ * same slot as the published checkpoint" remains scoped by slot to preserve pipelining: local
114
+ * blocks that live at a later slot than the checkpoint being processed represent speculation
115
+ * atop the just-confirmed tip (and may be referenced by a pending proposed checkpoint), so we
116
+ * leave them in place. This method handles multiple checkpoints but returns after pruning the
117
+ * first conflict found. This is correct because pruning from the first conflict point removes
118
+ * all subsequent blocks, and when checkpoints are added afterward, they include all the correct
119
+ * blocks.
120
+ */ async pruneMismatchingLocalBlocks(checkpoints) {
121
+ const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
122
+ this.stores.blocks.getCheckpointedL2BlockNumber(),
123
+ this.stores.blocks.getLatestL2BlockNumber()
124
+ ]);
125
+ // Exit early if there are no local uncheckpointed blocks
126
+ if (lastBlockNumber === lastCheckpointedBlockNumber) {
127
+ return {
128
+ prunedBlocks: undefined,
129
+ lastAlreadyInsertedBlockNumber: undefined
130
+ };
131
+ }
132
+ // Get all uncheckpointed local blocks
133
+ const uncheckpointedLocalBlocks = await this.stores.blocks.getBlocksData({
134
+ from: BlockNumber.add(lastCheckpointedBlockNumber, 1),
135
+ limit: lastBlockNumber - lastCheckpointedBlockNumber
136
+ });
137
+ let lastAlreadyInsertedBlockNumber;
138
+ for (const publishedCheckpoint of checkpoints){
139
+ const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
140
+ const slot = publishedCheckpoint.checkpoint.slot;
141
+ if (checkpointBlocks.length === 0) {
142
+ this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
143
+ continue;
144
+ }
145
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards.
146
+ // Conflict detection joins on block number only — same block number at a different slot is still a conflict.
147
+ for (const checkpointBlock of checkpointBlocks){
148
+ const blockNumber = checkpointBlock.number;
149
+ const existingBlock = uncheckpointedLocalBlocks.find((b)=>b.header.getBlockNumber() === blockNumber);
150
+ const blockInfos = {
151
+ existingBlock: existingBlock?.header.toInspect(),
152
+ checkpointBlock: checkpointBlock.toBlockInfo()
153
+ };
154
+ if (!existingBlock) {
155
+ this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`, blockInfos);
156
+ } else if (existingBlock.archive.root.equals(checkpointBlock.archive.root)) {
157
+ this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
158
+ lastAlreadyInsertedBlockNumber = blockNumber;
159
+ } else {
160
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
161
+ const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
162
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
163
+ return {
164
+ prunedBlocks,
165
+ lastAlreadyInsertedBlockNumber
166
+ };
167
+ }
168
+ }
169
+ // If the sequencer locally proposed extra blocks within this checkpoint's slot (e.g. local has
170
+ // [N, N+1] but L1 confirmed just [N]), prune the extras. Scoped to the checkpoint's slot so we
171
+ // do not throw away speculative blocks at later slots that belong to a pending proposed checkpoint.
172
+ const lastCheckpointBlockNumber = checkpointBlocks.at(-1).number;
173
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter((b)=>b.header.getSlot() === slot);
174
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.header.getBlockNumber();
175
+ if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
176
+ this.log.warn(`Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`);
177
+ const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
178
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
179
+ return {
180
+ prunedBlocks,
181
+ lastAlreadyInsertedBlockNumber
182
+ };
183
+ }
184
+ }
185
+ return {
186
+ prunedBlocks: undefined,
187
+ lastAlreadyInsertedBlockNumber
188
+ };
189
+ }
190
+ /**
191
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
192
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
193
+ * Verifies that each block being removed is not part of a stored checkpoint.
194
+ *
195
+ * @param blockNumber - Remove all blocks with number greater than this.
196
+ * @returns The removed blocks.
197
+ * @throws Error if any block to be removed is checkpointed.
198
+ */ async removeUncheckpointedBlocksAfter(blockNumber) {
199
+ const result = await this.stores.db.transactionAsync(async ()=>{
200
+ // Verify we're only removing uncheckpointed blocks
201
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getCheckpointedL2BlockNumber();
202
+ if (blockNumber < lastCheckpointedBlockNumber) {
203
+ throw new Error(`Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);
204
+ }
205
+ const prunedBlocks = await this.removeBlocksAfter(blockNumber);
206
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
207
+ return prunedBlocks;
208
+ });
209
+ await this.l2TipsCache?.refresh();
210
+ return result;
211
+ }
212
+ /**
213
+ * Removes all blocks without a proposed checkpoint strictly after the specified block number and cleans up associated contract data.
214
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
215
+ * Verifies that each block being removed is not part of a stored checkpoint (proposed or not).
216
+ * This differs from `removeUncheckpointedBlocksAfter` in that it also checks proposed checkpoints.
217
+ *
218
+ * @param blockNumber - Remove all blocks with number greater than this.
219
+ * @returns The removed blocks.
220
+ * @throws Error if any block to be removed is checkpointed.
221
+ */ async removeBlocksWithoutProposedCheckpointAfter(blockNumber) {
222
+ const result = await this.stores.db.transactionAsync(async ()=>{
223
+ // Verify we're only removing uncheckpointed blocks
224
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getProposedCheckpointL2BlockNumber();
225
+ if (blockNumber < lastCheckpointedBlockNumber) {
226
+ throw new Error(`Cannot remove blocks after ${blockNumber} because proposed checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);
227
+ }
228
+ return await this.removeBlocksAfter(blockNumber);
229
+ });
230
+ await this.l2TipsCache?.refresh();
231
+ return result;
232
+ }
233
+ /**
234
+ * Evicts pending proposed checkpoints that referenced any of the just-pruned blocks. Pruned
235
+ * blocks invalidate all proposed checkpoints from the lowest pruned block's checkpoint number
236
+ * onwards: those checkpoints either reference the pruned blocks directly or chain off them.
237
+ */ async evictProposedCheckpointsForPrunedBlocks(prunedBlocks) {
238
+ if (prunedBlocks.length === 0) {
239
+ return;
240
+ }
241
+ const fromCheckpointNumber = prunedBlocks[0].checkpointNumber;
242
+ await this.stores.blocks.evictProposedCheckpointsFrom(fromCheckpointNumber);
243
+ }
244
+ /**
245
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
246
+ * Does not remove their checkpoints.
247
+ */ async removeBlocksAfter(blockNumber) {
248
+ // First get the blocks to be removed so we can clean up contract data
249
+ const removedBlocks = await this.stores.blocks.removeBlocksAfter(blockNumber);
250
+ // Clean up contract data and logs for the removed blocks
251
+ await Promise.all([
252
+ this.stores.logs.deleteLogs(removedBlocks),
253
+ ...removedBlocks.map((block)=>this.removeContractDataFromDb(block))
254
+ ]);
255
+ return removedBlocks;
256
+ }
257
+ /**
258
+ * Removes all checkpoints after the given checkpoint number.
259
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
260
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
261
+ * and uncheckpointed) after the last block of the given checkpoint.
262
+ *
263
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
264
+ * @returns True if the operation is successful.
265
+ */ async removeCheckpointsAfter(checkpointNumber) {
266
+ const result = await this.stores.db.transactionAsync(async ()=>{
267
+ const { blocksRemoved = [] } = await this.stores.blocks.removeCheckpointsAfter(checkpointNumber);
268
+ const opResults = await Promise.all([
269
+ // Prune rolls back to the last proven block, which is by definition valid
270
+ this.stores.blocks.setPendingChainValidationStatus({
271
+ valid: true
272
+ }),
273
+ // Remove contract data for all blocks being removed
274
+ ...blocksRemoved.map((block)=>this.removeContractDataFromDb(block)),
275
+ this.stores.logs.deleteLogs(blocksRemoved)
276
+ ]);
277
+ return opResults.every(Boolean);
278
+ });
279
+ await this.l2TipsCache?.refresh();
280
+ return result;
281
+ }
282
+ /**
283
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
284
+ * @param checkpointNumber - The checkpoint number to set as proven.
285
+ */ async setProvenCheckpointNumber(checkpointNumber) {
286
+ await this.stores.db.transactionAsync(async ()=>{
287
+ await this.stores.blocks.setProvenCheckpointNumber(checkpointNumber);
288
+ });
289
+ await this.l2TipsCache?.refresh();
290
+ }
291
+ /**
292
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
293
+ * @param checkpointNumber - The checkpoint number to set as finalized.
294
+ */ async setFinalizedCheckpointNumber(checkpointNumber) {
295
+ await this.stores.db.transactionAsync(async ()=>{
296
+ await this.stores.blocks.setFinalizedCheckpointNumber(checkpointNumber);
297
+ });
298
+ await this.l2TipsCache?.refresh();
299
+ }
300
+ /** Extracts and stores contract data from a single block. */ addContractDataToDb(block) {
301
+ return this.updateContractDataOnDb(block, 0);
302
+ }
303
+ /** Removes contract data associated with a block. */ removeContractDataFromDb(block) {
304
+ return this.updateContractDataOnDb(block, 1);
305
+ }
306
+ /** Adds or remove contract data associated with a block. */ async updateContractDataOnDb(block, operation) {
307
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
308
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
309
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
310
+ return (await Promise.all([
311
+ this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
312
+ this.updateDeployedContractInstances(privateLogs, block.number, operation),
313
+ this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation)
314
+ ])).every(Boolean);
315
+ }
316
+ /**
317
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
318
+ */ async updatePublishedContractClasses(allLogs, blockNum, operation) {
319
+ const contractClassPublishedEvents = allLogs.filter((log)=>ContractClassPublishedEvent.isContractClassPublishedEvent(log)).map((log)=>ContractClassPublishedEvent.fromLog(log));
320
+ if (operation == 1) {
321
+ const contractClasses = contractClassPublishedEvents.map((e)=>e.toContractClassPublic());
322
+ if (contractClasses.length > 0) {
323
+ contractClasses.forEach((c)=>this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
324
+ return await this.stores.contractClasses.deleteContractClasses(contractClasses, blockNum);
325
+ }
326
+ return true;
327
+ }
328
+ // Compute bytecode commitments and validate class IDs in a single pass.
329
+ const contractClasses = [];
330
+ for (const event of contractClassPublishedEvents){
331
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
332
+ const computedClassId = await computeContractClassId({
333
+ artifactHash: contractClass.artifactHash,
334
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
335
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment
336
+ });
337
+ if (!computedClassId.equals(contractClass.id)) {
338
+ this.log.warn(`Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`, {
339
+ blockNum,
340
+ contractClassId: event.contractClassId.toString()
341
+ });
342
+ continue;
343
+ }
344
+ contractClasses.push(contractClass);
345
+ }
346
+ if (contractClasses.length > 0) {
347
+ contractClasses.forEach((c)=>this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
348
+ return await this.stores.contractClasses.addContractClasses(contractClasses, blockNum);
349
+ }
350
+ return true;
351
+ }
352
+ /**
353
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
354
+ */ async updateDeployedContractInstances(allLogs, blockNum, operation) {
355
+ const allInstances = allLogs.filter((log)=>ContractInstancePublishedEvent.isContractInstancePublishedEvent(log)).map((log)=>ContractInstancePublishedEvent.fromLog(log)).map((e)=>e.toContractInstance());
356
+ // Verify that each instance's address matches the one derived from its fields if we're adding
357
+ const contractInstances = operation === 1 ? allInstances : await filterAsync(allInstances, async (instance)=>{
358
+ const computedAddress = await computeContractAddressFromInstance(instance);
359
+ if (!computedAddress.equals(instance.address)) {
360
+ this.log.warn(`Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`, {
361
+ instanceAddress: instance.address.toString(),
362
+ computedAddress: computedAddress.toString(),
363
+ blockNum
364
+ });
365
+ return false;
366
+ }
367
+ return true;
368
+ });
369
+ if (contractInstances.length > 0) {
370
+ contractInstances.forEach((c)=>this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`));
371
+ if (operation == 0) {
372
+ return await this.stores.contractInstances.addContractInstances(contractInstances, blockNum);
373
+ } else if (operation == 1) {
374
+ return await this.stores.contractInstances.deleteContractInstances(contractInstances);
375
+ }
376
+ }
377
+ return true;
378
+ }
379
+ /**
380
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
381
+ */ async updateUpdatedContractInstances(allLogs, timestamp, operation) {
382
+ const contractUpdates = allLogs.filter((log)=>ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log)).map((log)=>ContractInstanceUpdatedEvent.fromLog(log)).map((e)=>e.toContractInstanceUpdate());
383
+ if (contractUpdates.length > 0) {
384
+ contractUpdates.forEach((c)=>this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`));
385
+ if (operation == 0) {
386
+ return await this.stores.contractInstances.addContractInstanceUpdates(contractUpdates, timestamp);
387
+ } else if (operation == 1) {
388
+ return await this.stores.contractInstances.deleteContractInstanceUpdates(contractUpdates, timestamp);
389
+ }
390
+ }
391
+ return true;
392
+ }
393
+ }
@@ -0,0 +1,63 @@
1
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { L2Block } from '@aztec/stdlib/block';
3
+ import type { CheckpointData } from '@aztec/stdlib/checkpoint';
4
+ import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
5
+ import { type LmdbStatsCallback, type TelemetryClient, type Tracer } from '@aztec/telemetry-client';
6
+ export declare class ArchiverInstrumentation {
7
+ private telemetry;
8
+ readonly tracer: Tracer;
9
+ private blockHeight;
10
+ private checkpointHeight;
11
+ private txCount;
12
+ private l1BlockHeight;
13
+ private proofsSubmittedDelay;
14
+ private proofsSubmittedCount;
15
+ private dbMetrics;
16
+ private pruneDuration;
17
+ private pruneCount;
18
+ private syncDurationPerBlock;
19
+ private syncDurationPerCheckpoint;
20
+ private syncBlockCount;
21
+ private manaPerBlock;
22
+ private txsPerBlock;
23
+ private syncDurationPerMessage;
24
+ private syncMessageCount;
25
+ private blockProposalTxTargetCount;
26
+ private checkpointL1InclusionDelay;
27
+ private checkpointPromotedCount;
28
+ private log;
29
+ private constructor();
30
+ static new(telemetry: TelemetryClient, lmdbStats?: LmdbStatsCallback): Promise<ArchiverInstrumentation>;
31
+ isEnabled(): boolean;
32
+ processNewProposedBlock(syncTimePerBlock: number, block: L2Block): void;
33
+ processNewCheckpointedBlocks(syncTimePerCheckpoint: number, blocks: L2Block[]): void;
34
+ processNewMessages(count: number, syncPerMessageMs: number): void;
35
+ processPrune(duration: number): void;
36
+ /**
37
+ * Records a pending-chain reorg, where the archiver dropped proposed blocks (and world-state follows by pruning). The
38
+ * type distinguishes the cause: 'uncheckpointed' (slot ended without a checkpoint), 'l1_conflict' (proposed blocks
39
+ * conflicting with an L1 checkpoint), 'orphan' (no matching proposed checkpoint arrived before the deadline), or
40
+ * 'l1_mismatch' (the local checkpointed tip diverged from L1 — an L1 reorg or a pruned/missed-proof checkpoint — so
41
+ * already-checkpointed blocks were rewound).
42
+ */
43
+ recordPrune(pruneType: 'uncheckpointed' | 'l1_conflict' | 'orphan' | 'l1_mismatch'): void;
44
+ updateLastProvenCheckpoint(checkpoint: CheckpointData): void;
45
+ processProofsVerified(logs: {
46
+ proverId: string;
47
+ l2BlockNumber: bigint;
48
+ delay: bigint;
49
+ }[]): void;
50
+ updateL1BlockHeight(blockNumber: bigint): void;
51
+ recordBlockProposalTxTarget(target: string, usedTrace: boolean): void;
52
+ /** Records a checkpoint promoted from proposed (blob fetch skipped). */
53
+ processCheckpointPromoted(): void;
54
+ /**
55
+ * Records L1 inclusion timing for a checkpoint observed on L1 (seconds into the L2 slot).
56
+ */
57
+ processCheckpointL1Timing(data: {
58
+ slotNumber: SlotNumber;
59
+ l1Timestamp: bigint;
60
+ l1Constants: Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration'>;
61
+ }): void;
62
+ }
63
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5zdHJ1bWVudGF0aW9uLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbW9kdWxlcy9pbnN0cnVtZW50YXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLEVBQUUsVUFBVSxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFFbEUsT0FBTyxLQUFLLEVBQUUsT0FBTyxFQUFFLE1BQU0scUJBQXFCLENBQUM7QUFDbkQsT0FBTyxLQUFLLEVBQUUsY0FBYyxFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFDL0QsT0FBTyxLQUFLLEVBQUUsaUJBQWlCLEVBQUUsTUFBTSw2QkFBNkIsQ0FBQztBQUVyRSxPQUFPLEVBS0wsS0FBSyxpQkFBaUIsRUFFdEIsS0FBSyxlQUFlLEVBQ3BCLEtBQUssTUFBTSxFQUdaLE1BQU0seUJBQXlCLENBQUM7QUFFakMscUJBQWEsdUJBQXVCO0lBK0JoQyxPQUFPLENBQUMsU0FBUztJQ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,4BAA4B,CAAC,qBAAqB,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,QASnF;IAEM,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,QAMhE;IAEM,YAAY,CAAC,QAAQ,EAAE,MAAM,QAGnC;IAED;;;;;;OAMG;IACI,WAAW,CAAC,SAAS,EAAE,gBAAgB,GAAG,aAAa,GAAG,QAAQ,GAAG,aAAa,QAExF;IAEM,0BAA0B,CAAC,UAAU,EAAE,cAAc,QAI3D;IAEM,qBAAqB,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,QAW9F;IAEM,mBAAmB,CAAC,WAAW,EAAE,MAAM,QAE7C;IAEM,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,QAKpE;IAED,wEAAwE;IACjE,yBAAyB,SAE/B;IAED;;OAEG;IACI,yBAAyB,CAAC,IAAI,EAAE;QACrC,UAAU,EAAE,UAAU,CAAC;QACvB,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,IAAI,CAAC,iBAAiB,EAAE,eAAe,GAAG,cAAc,CAAC,CAAC;KACxE,GAAG,IAAI,CAIP;CACF"}
@@ -0,0 +1,166 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
3
+ import { Attributes, LmdbMetrics, Metrics, createUpDownCounterWithDefault } from '@aztec/telemetry-client';
4
+ export class ArchiverInstrumentation {
5
+ telemetry;
6
+ tracer;
7
+ blockHeight;
8
+ checkpointHeight;
9
+ txCount;
10
+ l1BlockHeight;
11
+ proofsSubmittedDelay;
12
+ proofsSubmittedCount;
13
+ dbMetrics;
14
+ pruneDuration;
15
+ pruneCount;
16
+ syncDurationPerBlock;
17
+ syncDurationPerCheckpoint;
18
+ syncBlockCount;
19
+ manaPerBlock;
20
+ txsPerBlock;
21
+ syncDurationPerMessage;
22
+ syncMessageCount;
23
+ blockProposalTxTargetCount;
24
+ checkpointL1InclusionDelay;
25
+ checkpointPromotedCount;
26
+ log;
27
+ constructor(telemetry, lmdbStats){
28
+ this.telemetry = telemetry;
29
+ this.log = createLogger('archiver:instrumentation');
30
+ this.tracer = telemetry.getTracer('Archiver');
31
+ const meter = telemetry.getMeter('Archiver');
32
+ this.blockHeight = meter.createGauge(Metrics.ARCHIVER_BLOCK_HEIGHT);
33
+ this.checkpointHeight = meter.createGauge(Metrics.ARCHIVER_CHECKPOINT_HEIGHT);
34
+ this.l1BlockHeight = meter.createGauge(Metrics.ARCHIVER_L1_BLOCK_HEIGHT);
35
+ this.txCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_TOTAL_TXS);
36
+ this.proofsSubmittedCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_ROLLUP_PROOF_COUNT, {
37
+ [Attributes.PROOF_TIMED_OUT]: [
38
+ true,
39
+ false
40
+ ]
41
+ });
42
+ this.proofsSubmittedDelay = meter.createHistogram(Metrics.ARCHIVER_ROLLUP_PROOF_DELAY);
43
+ this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK);
44
+ this.syncDurationPerCheckpoint = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_CHECKPOINT);
45
+ this.syncBlockCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
46
+ this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK);
47
+ this.txsPerBlock = meter.createHistogram(Metrics.ARCHIVER_TXS_PER_BLOCK);
48
+ this.syncDurationPerMessage = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_MESSAGE);
49
+ this.syncMessageCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_MESSAGE_COUNT);
50
+ this.pruneDuration = meter.createHistogram(Metrics.ARCHIVER_PRUNE_DURATION);
51
+ this.pruneCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_PRUNE_COUNT, {
52
+ [Attributes.PRUNE_TYPE]: [
53
+ 'unproven',
54
+ 'uncheckpointed',
55
+ 'l1_conflict',
56
+ 'orphan',
57
+ 'l1_mismatch'
58
+ ]
59
+ });
60
+ this.blockProposalTxTargetCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_BLOCK_PROPOSAL_TX_TARGET_COUNT, {
61
+ [Attributes.L1_BLOCK_PROPOSAL_USED_TRACE]: [
62
+ true,
63
+ false
64
+ ]
65
+ });
66
+ this.checkpointL1InclusionDelay = meter.createHistogram(Metrics.ARCHIVER_CHECKPOINT_L1_INCLUSION_DELAY);
67
+ this.checkpointPromotedCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_CHECKPOINT_PROMOTED_COUNT);
68
+ this.dbMetrics = new LmdbMetrics(meter, {
69
+ [Attributes.DB_DATA_TYPE]: 'archiver'
70
+ }, lmdbStats);
71
+ }
72
+ static async new(telemetry, lmdbStats) {
73
+ const instance = new ArchiverInstrumentation(telemetry, lmdbStats);
74
+ await instance.telemetry.flush();
75
+ return instance;
76
+ }
77
+ isEnabled() {
78
+ return this.telemetry.isEnabled();
79
+ }
80
+ processNewProposedBlock(syncTimePerBlock, block) {
81
+ const attrs = {
82
+ [Attributes.STATUS]: 'proposed'
83
+ };
84
+ this.blockHeight.record(block.number, attrs);
85
+ this.syncDurationPerBlock.record(Math.ceil(syncTimePerBlock));
86
+ // Per block metrics
87
+ this.txCount.add(block.body.txEffects.length);
88
+ this.txsPerBlock.record(block.body.txEffects.length);
89
+ this.manaPerBlock.record(block.header.totalManaUsed.toNumber() / 1e6);
90
+ }
91
+ processNewCheckpointedBlocks(syncTimePerCheckpoint, blocks) {
92
+ if (blocks.length === 0) {
93
+ return;
94
+ }
95
+ this.syncDurationPerCheckpoint.record(Math.ceil(syncTimePerCheckpoint));
96
+ this.blockHeight.record(Math.max(...blocks.map((b)=>b.number)), {
97
+ [Attributes.STATUS]: 'checkpointed'
98
+ });
99
+ this.checkpointHeight.record(Math.max(...blocks.map((b)=>b.checkpointNumber)));
100
+ this.syncBlockCount.add(blocks.length);
101
+ }
102
+ processNewMessages(count, syncPerMessageMs) {
103
+ if (count === 0) {
104
+ return;
105
+ }
106
+ this.syncMessageCount.add(count);
107
+ this.syncDurationPerMessage.record(Math.ceil(syncPerMessageMs));
108
+ }
109
+ processPrune(duration) {
110
+ this.pruneCount.add(1, {
111
+ [Attributes.PRUNE_TYPE]: 'unproven'
112
+ });
113
+ this.pruneDuration.record(Math.ceil(duration));
114
+ }
115
+ /**
116
+ * Records a pending-chain reorg, where the archiver dropped proposed blocks (and world-state follows by pruning). The
117
+ * type distinguishes the cause: 'uncheckpointed' (slot ended without a checkpoint), 'l1_conflict' (proposed blocks
118
+ * conflicting with an L1 checkpoint), 'orphan' (no matching proposed checkpoint arrived before the deadline), or
119
+ * 'l1_mismatch' (the local checkpointed tip diverged from L1 — an L1 reorg or a pruned/missed-proof checkpoint — so
120
+ * already-checkpointed blocks were rewound).
121
+ */ recordPrune(pruneType) {
122
+ this.pruneCount.add(1, {
123
+ [Attributes.PRUNE_TYPE]: pruneType
124
+ });
125
+ }
126
+ updateLastProvenCheckpoint(checkpoint) {
127
+ const lastBlockNumberInCheckpoint = checkpoint.startBlock + checkpoint.blockCount - 1;
128
+ this.blockHeight.record(lastBlockNumberInCheckpoint, {
129
+ [Attributes.STATUS]: 'proven'
130
+ });
131
+ this.checkpointHeight.record(checkpoint.checkpointNumber, {
132
+ [Attributes.STATUS]: 'proven'
133
+ });
134
+ }
135
+ processProofsVerified(logs) {
136
+ for (const log of logs){
137
+ this.log.debug('Recording proof verified event', log);
138
+ this.proofsSubmittedCount.add(1, {
139
+ [Attributes.ROLLUP_PROVER_ID]: log.proverId,
140
+ [Attributes.PROOF_TIMED_OUT]: log.delay > 20n * 60n * 1000n
141
+ });
142
+ this.proofsSubmittedDelay.record(Math.ceil(Number(log.delay)), {
143
+ [Attributes.ROLLUP_PROVER_ID]: log.proverId
144
+ });
145
+ }
146
+ }
147
+ updateL1BlockHeight(blockNumber) {
148
+ this.l1BlockHeight.record(Number(blockNumber));
149
+ }
150
+ recordBlockProposalTxTarget(target, usedTrace) {
151
+ this.blockProposalTxTargetCount.add(1, {
152
+ [Attributes.L1_BLOCK_PROPOSAL_TX_TARGET]: target.toLowerCase(),
153
+ [Attributes.L1_BLOCK_PROPOSAL_USED_TRACE]: usedTrace
154
+ });
155
+ }
156
+ /** Records a checkpoint promoted from proposed (blob fetch skipped). */ processCheckpointPromoted() {
157
+ this.checkpointPromotedCount.add(1);
158
+ }
159
+ /**
160
+ * Records L1 inclusion timing for a checkpoint observed on L1 (seconds into the L2 slot).
161
+ */ processCheckpointL1Timing(data) {
162
+ const slotStartTs = getTimestampForSlot(data.slotNumber, data.l1Constants);
163
+ const inclusionDelaySeconds = Number(data.l1Timestamp - slotStartTs);
164
+ this.checkpointL1InclusionDelay.record(inclusionDelaySeconds);
165
+ }
166
+ }