@aztec/archiver 0.0.1-commit.fcb71a6 → 0.0.1-commit.ff7989d6c

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 (200) hide show
  1. package/README.md +156 -22
  2. package/dest/archiver.d.ts +139 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +699 -0
  5. package/dest/{archiver/config.d.ts → config.d.ts} +9 -1
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +11 -2
  8. package/dest/errors.d.ts +41 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/{archiver/errors.js → errors.js} +8 -0
  11. package/dest/factory.d.ts +9 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +94 -11
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -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/{archiver/l1 → l1}/bin/retrieve-calldata.d.ts +1 -1
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.js +17 -18
  23. package/dest/{archiver/l1 → l1}/calldata_retriever.d.ts +9 -3
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/{archiver/l1 → l1}/calldata_retriever.js +19 -6
  26. package/dest/l1/data_retrieval.d.ts +89 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver/l1 → l1}/data_retrieval.js +39 -57
  29. package/dest/{archiver/l1 → l1}/debug_tx.d.ts +1 -1
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/{archiver/l1 → l1}/spire_proposer.d.ts +1 -1
  32. package/dest/l1/spire_proposer.d.ts.map +1 -0
  33. package/dest/{archiver/l1 → l1}/trace_tx.d.ts +1 -1
  34. package/dest/l1/trace_tx.d.ts.map +1 -0
  35. package/dest/l1/types.d.ts +12 -0
  36. package/dest/l1/types.d.ts.map +1 -0
  37. package/dest/{archiver/l1 → l1}/validate_trace.d.ts +6 -3
  38. package/dest/l1/validate_trace.d.ts.map +1 -0
  39. package/dest/{archiver/l1 → l1}/validate_trace.js +14 -10
  40. package/dest/modules/data_source_base.d.ts +89 -0
  41. package/dest/modules/data_source_base.d.ts.map +1 -0
  42. package/dest/modules/data_source_base.js +216 -0
  43. package/dest/modules/data_store_updater.d.ts +80 -0
  44. package/dest/modules/data_store_updater.d.ts.map +1 -0
  45. package/dest/modules/data_store_updater.js +323 -0
  46. package/dest/modules/instrumentation.d.ts +39 -0
  47. package/dest/modules/instrumentation.d.ts.map +1 -0
  48. package/dest/{archiver → modules}/instrumentation.js +33 -67
  49. package/dest/modules/l1_synchronizer.d.ts +76 -0
  50. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  51. package/dest/modules/l1_synchronizer.js +1112 -0
  52. package/dest/modules/validation.d.ts +17 -0
  53. package/dest/modules/validation.d.ts.map +1 -0
  54. package/dest/{archiver → modules}/validation.js +7 -1
  55. package/dest/store/block_store.d.ts +196 -0
  56. package/dest/store/block_store.d.ts.map +1 -0
  57. package/dest/{archiver/kv_archiver_store → store}/block_store.js +228 -62
  58. package/dest/store/contract_class_store.d.ts +18 -0
  59. package/dest/store/contract_class_store.d.ts.map +1 -0
  60. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +12 -8
  61. package/dest/store/contract_instance_store.d.ts +24 -0
  62. package/dest/store/contract_instance_store.d.ts.map +1 -0
  63. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  64. package/dest/store/kv_archiver_store.d.ts +354 -0
  65. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  66. package/dest/store/kv_archiver_store.js +464 -0
  67. package/dest/store/l2_tips_cache.d.ts +19 -0
  68. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  69. package/dest/store/l2_tips_cache.js +89 -0
  70. package/dest/store/log_store.d.ts +54 -0
  71. package/dest/store/log_store.d.ts.map +1 -0
  72. package/dest/{archiver/kv_archiver_store → store}/log_store.js +146 -91
  73. package/dest/{archiver/kv_archiver_store → store}/message_store.d.ts +1 -1
  74. package/dest/store/message_store.d.ts.map +1 -0
  75. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  76. package/dest/structs/data_retrieval.d.ts.map +1 -0
  77. package/dest/structs/inbox_message.d.ts +15 -0
  78. package/dest/structs/inbox_message.d.ts.map +1 -0
  79. package/dest/{archiver/structs → structs}/published.d.ts +1 -1
  80. package/dest/structs/published.d.ts.map +1 -0
  81. package/dest/test/fake_l1_state.d.ts +193 -0
  82. package/dest/test/fake_l1_state.d.ts.map +1 -0
  83. package/dest/test/fake_l1_state.js +389 -0
  84. package/dest/test/index.d.ts +2 -1
  85. package/dest/test/index.d.ts.map +1 -1
  86. package/dest/test/index.js +4 -1
  87. package/dest/test/mock_archiver.d.ts +2 -2
  88. package/dest/test/mock_archiver.d.ts.map +1 -1
  89. package/dest/test/mock_archiver.js +3 -3
  90. package/dest/test/mock_l1_to_l2_message_source.d.ts +2 -2
  91. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  92. package/dest/test/mock_l1_to_l2_message_source.js +12 -3
  93. package/dest/test/mock_l2_block_source.d.ts +39 -17
  94. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  95. package/dest/test/mock_l2_block_source.js +232 -83
  96. package/dest/test/mock_structs.d.ts +78 -3
  97. package/dest/test/mock_structs.d.ts.map +1 -1
  98. package/dest/test/mock_structs.js +140 -7
  99. package/dest/test/noop_l1_archiver.d.ts +23 -0
  100. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  101. package/dest/test/noop_l1_archiver.js +68 -0
  102. package/package.json +16 -17
  103. package/src/archiver.ts +443 -0
  104. package/src/{archiver/config.ts → config.ts} +13 -2
  105. package/src/{archiver/errors.ts → errors.ts} +12 -0
  106. package/src/factory.ts +140 -11
  107. package/src/index.ts +11 -3
  108. package/src/interfaces.ts +9 -0
  109. package/src/{archiver/l1 → l1}/bin/retrieve-calldata.ts +16 -17
  110. package/src/{archiver/l1 → l1}/calldata_retriever.ts +28 -6
  111. package/src/{archiver/l1 → l1}/data_retrieval.ts +60 -74
  112. package/src/{archiver/l1 → l1}/validate_trace.ts +25 -7
  113. package/src/modules/data_source_base.ts +328 -0
  114. package/src/modules/data_store_updater.ts +448 -0
  115. package/src/{archiver → modules}/instrumentation.ts +33 -70
  116. package/src/modules/l1_synchronizer.ts +932 -0
  117. package/src/{archiver → modules}/validation.ts +11 -6
  118. package/src/{archiver/kv_archiver_store → store}/block_store.ts +293 -100
  119. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +12 -8
  120. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +1 -1
  121. package/src/{archiver/kv_archiver_store → store}/kv_archiver_store.ts +273 -40
  122. package/src/store/l2_tips_cache.ts +89 -0
  123. package/src/{archiver/kv_archiver_store → store}/log_store.ts +242 -121
  124. package/src/test/fake_l1_state.ts +607 -0
  125. package/src/test/index.ts +4 -0
  126. package/src/test/mock_archiver.ts +4 -3
  127. package/src/test/mock_l1_to_l2_message_source.ts +10 -4
  128. package/src/test/mock_l2_block_source.ts +276 -90
  129. package/src/test/mock_structs.ts +269 -8
  130. package/src/test/noop_l1_archiver.ts +109 -0
  131. package/dest/archiver/archiver.d.ts +0 -304
  132. package/dest/archiver/archiver.d.ts.map +0 -1
  133. package/dest/archiver/archiver.js +0 -1645
  134. package/dest/archiver/archiver_store.d.ts +0 -308
  135. package/dest/archiver/archiver_store.d.ts.map +0 -1
  136. package/dest/archiver/archiver_store.js +0 -4
  137. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  138. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  139. package/dest/archiver/archiver_store_test_suite.js +0 -2770
  140. package/dest/archiver/config.d.ts.map +0 -1
  141. package/dest/archiver/errors.d.ts +0 -36
  142. package/dest/archiver/errors.d.ts.map +0 -1
  143. package/dest/archiver/index.d.ts +0 -7
  144. package/dest/archiver/index.d.ts.map +0 -1
  145. package/dest/archiver/index.js +0 -4
  146. package/dest/archiver/instrumentation.d.ts +0 -37
  147. package/dest/archiver/instrumentation.d.ts.map +0 -1
  148. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -157
  149. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  150. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  151. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  152. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  153. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  154. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -158
  155. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  156. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -313
  157. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -45
  158. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  159. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  160. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +0 -1
  161. package/dest/archiver/l1/calldata_retriever.d.ts.map +0 -1
  162. package/dest/archiver/l1/data_retrieval.d.ts +0 -90
  163. package/dest/archiver/l1/data_retrieval.d.ts.map +0 -1
  164. package/dest/archiver/l1/debug_tx.d.ts.map +0 -1
  165. package/dest/archiver/l1/spire_proposer.d.ts.map +0 -1
  166. package/dest/archiver/l1/trace_tx.d.ts.map +0 -1
  167. package/dest/archiver/l1/types.d.ts +0 -12
  168. package/dest/archiver/l1/types.d.ts.map +0 -1
  169. package/dest/archiver/l1/validate_trace.d.ts.map +0 -1
  170. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  171. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  172. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  173. package/dest/archiver/structs/published.d.ts.map +0 -1
  174. package/dest/archiver/validation.d.ts +0 -17
  175. package/dest/archiver/validation.d.ts.map +0 -1
  176. package/dest/rpc/index.d.ts +0 -9
  177. package/dest/rpc/index.d.ts.map +0 -1
  178. package/dest/rpc/index.js +0 -15
  179. package/src/archiver/archiver.ts +0 -2157
  180. package/src/archiver/archiver_store.ts +0 -372
  181. package/src/archiver/archiver_store_test_suite.ts +0 -2843
  182. package/src/archiver/index.ts +0 -6
  183. package/src/rpc/index.ts +0 -16
  184. /package/dest/{archiver/l1 → l1}/debug_tx.js +0 -0
  185. /package/dest/{archiver/l1 → l1}/spire_proposer.js +0 -0
  186. /package/dest/{archiver/l1 → l1}/trace_tx.js +0 -0
  187. /package/dest/{archiver/l1 → l1}/types.js +0 -0
  188. /package/dest/{archiver/kv_archiver_store → store}/message_store.js +0 -0
  189. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  190. /package/dest/{archiver/structs → structs}/inbox_message.js +0 -0
  191. /package/dest/{archiver/structs → structs}/published.js +0 -0
  192. /package/src/{archiver/l1 → l1}/README.md +0 -0
  193. /package/src/{archiver/l1 → l1}/debug_tx.ts +0 -0
  194. /package/src/{archiver/l1 → l1}/spire_proposer.ts +0 -0
  195. /package/src/{archiver/l1 → l1}/trace_tx.ts +0 -0
  196. /package/src/{archiver/l1 → l1}/types.ts +0 -0
  197. /package/src/{archiver/kv_archiver_store → store}/message_store.ts +0 -0
  198. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
  199. /package/src/{archiver/structs → structs}/inbox_message.ts +0 -0
  200. /package/src/{archiver/structs → structs}/published.ts +0 -0
@@ -0,0 +1,216 @@
1
+ import { range } from '@aztec/foundation/array';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { isDefined } from '@aztec/foundation/types';
4
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
5
+ import { getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
6
+ /**
7
+ * Abstract base class implementing ArchiverDataSource using a KVArchiverDataStore.
8
+ * Provides implementations for all store-delegating methods and declares abstract methods
9
+ * for L1-dependent functionality that subclasses must implement.
10
+ */ export class ArchiverDataSourceBase {
11
+ store;
12
+ l1Constants;
13
+ constructor(store, l1Constants){
14
+ this.store = store;
15
+ this.l1Constants = l1Constants;
16
+ }
17
+ getCheckpointNumber() {
18
+ return this.store.getSynchedCheckpointNumber();
19
+ }
20
+ getSynchedCheckpointNumber() {
21
+ return this.store.getSynchedCheckpointNumber();
22
+ }
23
+ getProvenCheckpointNumber() {
24
+ return this.store.getProvenCheckpointNumber();
25
+ }
26
+ getBlockNumber() {
27
+ return this.store.getLatestBlockNumber();
28
+ }
29
+ getProvenBlockNumber() {
30
+ return this.store.getProvenBlockNumber();
31
+ }
32
+ async getBlockHeader(number) {
33
+ const blockNumber = number === 'latest' ? await this.store.getLatestBlockNumber() : number;
34
+ if (blockNumber === 0) {
35
+ return undefined;
36
+ }
37
+ const headers = await this.store.getBlockHeaders(blockNumber, 1);
38
+ return headers.length === 0 ? undefined : headers[0];
39
+ }
40
+ getCheckpointedBlock(number) {
41
+ return this.store.getCheckpointedBlock(number);
42
+ }
43
+ getCheckpointedL2BlockNumber() {
44
+ return this.store.getCheckpointedL2BlockNumber();
45
+ }
46
+ getFinalizedL2BlockNumber() {
47
+ return this.store.getFinalizedL2BlockNumber();
48
+ }
49
+ async getCheckpointHeader(number) {
50
+ if (number === 'latest') {
51
+ number = await this.store.getSynchedCheckpointNumber();
52
+ }
53
+ if (number === 0) {
54
+ return undefined;
55
+ }
56
+ const checkpoint = await this.store.getCheckpointData(number);
57
+ if (!checkpoint) {
58
+ return undefined;
59
+ }
60
+ return checkpoint.header;
61
+ }
62
+ async getLastBlockNumberInCheckpoint(checkpointNumber) {
63
+ const checkpointData = await this.store.getCheckpointData(checkpointNumber);
64
+ if (!checkpointData) {
65
+ return undefined;
66
+ }
67
+ return BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
68
+ }
69
+ getCheckpointedBlocks(from, limit) {
70
+ return this.store.getCheckpointedBlocks(from, limit);
71
+ }
72
+ getBlockHeaderByHash(blockHash) {
73
+ return this.store.getBlockHeaderByHash(blockHash);
74
+ }
75
+ getBlockHeaderByArchive(archive) {
76
+ return this.store.getBlockHeaderByArchive(archive);
77
+ }
78
+ getBlockData(number) {
79
+ return this.store.getBlockData(number);
80
+ }
81
+ getBlockDataByArchive(archive) {
82
+ return this.store.getBlockDataByArchive(archive);
83
+ }
84
+ async getL2Block(number) {
85
+ // If the number provided is -ve, then return the latest block.
86
+ if (number < 0) {
87
+ number = await this.store.getLatestBlockNumber();
88
+ }
89
+ if (number === 0) {
90
+ return undefined;
91
+ }
92
+ const publishedBlock = await this.store.getBlock(number);
93
+ return publishedBlock;
94
+ }
95
+ getTxEffect(txHash) {
96
+ return this.store.getTxEffect(txHash);
97
+ }
98
+ getSettledTxReceipt(txHash) {
99
+ return this.store.getSettledTxReceipt(txHash);
100
+ }
101
+ isPendingChainInvalid() {
102
+ return this.getPendingChainValidationStatus().then((status)=>!status.valid);
103
+ }
104
+ async getPendingChainValidationStatus() {
105
+ return await this.store.getPendingChainValidationStatus() ?? {
106
+ valid: true
107
+ };
108
+ }
109
+ getPrivateLogsByTags(tags, page) {
110
+ return this.store.getPrivateLogsByTags(tags, page);
111
+ }
112
+ getPublicLogsByTagsFromContract(contractAddress, tags, page) {
113
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags, page);
114
+ }
115
+ getPublicLogs(filter) {
116
+ return this.store.getPublicLogs(filter);
117
+ }
118
+ getContractClassLogs(filter) {
119
+ return this.store.getContractClassLogs(filter);
120
+ }
121
+ getContractClass(id) {
122
+ return this.store.getContractClass(id);
123
+ }
124
+ getBytecodeCommitment(id) {
125
+ return this.store.getBytecodeCommitment(id);
126
+ }
127
+ async getContract(address, maybeTimestamp) {
128
+ let timestamp;
129
+ if (maybeTimestamp === undefined) {
130
+ const latestBlockHeader = await this.getBlockHeader('latest');
131
+ // If we get undefined block header, it means that the archiver has not yet synced any block so we default to 0.
132
+ timestamp = latestBlockHeader ? latestBlockHeader.globalVariables.timestamp : 0n;
133
+ } else {
134
+ timestamp = maybeTimestamp;
135
+ }
136
+ return this.store.getContractInstance(address, timestamp);
137
+ }
138
+ getContractClassIds() {
139
+ return this.store.getContractClassIds();
140
+ }
141
+ getDebugFunctionName(address, selector) {
142
+ return this.store.getDebugFunctionName(address, selector);
143
+ }
144
+ registerContractFunctionSignatures(signatures) {
145
+ return this.store.registerContractFunctionSignatures(signatures);
146
+ }
147
+ getL1ToL2Messages(checkpointNumber) {
148
+ return this.store.getL1ToL2Messages(checkpointNumber);
149
+ }
150
+ getL1ToL2MessageIndex(l1ToL2Message) {
151
+ return this.store.getL1ToL2MessageIndex(l1ToL2Message);
152
+ }
153
+ async getCheckpoints(checkpointNumber, limit) {
154
+ const checkpoints = await this.store.getRangeOfCheckpoints(checkpointNumber, limit);
155
+ return Promise.all(checkpoints.map((ch)=>this.getPublishedCheckpointFromCheckpointData(ch)));
156
+ }
157
+ async getPublishedCheckpointFromCheckpointData(checkpoint) {
158
+ const blocksForCheckpoint = await this.store.getBlocksForCheckpoint(checkpoint.checkpointNumber);
159
+ if (!blocksForCheckpoint) {
160
+ throw new Error(`Blocks for checkpoint ${checkpoint.checkpointNumber} not found`);
161
+ }
162
+ const fullCheckpoint = new Checkpoint(checkpoint.archive, checkpoint.header, blocksForCheckpoint, checkpoint.checkpointNumber);
163
+ return new PublishedCheckpoint(fullCheckpoint, checkpoint.l1, checkpoint.attestations);
164
+ }
165
+ getBlocksForSlot(slotNumber) {
166
+ return this.store.getBlocksForSlot(slotNumber);
167
+ }
168
+ async getCheckpointedBlocksForEpoch(epochNumber) {
169
+ const checkpointsData = await this.getCheckpointsDataForEpoch(epochNumber);
170
+ const blocks = await Promise.all(checkpointsData.flatMap((checkpoint)=>range(checkpoint.blockCount, checkpoint.startBlock).map((blockNumber)=>this.getCheckpointedBlock(BlockNumber(blockNumber)))));
171
+ return blocks.filter(isDefined);
172
+ }
173
+ async getCheckpointedBlockHeadersForEpoch(epochNumber) {
174
+ const checkpointsData = await this.getCheckpointsDataForEpoch(epochNumber);
175
+ const blocks = await Promise.all(checkpointsData.flatMap((checkpoint)=>range(checkpoint.blockCount, checkpoint.startBlock).map((blockNumber)=>this.getBlockHeader(BlockNumber(blockNumber)))));
176
+ return blocks.filter(isDefined);
177
+ }
178
+ async getCheckpointsForEpoch(epochNumber) {
179
+ const checkpointsData = await this.getCheckpointsDataForEpoch(epochNumber);
180
+ return Promise.all(checkpointsData.map((data)=>this.getPublishedCheckpointFromCheckpointData(data).then((p)=>p.checkpoint)));
181
+ }
182
+ /** Returns checkpoint data for all checkpoints whose slot falls within the given epoch. */ getCheckpointsDataForEpoch(epochNumber) {
183
+ if (!this.l1Constants) {
184
+ throw new Error('L1 constants not set');
185
+ }
186
+ const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
187
+ return this.store.getCheckpointDataForSlotRange(start, end);
188
+ }
189
+ async getBlock(number) {
190
+ // If the number provided is -ve, then return the latest block.
191
+ if (number < 0) {
192
+ number = await this.store.getLatestBlockNumber();
193
+ }
194
+ if (number === 0) {
195
+ return undefined;
196
+ }
197
+ return this.store.getBlock(number);
198
+ }
199
+ getBlocks(from, limit) {
200
+ return this.store.getBlocks(from, limit);
201
+ }
202
+ getCheckpointedBlockByHash(blockHash) {
203
+ return this.store.getCheckpointedBlockByHash(blockHash);
204
+ }
205
+ getCheckpointedBlockByArchive(archive) {
206
+ return this.store.getCheckpointedBlockByArchive(archive);
207
+ }
208
+ async getL2BlockByHash(blockHash) {
209
+ const checkpointedBlock = await this.store.getCheckpointedBlockByHash(blockHash);
210
+ return checkpointedBlock?.block;
211
+ }
212
+ async getL2BlockByArchive(archive) {
213
+ const checkpointedBlock = await this.store.getCheckpointedBlockByArchive(archive);
214
+ return checkpointedBlock?.block;
215
+ }
216
+ }
@@ -0,0 +1,80 @@
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
3
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
4
+ import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
5
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
6
+ /** Result of adding checkpoints with information about any pruned blocks. */
7
+ type ReconcileCheckpointsResult = {
8
+ /** Blocks that were pruned due to conflict with L1 checkpoints. */
9
+ prunedBlocks: L2Block[] | undefined;
10
+ /** Last block number that was already inserted locally, or undefined if none. */
11
+ lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
12
+ };
13
+ /** Archiver helper module to handle updates to the data store. */
14
+ export declare class ArchiverDataStoreUpdater {
15
+ private store;
16
+ private l2TipsCache?;
17
+ private readonly log;
18
+ constructor(store: KVArchiverDataStore, l2TipsCache?: L2TipsCache | undefined);
19
+ /**
20
+ * Adds proposed blocks to the store with contract class/instance extraction from logs.
21
+ * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
22
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
23
+ * and individually broadcasted functions from the block logs.
24
+ *
25
+ * @param blocks - The proposed L2 blocks to add.
26
+ * @param pendingChainValidationStatus - Optional validation status to set.
27
+ * @returns True if the operation is successful.
28
+ */
29
+ addProposedBlocks(blocks: L2Block[], pendingChainValidationStatus?: ValidateCheckpointResult): Promise<boolean>;
30
+ /**
31
+ * Reconciles local blocks with incoming checkpoints from L1.
32
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
33
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
34
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
35
+ * and individually broadcasted functions from the checkpoint block logs.
36
+ *
37
+ * @param checkpoints - The published checkpoints to add.
38
+ * @param pendingChainValidationStatus - Optional validation status to set.
39
+ * @returns Result with information about any pruned blocks.
40
+ */
41
+ addCheckpoints(checkpoints: PublishedCheckpoint[], pendingChainValidationStatus?: ValidateCheckpointResult): Promise<ReconcileCheckpointsResult>;
42
+ private pruneMismatchingLocalBlocks;
43
+ /**
44
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
45
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
46
+ * Verifies that each block being removed is not part of a stored checkpoint.
47
+ *
48
+ * @param blockNumber - Remove all blocks with number greater than this.
49
+ * @returns The removed blocks.
50
+ * @throws Error if any block to be removed is checkpointed.
51
+ */
52
+ removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]>;
53
+ private removeBlocksAfter;
54
+ /**
55
+ * Removes all checkpoints after the given checkpoint number.
56
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
57
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
58
+ * and uncheckpointed) after the last block of the given checkpoint.
59
+ *
60
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
61
+ * @returns True if the operation is successful.
62
+ */
63
+ removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean>;
64
+ /**
65
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
66
+ * @param checkpointNumber - The checkpoint number to set as proven.
67
+ */
68
+ setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void>;
69
+ /** Extracts and stores contract data from a single block. */
70
+ private addContractDataToDb;
71
+ /** Removes contract data associated with a block. */
72
+ private removeContractDataFromDb;
73
+ private updateContractDataOnDb;
74
+ private updatePublishedContractClasses;
75
+ private updateDeployedContractInstances;
76
+ private updateUpdatedContractInstances;
77
+ private storeBroadcastedIndividualFunctions;
78
+ }
79
+ export {};
80
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGF0YV9zdG9yZV91cGRhdGVyLmQud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D"}
@@ -0,0 +1,323 @@
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import { ContractClassPublishedEvent, PrivateFunctionBroadcastedEvent, UtilityFunctionBroadcastedEvent } from '@aztec/protocol-contracts/class-registry';
5
+ import { ContractInstancePublishedEvent, ContractInstanceUpdatedEvent } from '@aztec/protocol-contracts/instance-registry';
6
+ import { computePublicBytecodeCommitment, isValidPrivateFunctionMembershipProof, isValidUtilityFunctionMembershipProof } from '@aztec/stdlib/contract';
7
+ import groupBy from 'lodash.groupby';
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
+ store;
15
+ l2TipsCache;
16
+ log;
17
+ constructor(store, l2TipsCache){
18
+ this.store = store;
19
+ this.l2TipsCache = l2TipsCache;
20
+ this.log = createLogger('archiver:store_updater');
21
+ }
22
+ /**
23
+ * Adds proposed blocks to the store with contract class/instance extraction from logs.
24
+ * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
25
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
26
+ * and individually broadcasted functions from the block logs.
27
+ *
28
+ * @param blocks - The proposed L2 blocks to add.
29
+ * @param pendingChainValidationStatus - Optional validation status to set.
30
+ * @returns True if the operation is successful.
31
+ */ async addProposedBlocks(blocks, pendingChainValidationStatus) {
32
+ const result = await this.store.transactionAsync(async ()=>{
33
+ await this.store.addProposedBlocks(blocks);
34
+ const opResults = await Promise.all([
35
+ // Update the pending chain validation status if provided
36
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
37
+ // Add any logs emitted during the retrieved blocks
38
+ this.store.addLogs(blocks),
39
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
40
+ ...blocks.map((block)=>this.addContractDataToDb(block))
41
+ ]);
42
+ await this.l2TipsCache?.refresh();
43
+ return opResults.every(Boolean);
44
+ });
45
+ return result;
46
+ }
47
+ /**
48
+ * Reconciles local blocks with incoming checkpoints from L1.
49
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
50
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
51
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
52
+ * and individually broadcasted functions from the checkpoint block logs.
53
+ *
54
+ * @param checkpoints - The published checkpoints to add.
55
+ * @param pendingChainValidationStatus - Optional validation status to set.
56
+ * @returns Result with information about any pruned blocks.
57
+ */ async addCheckpoints(checkpoints, pendingChainValidationStatus) {
58
+ const result = await this.store.transactionAsync(async ()=>{
59
+ // Before adding checkpoints, check for conflicts with local blocks if any
60
+ const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
61
+ await this.store.addCheckpoints(checkpoints);
62
+ // Filter out blocks that were already inserted via addProposedBlocks() to avoid duplicating logs/contract data
63
+ const newBlocks = checkpoints.flatMap((ch)=>ch.checkpoint.blocks).filter((b)=>lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
64
+ await Promise.all([
65
+ // Update the pending chain validation status if provided
66
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
67
+ // Add any logs emitted during the retrieved blocks
68
+ this.store.addLogs(newBlocks),
69
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
70
+ ...newBlocks.map((block)=>this.addContractDataToDb(block))
71
+ ]);
72
+ await this.l2TipsCache?.refresh();
73
+ return {
74
+ prunedBlocks,
75
+ lastAlreadyInsertedBlockNumber
76
+ };
77
+ });
78
+ return result;
79
+ }
80
+ /**
81
+ * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
82
+ * This method handles multiple checkpoints but returns after pruning the first conflict found.
83
+ * This is correct because pruning from the first conflict point removes all subsequent blocks,
84
+ * and when checkpoints are added afterward, they include all the correct blocks.
85
+ */ async pruneMismatchingLocalBlocks(checkpoints) {
86
+ const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
87
+ this.store.getCheckpointedL2BlockNumber(),
88
+ this.store.getLatestBlockNumber()
89
+ ]);
90
+ // Exit early if there are no local uncheckpointed blocks
91
+ if (lastBlockNumber === lastCheckpointedBlockNumber) {
92
+ return {
93
+ prunedBlocks: undefined,
94
+ lastAlreadyInsertedBlockNumber: undefined
95
+ };
96
+ }
97
+ // Get all uncheckpointed local blocks
98
+ const uncheckpointedLocalBlocks = await this.store.getBlocks(BlockNumber.add(lastCheckpointedBlockNumber, 1), lastBlockNumber - lastCheckpointedBlockNumber);
99
+ let lastAlreadyInsertedBlockNumber;
100
+ for (const publishedCheckpoint of checkpoints){
101
+ const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
102
+ const slot = publishedCheckpoint.checkpoint.slot;
103
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter((b)=>b.slot === slot);
104
+ if (checkpointBlocks.length === 0) {
105
+ this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
106
+ continue;
107
+ }
108
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards
109
+ for (const checkpointBlock of checkpointBlocks){
110
+ const blockNumber = checkpointBlock.number;
111
+ const existingBlock = localBlocksInSlot.find((b)=>b.number === blockNumber);
112
+ const blockInfos = {
113
+ existingBlock: existingBlock?.toBlockInfo(),
114
+ checkpointBlock: checkpointBlock.toBlockInfo()
115
+ };
116
+ if (!existingBlock) {
117
+ this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`, blockInfos);
118
+ } else if (existingBlock.archive.root.equals(checkpointBlock.archive.root)) {
119
+ this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
120
+ lastAlreadyInsertedBlockNumber = blockNumber;
121
+ } else {
122
+ this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
123
+ const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
124
+ return {
125
+ prunedBlocks,
126
+ lastAlreadyInsertedBlockNumber
127
+ };
128
+ }
129
+ }
130
+ // If local has more blocks than the checkpoint (e.g., local has [2,3,4] but checkpoint has [2,3]),
131
+ // we need to prune the extra local blocks so they match what was checkpointed
132
+ const lastCheckpointBlockNumber = checkpointBlocks.at(-1).number;
133
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.number;
134
+ if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
135
+ this.log.warn(`Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`);
136
+ const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
137
+ return {
138
+ prunedBlocks,
139
+ lastAlreadyInsertedBlockNumber
140
+ };
141
+ }
142
+ }
143
+ return {
144
+ prunedBlocks: undefined,
145
+ lastAlreadyInsertedBlockNumber
146
+ };
147
+ }
148
+ /**
149
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
150
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
151
+ * Verifies that each block being removed is not part of a stored checkpoint.
152
+ *
153
+ * @param blockNumber - Remove all blocks with number greater than this.
154
+ * @returns The removed blocks.
155
+ * @throws Error if any block to be removed is checkpointed.
156
+ */ async removeUncheckpointedBlocksAfter(blockNumber) {
157
+ const result = await this.store.transactionAsync(async ()=>{
158
+ // Verify we're only removing uncheckpointed blocks
159
+ const lastCheckpointedBlockNumber = await this.store.getCheckpointedL2BlockNumber();
160
+ if (blockNumber < lastCheckpointedBlockNumber) {
161
+ throw new Error(`Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`);
162
+ }
163
+ const result = await this.removeBlocksAfter(blockNumber);
164
+ await this.l2TipsCache?.refresh();
165
+ return result;
166
+ });
167
+ return result;
168
+ }
169
+ /**
170
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
171
+ * Does not remove their checkpoints.
172
+ */ async removeBlocksAfter(blockNumber) {
173
+ // First get the blocks to be removed so we can clean up contract data
174
+ const removedBlocks = await this.store.removeBlocksAfter(blockNumber);
175
+ // Clean up contract data and logs for the removed blocks
176
+ await Promise.all([
177
+ this.store.deleteLogs(removedBlocks),
178
+ ...removedBlocks.map((block)=>this.removeContractDataFromDb(block))
179
+ ]);
180
+ return removedBlocks;
181
+ }
182
+ /**
183
+ * Removes all checkpoints after the given checkpoint number.
184
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
185
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
186
+ * and uncheckpointed) after the last block of the given checkpoint.
187
+ *
188
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
189
+ * @returns True if the operation is successful.
190
+ */ async removeCheckpointsAfter(checkpointNumber) {
191
+ return await this.store.transactionAsync(async ()=>{
192
+ const { blocksRemoved = [] } = await this.store.removeCheckpointsAfter(checkpointNumber);
193
+ const opResults = await Promise.all([
194
+ // Prune rolls back to the last proven block, which is by definition valid
195
+ this.store.setPendingChainValidationStatus({
196
+ valid: true
197
+ }),
198
+ // Remove contract data for all blocks being removed
199
+ ...blocksRemoved.map((block)=>this.removeContractDataFromDb(block)),
200
+ this.store.deleteLogs(blocksRemoved)
201
+ ]);
202
+ await this.l2TipsCache?.refresh();
203
+ return opResults.every(Boolean);
204
+ });
205
+ }
206
+ /**
207
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
208
+ * @param checkpointNumber - The checkpoint number to set as proven.
209
+ */ async setProvenCheckpointNumber(checkpointNumber) {
210
+ await this.store.transactionAsync(async ()=>{
211
+ await this.store.setProvenCheckpointNumber(checkpointNumber);
212
+ await this.l2TipsCache?.refresh();
213
+ });
214
+ }
215
+ /** Extracts and stores contract data from a single block. */ addContractDataToDb(block) {
216
+ return this.updateContractDataOnDb(block, 0);
217
+ }
218
+ /** Removes contract data associated with a block. */ removeContractDataFromDb(block) {
219
+ return this.updateContractDataOnDb(block, 1);
220
+ }
221
+ /** Adds or remove contract data associated with a block. */ async updateContractDataOnDb(block, operation) {
222
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
223
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
224
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
225
+ return (await Promise.all([
226
+ this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
227
+ this.updateDeployedContractInstances(privateLogs, block.number, operation),
228
+ this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
229
+ operation === 0 ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number) : Promise.resolve(true)
230
+ ])).every(Boolean);
231
+ }
232
+ /**
233
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
234
+ */ async updatePublishedContractClasses(allLogs, blockNum, operation) {
235
+ const contractClassPublishedEvents = allLogs.filter((log)=>ContractClassPublishedEvent.isContractClassPublishedEvent(log)).map((log)=>ContractClassPublishedEvent.fromLog(log));
236
+ const contractClasses = await Promise.all(contractClassPublishedEvents.map((e)=>e.toContractClassPublic()));
237
+ if (contractClasses.length > 0) {
238
+ contractClasses.forEach((c)=>this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
239
+ if (operation == 0) {
240
+ // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
241
+ const commitments = await Promise.all(contractClasses.map((c)=>computePublicBytecodeCommitment(c.packedBytecode)));
242
+ return await this.store.addContractClasses(contractClasses, commitments, blockNum);
243
+ } else if (operation == 1) {
244
+ return await this.store.deleteContractClasses(contractClasses, blockNum);
245
+ }
246
+ }
247
+ return true;
248
+ }
249
+ /**
250
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
251
+ */ async updateDeployedContractInstances(allLogs, blockNum, operation) {
252
+ const contractInstances = allLogs.filter((log)=>ContractInstancePublishedEvent.isContractInstancePublishedEvent(log)).map((log)=>ContractInstancePublishedEvent.fromLog(log)).map((e)=>e.toContractInstance());
253
+ if (contractInstances.length > 0) {
254
+ contractInstances.forEach((c)=>this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`));
255
+ if (operation == 0) {
256
+ return await this.store.addContractInstances(contractInstances, blockNum);
257
+ } else if (operation == 1) {
258
+ return await this.store.deleteContractInstances(contractInstances, blockNum);
259
+ }
260
+ }
261
+ return true;
262
+ }
263
+ /**
264
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
265
+ */ async updateUpdatedContractInstances(allLogs, timestamp, operation) {
266
+ const contractUpdates = allLogs.filter((log)=>ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log)).map((log)=>ContractInstanceUpdatedEvent.fromLog(log)).map((e)=>e.toContractInstanceUpdate());
267
+ if (contractUpdates.length > 0) {
268
+ contractUpdates.forEach((c)=>this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`));
269
+ if (operation == 0) {
270
+ return await this.store.addContractInstanceUpdates(contractUpdates, timestamp);
271
+ } else if (operation == 1) {
272
+ return await this.store.deleteContractInstanceUpdates(contractUpdates, timestamp);
273
+ }
274
+ }
275
+ return true;
276
+ }
277
+ /**
278
+ * Stores the functions that were broadcasted individually.
279
+ *
280
+ * @dev Beware that there is not a delete variant of this, since they are added to contract classes
281
+ * and will be deleted as part of the class if needed.
282
+ */ async storeBroadcastedIndividualFunctions(allLogs, _blockNum) {
283
+ // Filter out private and utility function broadcast events
284
+ const privateFnEvents = allLogs.filter((log)=>PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log)).map((log)=>PrivateFunctionBroadcastedEvent.fromLog(log));
285
+ const utilityFnEvents = allLogs.filter((log)=>UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log)).map((log)=>UtilityFunctionBroadcastedEvent.fromLog(log));
286
+ // Group all events by contract class id
287
+ for (const [classIdString, classEvents] of Object.entries(groupBy([
288
+ ...privateFnEvents,
289
+ ...utilityFnEvents
290
+ ], (e)=>e.contractClassId.toString()))){
291
+ const contractClassId = Fr.fromHexString(classIdString);
292
+ const contractClass = await this.store.getContractClass(contractClassId);
293
+ if (!contractClass) {
294
+ this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
295
+ continue;
296
+ }
297
+ // Split private and utility functions, and filter out invalid ones
298
+ const allFns = classEvents.map((e)=>e.toFunctionWithMembershipProof());
299
+ const privateFns = allFns.filter((fn)=>'utilityFunctionsTreeRoot' in fn);
300
+ const utilityFns = allFns.filter((fn)=>'privateFunctionsArtifactTreeRoot' in fn);
301
+ const privateFunctionsWithValidity = await Promise.all(privateFns.map(async (fn)=>({
302
+ fn,
303
+ valid: await isValidPrivateFunctionMembershipProof(fn, contractClass)
304
+ })));
305
+ const validPrivateFns = privateFunctionsWithValidity.filter(({ valid })=>valid).map(({ fn })=>fn);
306
+ const utilityFunctionsWithValidity = await Promise.all(utilityFns.map(async (fn)=>({
307
+ fn,
308
+ valid: await isValidUtilityFunctionMembershipProof(fn, contractClass)
309
+ })));
310
+ const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid })=>valid).map(({ fn })=>fn);
311
+ const validFnCount = validPrivateFns.length + validUtilityFns.length;
312
+ if (validFnCount !== allFns.length) {
313
+ this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
314
+ }
315
+ // Store the functions in the contract class in a single operation
316
+ if (validFnCount > 0) {
317
+ this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
318
+ }
319
+ return await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
320
+ }
321
+ return true;
322
+ }
323
+ }
@@ -0,0 +1,39 @@
1
+ import type { L2Block } from '@aztec/stdlib/block';
2
+ import type { CheckpointData } from '@aztec/stdlib/checkpoint';
3
+ import { type LmdbStatsCallback, type TelemetryClient, type Tracer } from '@aztec/telemetry-client';
4
+ export declare class ArchiverInstrumentation {
5
+ private telemetry;
6
+ readonly tracer: Tracer;
7
+ private blockHeight;
8
+ private checkpointHeight;
9
+ private txCount;
10
+ private l1BlockHeight;
11
+ private proofsSubmittedDelay;
12
+ private proofsSubmittedCount;
13
+ private dbMetrics;
14
+ private pruneDuration;
15
+ private pruneCount;
16
+ private syncDurationPerBlock;
17
+ private syncBlockCount;
18
+ private manaPerBlock;
19
+ private txsPerBlock;
20
+ private syncDurationPerMessage;
21
+ private syncMessageCount;
22
+ private blockProposalTxTargetCount;
23
+ private log;
24
+ private constructor();
25
+ static new(telemetry: TelemetryClient, lmdbStats?: LmdbStatsCallback): Promise<ArchiverInstrumentation>;
26
+ isEnabled(): boolean;
27
+ processNewBlocks(syncTimePerBlock: number, blocks: L2Block[]): void;
28
+ processNewMessages(count: number, syncPerMessageMs: number): void;
29
+ processPrune(duration: number): void;
30
+ updateLastProvenCheckpoint(checkpoint: CheckpointData): void;
31
+ processProofsVerified(logs: {
32
+ proverId: string;
33
+ l2BlockNumber: bigint;
34
+ delay: bigint;
35
+ }[]): void;
36
+ updateL1BlockHeight(blockNumber: bigint): void;
37
+ recordBlockProposalTxTarget(target: string, usedTrace: boolean): void;
38
+ }
39
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5zdHJ1bWVudGF0aW9uLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbW9kdWxlcy9pbnN0cnVtZW50YXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxLQUFLLEVBQUUsT0FBTyxFQUFFLE1BQU0scUJBQXFCLENBQUM7QUFDbkQsT0FBTyxLQUFLL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