@aztec/archiver 0.0.1-commit.c7c42ec → 0.0.1-commit.f295ac2

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 (187) hide show
  1. package/README.md +147 -22
  2. package/dest/archiver.d.ts +135 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +769 -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/{archiver/errors.d.ts → errors.d.ts} +1 -1
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/factory.d.ts +5 -6
  11. package/dest/factory.d.ts.map +1 -1
  12. package/dest/factory.js +82 -5
  13. package/dest/index.d.ts +10 -4
  14. package/dest/index.d.ts.map +1 -1
  15. package/dest/index.js +8 -3
  16. package/dest/interfaces.d.ts +9 -0
  17. package/dest/interfaces.d.ts.map +1 -0
  18. package/dest/interfaces.js +3 -0
  19. package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.d.ts +1 -1
  20. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  21. package/dest/{archiver/l1 → l1}/calldata_retriever.d.ts +3 -3
  22. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  23. package/dest/{archiver/l1 → l1}/calldata_retriever.js +2 -2
  24. package/dest/l1/data_retrieval.d.ts +88 -0
  25. package/dest/l1/data_retrieval.d.ts.map +1 -0
  26. package/dest/{archiver/l1 → l1}/data_retrieval.js +34 -53
  27. package/dest/{archiver/l1 → l1}/debug_tx.d.ts +1 -1
  28. package/dest/l1/debug_tx.d.ts.map +1 -0
  29. package/dest/{archiver/l1 → l1}/spire_proposer.d.ts +1 -1
  30. package/dest/l1/spire_proposer.d.ts.map +1 -0
  31. package/dest/{archiver/l1 → l1}/trace_tx.d.ts +1 -1
  32. package/dest/l1/trace_tx.d.ts.map +1 -0
  33. package/dest/l1/types.d.ts +12 -0
  34. package/dest/l1/types.d.ts.map +1 -0
  35. package/dest/{archiver/l1 → l1}/validate_trace.d.ts +1 -1
  36. package/dest/l1/validate_trace.d.ts.map +1 -0
  37. package/dest/{archiver/l1 → l1}/validate_trace.js +1 -1
  38. package/dest/modules/data_source_base.d.ts +85 -0
  39. package/dest/modules/data_source_base.d.ts.map +1 -0
  40. package/dest/modules/data_source_base.js +291 -0
  41. package/dest/modules/data_store_updater.d.ts +69 -0
  42. package/dest/modules/data_store_updater.d.ts.map +1 -0
  43. package/dest/modules/data_store_updater.js +304 -0
  44. package/dest/modules/instrumentation.d.ts +37 -0
  45. package/dest/modules/instrumentation.d.ts.map +1 -0
  46. package/dest/{archiver → modules}/instrumentation.js +15 -63
  47. package/dest/modules/l1_synchronizer.d.ts +75 -0
  48. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  49. package/dest/modules/l1_synchronizer.js +1113 -0
  50. package/dest/modules/validation.d.ts +17 -0
  51. package/dest/modules/validation.d.ts.map +1 -0
  52. package/dest/{archiver → modules}/validation.js +7 -1
  53. package/dest/{archiver/kv_archiver_store → store}/block_store.d.ts +27 -6
  54. package/dest/store/block_store.d.ts.map +1 -0
  55. package/dest/{archiver/kv_archiver_store → store}/block_store.js +87 -14
  56. package/dest/store/contract_class_store.d.ts +18 -0
  57. package/dest/store/contract_class_store.d.ts.map +1 -0
  58. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +1 -1
  59. package/dest/store/contract_instance_store.d.ts +24 -0
  60. package/dest/store/contract_instance_store.d.ts.map +1 -0
  61. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  62. package/dest/{archiver/archiver_store.d.ts → store/kv_archiver_store.d.ts} +155 -132
  63. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  64. package/dest/{archiver/kv_archiver_store → store}/kv_archiver_store.js +173 -48
  65. package/dest/{archiver/kv_archiver_store → store}/log_store.d.ts +1 -1
  66. package/dest/store/log_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/log_store.js +69 -48
  68. package/dest/{archiver/kv_archiver_store → store}/message_store.d.ts +1 -1
  69. package/dest/store/message_store.d.ts.map +1 -0
  70. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  71. package/dest/structs/data_retrieval.d.ts.map +1 -0
  72. package/dest/structs/inbox_message.d.ts +15 -0
  73. package/dest/structs/inbox_message.d.ts.map +1 -0
  74. package/dest/{archiver/structs → structs}/published.d.ts +1 -1
  75. package/dest/structs/published.d.ts.map +1 -0
  76. package/dest/test/fake_l1_state.d.ts +190 -0
  77. package/dest/test/fake_l1_state.d.ts.map +1 -0
  78. package/dest/test/fake_l1_state.js +383 -0
  79. package/dest/test/index.d.ts +2 -1
  80. package/dest/test/index.d.ts.map +1 -1
  81. package/dest/test/index.js +1 -0
  82. package/dest/test/mock_archiver.d.ts +2 -2
  83. package/dest/test/mock_archiver.d.ts.map +1 -1
  84. package/dest/test/mock_archiver.js +1 -2
  85. package/dest/test/mock_l1_to_l2_message_source.d.ts +2 -2
  86. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  87. package/dest/test/mock_l1_to_l2_message_source.js +12 -3
  88. package/dest/test/mock_l2_block_source.d.ts +21 -14
  89. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  90. package/dest/test/mock_l2_block_source.js +147 -40
  91. package/dest/test/mock_structs.d.ts +76 -2
  92. package/dest/test/mock_structs.d.ts.map +1 -1
  93. package/dest/test/mock_structs.js +133 -2
  94. package/package.json +15 -17
  95. package/src/archiver.ts +525 -0
  96. package/src/{archiver/config.ts → config.ts} +13 -2
  97. package/src/factory.ts +118 -6
  98. package/src/index.ts +10 -3
  99. package/src/interfaces.ts +9 -0
  100. package/src/{archiver/l1 → l1}/calldata_retriever.ts +3 -3
  101. package/src/{archiver/l1 → l1}/data_retrieval.ts +54 -71
  102. package/src/{archiver/l1 → l1}/validate_trace.ts +1 -1
  103. package/src/modules/data_source_base.ts +414 -0
  104. package/src/modules/data_store_updater.ts +419 -0
  105. package/src/{archiver → modules}/instrumentation.ts +14 -63
  106. package/src/modules/l1_synchronizer.ts +931 -0
  107. package/src/{archiver → modules}/validation.ts +11 -6
  108. package/src/{archiver/kv_archiver_store → store}/block_store.ts +116 -19
  109. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +1 -1
  110. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +1 -1
  111. package/src/{archiver/kv_archiver_store → store}/kv_archiver_store.ts +196 -12
  112. package/src/{archiver/kv_archiver_store → store}/log_store.ts +112 -76
  113. package/src/test/fake_l1_state.ts +599 -0
  114. package/src/test/index.ts +1 -0
  115. package/src/test/mock_archiver.ts +2 -2
  116. package/src/test/mock_l1_to_l2_message_source.ts +10 -4
  117. package/src/test/mock_l2_block_source.ts +168 -52
  118. package/src/test/mock_structs.ts +247 -2
  119. package/dest/archiver/archiver.d.ts +0 -304
  120. package/dest/archiver/archiver.d.ts.map +0 -1
  121. package/dest/archiver/archiver.js +0 -1645
  122. package/dest/archiver/archiver_store.d.ts.map +0 -1
  123. package/dest/archiver/archiver_store.js +0 -4
  124. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  125. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  126. package/dest/archiver/archiver_store_test_suite.js +0 -2770
  127. package/dest/archiver/config.d.ts.map +0 -1
  128. package/dest/archiver/errors.d.ts.map +0 -1
  129. package/dest/archiver/index.d.ts +0 -7
  130. package/dest/archiver/index.d.ts.map +0 -1
  131. package/dest/archiver/index.js +0 -4
  132. package/dest/archiver/instrumentation.d.ts +0 -37
  133. package/dest/archiver/instrumentation.d.ts.map +0 -1
  134. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  135. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  136. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  137. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  138. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  139. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -158
  140. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  141. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  142. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  143. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +0 -1
  144. package/dest/archiver/l1/calldata_retriever.d.ts.map +0 -1
  145. package/dest/archiver/l1/data_retrieval.d.ts +0 -90
  146. package/dest/archiver/l1/data_retrieval.d.ts.map +0 -1
  147. package/dest/archiver/l1/debug_tx.d.ts.map +0 -1
  148. package/dest/archiver/l1/spire_proposer.d.ts.map +0 -1
  149. package/dest/archiver/l1/trace_tx.d.ts.map +0 -1
  150. package/dest/archiver/l1/types.d.ts +0 -12
  151. package/dest/archiver/l1/types.d.ts.map +0 -1
  152. package/dest/archiver/l1/validate_trace.d.ts.map +0 -1
  153. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  154. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  155. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  156. package/dest/archiver/structs/published.d.ts.map +0 -1
  157. package/dest/archiver/validation.d.ts +0 -17
  158. package/dest/archiver/validation.d.ts.map +0 -1
  159. package/dest/rpc/index.d.ts +0 -9
  160. package/dest/rpc/index.d.ts.map +0 -1
  161. package/dest/rpc/index.js +0 -15
  162. package/src/archiver/archiver.ts +0 -2157
  163. package/src/archiver/archiver_store.ts +0 -372
  164. package/src/archiver/archiver_store_test_suite.ts +0 -2843
  165. package/src/archiver/index.ts +0 -6
  166. package/src/rpc/index.ts +0 -16
  167. /package/dest/{archiver/errors.js → errors.js} +0 -0
  168. /package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.js +0 -0
  169. /package/dest/{archiver/l1 → l1}/debug_tx.js +0 -0
  170. /package/dest/{archiver/l1 → l1}/spire_proposer.js +0 -0
  171. /package/dest/{archiver/l1 → l1}/trace_tx.js +0 -0
  172. /package/dest/{archiver/l1 → l1}/types.js +0 -0
  173. /package/dest/{archiver/kv_archiver_store → store}/message_store.js +0 -0
  174. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  175. /package/dest/{archiver/structs → structs}/inbox_message.js +0 -0
  176. /package/dest/{archiver/structs → structs}/published.js +0 -0
  177. /package/src/{archiver/errors.ts → errors.ts} +0 -0
  178. /package/src/{archiver/l1 → l1}/README.md +0 -0
  179. /package/src/{archiver/l1 → l1}/bin/retrieve-calldata.ts +0 -0
  180. /package/src/{archiver/l1 → l1}/debug_tx.ts +0 -0
  181. /package/src/{archiver/l1 → l1}/spire_proposer.ts +0 -0
  182. /package/src/{archiver/l1 → l1}/trace_tx.ts +0 -0
  183. /package/src/{archiver/l1 → l1}/types.ts +0 -0
  184. /package/src/{archiver/kv_archiver_store → store}/message_store.ts +0 -0
  185. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
  186. /package/src/{archiver/structs → structs}/inbox_message.ts +0 -0
  187. /package/src/{archiver/structs → structs}/published.ts +0 -0
@@ -0,0 +1,291 @@
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { isDefined } from '@aztec/foundation/types';
3
+ import { CheckpointedL2Block, CommitteeAttestation } from '@aztec/stdlib/block';
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
+ getCheckpointedBlockNumber() {
44
+ return this.store.getCheckpointedL2BlockNumber();
45
+ }
46
+ async getCheckpointHeader(number) {
47
+ if (number === 'latest') {
48
+ number = await this.store.getSynchedCheckpointNumber();
49
+ }
50
+ if (number === 0) {
51
+ return undefined;
52
+ }
53
+ const checkpoint = await this.store.getCheckpointData(number);
54
+ if (!checkpoint) {
55
+ return undefined;
56
+ }
57
+ return checkpoint.header;
58
+ }
59
+ async getLastBlockNumberInCheckpoint(checkpointNumber) {
60
+ const checkpointData = await this.store.getCheckpointData(checkpointNumber);
61
+ if (!checkpointData) {
62
+ return undefined;
63
+ }
64
+ return BlockNumber(checkpointData.startBlock + checkpointData.numBlocks - 1);
65
+ }
66
+ async getCheckpointedBlocks(from, limit, proven) {
67
+ const blocks = await this.store.getCheckpointedBlocks(from, limit);
68
+ if (proven === true) {
69
+ const provenBlockNumber = await this.store.getProvenBlockNumber();
70
+ return blocks.filter((b)=>b.block.number <= provenBlockNumber);
71
+ }
72
+ return blocks;
73
+ }
74
+ getBlockHeaderByHash(blockHash) {
75
+ return this.store.getBlockHeaderByHash(blockHash);
76
+ }
77
+ getBlockHeaderByArchive(archive) {
78
+ return this.store.getBlockHeaderByArchive(archive);
79
+ }
80
+ async getL2BlockNew(number) {
81
+ // If the number provided is -ve, then return the latest block.
82
+ if (number < 0) {
83
+ number = await this.store.getLatestBlockNumber();
84
+ }
85
+ if (number === 0) {
86
+ return undefined;
87
+ }
88
+ const publishedBlock = await this.store.getBlock(number);
89
+ return publishedBlock;
90
+ }
91
+ getTxEffect(txHash) {
92
+ return this.store.getTxEffect(txHash);
93
+ }
94
+ getSettledTxReceipt(txHash) {
95
+ return this.store.getSettledTxReceipt(txHash);
96
+ }
97
+ isPendingChainInvalid() {
98
+ return this.getPendingChainValidationStatus().then((status)=>!status.valid);
99
+ }
100
+ async getPendingChainValidationStatus() {
101
+ return await this.store.getPendingChainValidationStatus() ?? {
102
+ valid: true
103
+ };
104
+ }
105
+ async getL2BlocksNew(from, limit, proven) {
106
+ const blocks = await this.store.getBlocks(from, limit);
107
+ if (proven === true) {
108
+ const provenBlockNumber = await this.store.getProvenBlockNumber();
109
+ return blocks.filter((b)=>b.number <= provenBlockNumber);
110
+ }
111
+ return blocks;
112
+ }
113
+ getPrivateLogsByTags(tags) {
114
+ return this.store.getPrivateLogsByTags(tags);
115
+ }
116
+ getPublicLogsByTagsFromContract(contractAddress, tags) {
117
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags);
118
+ }
119
+ getPublicLogs(filter) {
120
+ return this.store.getPublicLogs(filter);
121
+ }
122
+ getContractClassLogs(filter) {
123
+ return this.store.getContractClassLogs(filter);
124
+ }
125
+ getContractClass(id) {
126
+ return this.store.getContractClass(id);
127
+ }
128
+ getBytecodeCommitment(id) {
129
+ return this.store.getBytecodeCommitment(id);
130
+ }
131
+ async getContract(address, maybeTimestamp) {
132
+ let timestamp;
133
+ if (maybeTimestamp === undefined) {
134
+ const latestBlockHeader = await this.getBlockHeader('latest');
135
+ // If we get undefined block header, it means that the archiver has not yet synced any block so we default to 0.
136
+ timestamp = latestBlockHeader ? latestBlockHeader.globalVariables.timestamp : 0n;
137
+ } else {
138
+ timestamp = maybeTimestamp;
139
+ }
140
+ return this.store.getContractInstance(address, timestamp);
141
+ }
142
+ getContractClassIds() {
143
+ return this.store.getContractClassIds();
144
+ }
145
+ getDebugFunctionName(address, selector) {
146
+ return this.store.getDebugFunctionName(address, selector);
147
+ }
148
+ registerContractFunctionSignatures(signatures) {
149
+ return this.store.registerContractFunctionSignatures(signatures);
150
+ }
151
+ getL1ToL2Messages(checkpointNumber) {
152
+ return this.store.getL1ToL2Messages(checkpointNumber);
153
+ }
154
+ getL1ToL2MessageIndex(l1ToL2Message) {
155
+ return this.store.getL1ToL2MessageIndex(l1ToL2Message);
156
+ }
157
+ async getPublishedCheckpoints(checkpointNumber, limit) {
158
+ const checkpoints = await this.store.getRangeOfCheckpoints(checkpointNumber, limit);
159
+ const blocks = (await Promise.all(checkpoints.map((ch)=>this.store.getBlocksForCheckpoint(ch.checkpointNumber)))).filter(isDefined);
160
+ const fullCheckpoints = [];
161
+ for(let i = 0; i < checkpoints.length; i++){
162
+ const blocksForCheckpoint = blocks[i];
163
+ const checkpoint = checkpoints[i];
164
+ const fullCheckpoint = new Checkpoint(checkpoint.archive, checkpoint.header, blocksForCheckpoint, checkpoint.checkpointNumber);
165
+ const publishedCheckpoint = new PublishedCheckpoint(fullCheckpoint, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
166
+ fullCheckpoints.push(publishedCheckpoint);
167
+ }
168
+ return fullCheckpoints;
169
+ }
170
+ getBlocksForSlot(slotNumber) {
171
+ return this.store.getBlocksForSlot(slotNumber);
172
+ }
173
+ async getBlocksForEpoch(epochNumber) {
174
+ if (!this.l1Constants) {
175
+ throw new Error('L1 constants not set');
176
+ }
177
+ const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
178
+ const blocks = [];
179
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
180
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
181
+ let checkpoint = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
182
+ const slot = (b)=>b.header.slotNumber;
183
+ while(checkpoint && slot(checkpoint) >= start){
184
+ if (slot(checkpoint) <= end) {
185
+ // push the blocks on backwards
186
+ const endBlock = checkpoint.startBlock + checkpoint.numBlocks - 1;
187
+ for(let i = endBlock; i >= checkpoint.startBlock; i--){
188
+ const block = await this.getBlock(BlockNumber(i));
189
+ if (block) {
190
+ blocks.push(block);
191
+ }
192
+ }
193
+ }
194
+ checkpoint = await this.store.getCheckpointData(CheckpointNumber(checkpoint.checkpointNumber - 1));
195
+ }
196
+ return blocks.reverse();
197
+ }
198
+ async getBlockHeadersForEpoch(epochNumber) {
199
+ if (!this.l1Constants) {
200
+ throw new Error('L1 constants not set');
201
+ }
202
+ const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
203
+ const blocks = [];
204
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
205
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
206
+ let checkpoint = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
207
+ const slot = (b)=>b.header.slotNumber;
208
+ while(checkpoint && slot(checkpoint) >= start){
209
+ if (slot(checkpoint) <= end) {
210
+ // push the blocks on backwards
211
+ const endBlock = checkpoint.startBlock + checkpoint.numBlocks - 1;
212
+ for(let i = endBlock; i >= checkpoint.startBlock; i--){
213
+ const block = await this.getBlockHeader(BlockNumber(i));
214
+ if (block) {
215
+ blocks.push(block);
216
+ }
217
+ }
218
+ }
219
+ checkpoint = await this.store.getCheckpointData(CheckpointNumber(checkpoint.checkpointNumber - 1));
220
+ }
221
+ return blocks.reverse();
222
+ }
223
+ async getCheckpointsForEpoch(epochNumber) {
224
+ if (!this.l1Constants) {
225
+ throw new Error('L1 constants not set');
226
+ }
227
+ const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
228
+ const checkpoints = [];
229
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
230
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
231
+ let checkpointData = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
232
+ const slot = (b)=>b.header.slotNumber;
233
+ while(checkpointData && slot(checkpointData) >= start){
234
+ if (slot(checkpointData) <= end) {
235
+ // push the checkpoints on backwards
236
+ const [checkpoint] = await this.getPublishedCheckpoints(checkpointData.checkpointNumber, 1);
237
+ checkpoints.push(checkpoint.checkpoint);
238
+ }
239
+ checkpointData = await this.store.getCheckpointData(CheckpointNumber(checkpointData.checkpointNumber - 1));
240
+ }
241
+ return checkpoints.reverse();
242
+ }
243
+ async getPublishedBlocks(from, limit, proven) {
244
+ const checkpoints = await this.store.getRangeOfCheckpoints(CheckpointNumber(from), limit);
245
+ const provenCheckpointNumber = await this.store.getProvenCheckpointNumber();
246
+ const blocks = (await Promise.all(checkpoints.map((ch)=>this.store.getBlocksForCheckpoint(ch.checkpointNumber)))).filter(isDefined);
247
+ const publishedBlocks = [];
248
+ for(let i = 0; i < checkpoints.length; i++){
249
+ const blockForCheckpoint = blocks[i][0];
250
+ const checkpoint = checkpoints[i];
251
+ if (checkpoint.checkpointNumber > provenCheckpointNumber && proven === true) {
252
+ continue;
253
+ }
254
+ const publishedBlock = new CheckpointedL2Block(checkpoint.checkpointNumber, blockForCheckpoint, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
255
+ publishedBlocks.push(publishedBlock);
256
+ }
257
+ return publishedBlocks;
258
+ }
259
+ async getBlock(number) {
260
+ // If the number provided is -ve, then return the latest block.
261
+ if (number < 0) {
262
+ number = await this.store.getLatestBlockNumber();
263
+ }
264
+ if (number === 0) {
265
+ return undefined;
266
+ }
267
+ return this.store.getBlock(number);
268
+ }
269
+ async getBlocks(from, limit, proven) {
270
+ const blocks = await this.store.getBlocks(from, limit);
271
+ if (proven === true) {
272
+ const provenBlockNumber = await this.store.getProvenBlockNumber();
273
+ return blocks.filter((b)=>b.number <= provenBlockNumber);
274
+ }
275
+ return blocks;
276
+ }
277
+ getPublishedBlockByHash(blockHash) {
278
+ return this.store.getCheckpointedBlockByHash(blockHash);
279
+ }
280
+ getPublishedBlockByArchive(archive) {
281
+ return this.store.getCheckpointedBlockByArchive(archive);
282
+ }
283
+ async getL2BlockNewByHash(blockHash) {
284
+ const checkpointedBlock = await this.store.getCheckpointedBlockByHash(blockHash);
285
+ return checkpointedBlock?.block;
286
+ }
287
+ async getL2BlockNewByArchive(archive) {
288
+ const checkpointedBlock = await this.store.getCheckpointedBlockByArchive(archive);
289
+ return checkpointedBlock?.block;
290
+ }
291
+ }
@@ -0,0 +1,69 @@
1
+ import { BlockNumber, type CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import type { L2BlockNew, ValidateCheckpointResult } from '@aztec/stdlib/block';
3
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
4
+ import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
5
+ /** Result of adding checkpoints with information about any pruned blocks. */
6
+ type ReconcileCheckpointsResult = {
7
+ /** Blocks that were pruned due to conflict with L1 checkpoints. */
8
+ prunedBlocks: L2BlockNew[] | undefined;
9
+ /** Last block number that was already inserted locally, or undefined if none. */
10
+ lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
11
+ };
12
+ /** Archiver helper module to handle updates to the data store. */
13
+ export declare class ArchiverDataStoreUpdater {
14
+ private store;
15
+ private readonly log;
16
+ constructor(store: KVArchiverDataStore);
17
+ /**
18
+ * Adds blocks to the store with contract class/instance extraction from logs.
19
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
20
+ * and individually broadcasted functions from the block logs.
21
+ *
22
+ * @param blocks - The L2 blocks to add.
23
+ * @param pendingChainValidationStatus - Optional validation status to set.
24
+ * @returns True if the operation is successful.
25
+ */
26
+ addBlocks(blocks: L2BlockNew[], pendingChainValidationStatus?: ValidateCheckpointResult): Promise<boolean>;
27
+ /**
28
+ * Reconciles local blocks with incoming checkpoints from L1.
29
+ * Adds checkpoints to the store with contract class/instance extraction from logs.
30
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
31
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
32
+ * and individually broadcasted functions from the checkpoint block logs.
33
+ *
34
+ * @param checkpoints - The published checkpoints to add.
35
+ * @param pendingChainValidationStatus - Optional validation status to set.
36
+ * @returns Result with information about any pruned blocks.
37
+ */
38
+ setNewCheckpointData(checkpoints: PublishedCheckpoint[], pendingChainValidationStatus?: ValidateCheckpointResult): Promise<ReconcileCheckpointsResult>;
39
+ private pruneMismatchingLocalBlocks;
40
+ /**
41
+ * Removes all blocks strictly after the specified block number and cleans up associated contract data.
42
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
43
+ *
44
+ * @param blockNumber - Remove all blocks with number greater than this.
45
+ * @returns The removed blocks.
46
+ */
47
+ removeBlocksAfter(blockNumber: BlockNumber): Promise<L2BlockNew[]>;
48
+ /**
49
+ * Unwinds checkpoints from the store with reverse contract extraction.
50
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
51
+ * that was stored for the unwound checkpoints.
52
+ *
53
+ * @param from - The checkpoint number to unwind from (must be the current tip).
54
+ * @param checkpointsToUnwind - The number of checkpoints to unwind.
55
+ * @returns True if the operation is successful.
56
+ */
57
+ unwindCheckpoints(from: CheckpointNumber, checkpointsToUnwind: number): Promise<boolean>;
58
+ /** Extracts and stores contract data from a single block. */
59
+ private addBlockDataToDB;
60
+ /** Removes contract data associated with a block. */
61
+ private removeBlockDataFromDB;
62
+ private editContractBlockData;
63
+ private updatePublishedContractClasses;
64
+ private updateDeployedContractInstances;
65
+ private updateUpdatedContractInstances;
66
+ private storeBroadcastedIndividualFunctions;
67
+ }
68
+ export {};
69
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGF0YV9zdG9yZV91cGRhdGVyLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbW9kdWxlcy9kYXRhX3N0b3JlX3VwZGF0ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLFdBQVcsRUFBRSxLQUFLLGdCQUFnQixFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFZckYsT0FBTyxLQUFLLEVBQUUsVUFBVSxFQUFFLHdCQUF3QixFQUFFLE1BQU0scUJBQXFCLENBQUM7QUFDaEYsT0FBTyxLQUFLLEVBQUUsbUJBQW1CLEVBQUUsTUFBTSwwQkFBMEIsQ0FBQztBQWFwRSxPQUFPLEtBQUssRUFBRSxtQkFBbUIsRUFBRSxNQUFNLCtCQUErQixDQUFDO0FBUXpFLDZFQUE2RTtBQUM3RSxLQUFLLDBCQUEwQixHQUFHO0lBQ2hDLG1FQUFtRTtJQUNuRSxZQUFZLEVBQUUsVUFBVSxFQUFFLEdBQUcsU0FBUyxDQUFDO0lBQ3ZDLGlGQUFpRjtJQUNqRiw4QkFBOEIsRUFBRSxXQUFXLEdBQUcsU0FBUyxDQUFDO0NBQ3pELENBQUM7QUFFRixrRUFBa0U7QUFDbEUscUJBQWEsd0JBQXdCO0lBR3ZCLE9BQU8sQ0FBQyxLQUFLO0lBRnpCLE9BQU8sQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUEwQztJQUU5RCxZQUFvQixLQUFLLEVBQUUsbUJBQW1CLEVBQUk7SUFFbEQ7Ozs7Ozs7O09BUUc7SUFDSSxTQUFTLENBQUMsTUFBTSxFQUFFLFVBQVUsRUFBRSxFQUFFLDRCQUE0QixDQUFDLEVBQUUsd0JBQXdCLEdBQUcsT0FBTyxDQUFDLE9BQU8sQ0FBQyxDQWVoSDtJQUVEOzs7Ozs7Ozs7O09BVUc7SUFDSSxvQkFBb0IsQ0FDekIsV0FBVyxFQUFFLG1CQUFtQixFQUFFLEVBQ2xDLDRCQUE0QixDQUFDLEVBQUUsd0JBQXdCLEdBQ3RELE9BQU8sQ0FBQywwQkFBMEIsQ0FBQyxDQXVCckM7WUFRYSwyQkFBMkI7SUFtRXpDOzs7Ozs7T0FNRztJQUNJLGlCQUFpQixDQUFDLFdBQVcsRUFBRSxXQUFXLEdBQUcsT0FBTyxDQUFDLFVBQVUsRUFBRSxDQUFDLENBYXhFO0lBRUQ7Ozs7Ozs7O09BUUc7SUFDVSxpQkFBaUIsQ0FBQyxJQUFJLEVBQUUsZ0JBQWdCLEVBQUUsbUJBQW1CLEVBQUUsTUFBTSxHQUFHLE9BQU8sQ0FBQyxPQUFPLENBQUMsQ0E4QnBHO0lBRUQsNkRBQTZEO0lBQzdELE9BQU8sQ0FBQyxnQkFBZ0I7SUFJeEIscURBQXFEO0lBQ3JELE9BQU8sQ0FBQyxxQkFBcUI7WUFLZixxQkFBcUI7WUFvQnJCLDhCQUE4QjtZQTRCOUIsK0JBQStCO1lBeUIvQiw4QkFBOEI7WUE2QjlCLG1DQUFtQztDQXdEbEQifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data_store_updater.d.ts","sourceRoot":"","sources":["../../src/modules/data_store_updater.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAYrF,OAAO,KAAK,EAAE,UAAU,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAapE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAQzE,6EAA6E;AAC7E,KAAK,0BAA0B,GAAG;IAChC,mEAAmE;IACnE,YAAY,EAAE,UAAU,EAAE,GAAG,SAAS,CAAC;IACvC,iFAAiF;IACjF,8BAA8B,EAAE,WAAW,GAAG,SAAS,CAAC;CACzD,CAAC;AAEF,kEAAkE;AAClE,qBAAa,wBAAwB;IAGvB,OAAO,CAAC,KAAK;IAFzB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAA0C;IAE9D,YAAoB,KAAK,EAAE,mBAAmB,EAAI;IAElD;;;;;;;;OAQG;IACI,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,4BAA4B,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,OAAO,CAAC,CAehH;IAED;;;;;;;;;;OAUG;IACI,oBAAoB,CACzB,WAAW,EAAE,mBAAmB,EAAE,EAClC,4BAA4B,CAAC,EAAE,wBAAwB,GACtD,OAAO,CAAC,0BAA0B,CAAC,CAuBrC;YAQa,2BAA2B;IAmEzC;;;;;;OAMG;IACI,iBAAiB,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAaxE;IAED;;;;;;;;OAQG;IACU,iBAAiB,CAAC,IAAI,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CA8BpG;IAED,6DAA6D;IAC7D,OAAO,CAAC,gBAAgB;IAIxB,qDAAqD;IACrD,OAAO,CAAC,qBAAqB;YAKf,qBAAqB;YAoBrB,8BAA8B;YA4B9B,+BAA+B;YAyB/B,8BAA8B;YA6B9B,mCAAmC;CAwDlD"}
@@ -0,0 +1,304 @@
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
+ log;
16
+ constructor(store){
17
+ this.store = store;
18
+ this.log = createLogger('archiver:store_updater');
19
+ }
20
+ /**
21
+ * Adds blocks to the store with contract class/instance extraction from logs.
22
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
23
+ * and individually broadcasted functions from the block logs.
24
+ *
25
+ * @param blocks - The L2 blocks to add.
26
+ * @param pendingChainValidationStatus - Optional validation status to set.
27
+ * @returns True if the operation is successful.
28
+ */ addBlocks(blocks, pendingChainValidationStatus) {
29
+ return this.store.transactionAsync(async ()=>{
30
+ await this.store.addBlocks(blocks);
31
+ const opResults = await Promise.all([
32
+ // Update the pending chain validation status if provided
33
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
34
+ // Add any logs emitted during the retrieved blocks
35
+ this.store.addLogs(blocks),
36
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
37
+ ...blocks.map((block)=>this.addBlockDataToDB(block))
38
+ ]);
39
+ return opResults.every(Boolean);
40
+ });
41
+ }
42
+ /**
43
+ * Reconciles local blocks with incoming checkpoints from L1.
44
+ * Adds checkpoints to the store with contract class/instance extraction from logs.
45
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
46
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
47
+ * and individually broadcasted functions from the checkpoint block logs.
48
+ *
49
+ * @param checkpoints - The published checkpoints to add.
50
+ * @param pendingChainValidationStatus - Optional validation status to set.
51
+ * @returns Result with information about any pruned blocks.
52
+ */ setNewCheckpointData(checkpoints, pendingChainValidationStatus) {
53
+ return this.store.transactionAsync(async ()=>{
54
+ // Before adding checkpoints, check for conflicts with local blocks if any
55
+ const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
56
+ await this.store.addCheckpoints(checkpoints);
57
+ // Filter out blocks that were already inserted via addBlocks() to avoid duplicating logs/contract data
58
+ const newBlocks = checkpoints.flatMap((ch)=>ch.checkpoint.blocks).filter((b)=>lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
59
+ await Promise.all([
60
+ // Update the pending chain validation status if provided
61
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
62
+ // Add any logs emitted during the retrieved blocks
63
+ this.store.addLogs(newBlocks),
64
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
65
+ ...newBlocks.map((block)=>this.addBlockDataToDB(block))
66
+ ]);
67
+ return {
68
+ prunedBlocks,
69
+ lastAlreadyInsertedBlockNumber
70
+ };
71
+ });
72
+ }
73
+ /**
74
+ * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
75
+ * This method handles multiple checkpoints but returns after pruning the first conflict found.
76
+ * This is correct because pruning from the first conflict point removes all subsequent blocks,
77
+ * and when checkpoints are added afterward, they include all the correct blocks.
78
+ */ async pruneMismatchingLocalBlocks(checkpoints) {
79
+ const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
80
+ this.store.getCheckpointedL2BlockNumber(),
81
+ this.store.getLatestBlockNumber()
82
+ ]);
83
+ // Exit early if there are no local uncheckpointed blocks
84
+ if (lastBlockNumber === lastCheckpointedBlockNumber) {
85
+ return {
86
+ prunedBlocks: undefined,
87
+ lastAlreadyInsertedBlockNumber: undefined
88
+ };
89
+ }
90
+ // Get all uncheckpointed local blocks
91
+ const uncheckpointedLocalBlocks = await this.store.getBlocks(BlockNumber.add(lastCheckpointedBlockNumber, 1), lastBlockNumber - lastCheckpointedBlockNumber);
92
+ let lastAlreadyInsertedBlockNumber;
93
+ for (const publishedCheckpoint of checkpoints){
94
+ const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
95
+ const slot = publishedCheckpoint.checkpoint.slot;
96
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter((b)=>b.slot === slot);
97
+ if (checkpointBlocks.length === 0) {
98
+ this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
99
+ continue;
100
+ }
101
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards
102
+ for (const checkpointBlock of checkpointBlocks){
103
+ const blockNumber = checkpointBlock.number;
104
+ const existingBlock = localBlocksInSlot.find((b)=>b.number === blockNumber);
105
+ const blockInfos = {
106
+ existingBlock: existingBlock?.toBlockInfo(),
107
+ checkpointBlock: checkpointBlock.toBlockInfo()
108
+ };
109
+ if (!existingBlock) {
110
+ this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`, blockInfos);
111
+ } else if (existingBlock.archive.root.equals(checkpointBlock.archive.root)) {
112
+ this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
113
+ lastAlreadyInsertedBlockNumber = blockNumber;
114
+ } else {
115
+ this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
116
+ const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
117
+ return {
118
+ prunedBlocks,
119
+ lastAlreadyInsertedBlockNumber
120
+ };
121
+ }
122
+ }
123
+ // If local has more blocks than the checkpoint (e.g., local has [2,3,4] but checkpoint has [2,3]),
124
+ // we need to prune the extra local blocks so they match what was checkpointed
125
+ const lastCheckpointBlockNumber = checkpointBlocks.at(-1).number;
126
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.number;
127
+ if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
128
+ this.log.warn(`Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`);
129
+ const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
130
+ return {
131
+ prunedBlocks,
132
+ lastAlreadyInsertedBlockNumber
133
+ };
134
+ }
135
+ }
136
+ return {
137
+ prunedBlocks: undefined,
138
+ lastAlreadyInsertedBlockNumber
139
+ };
140
+ }
141
+ /**
142
+ * Removes all blocks strictly after the specified block number and cleans up associated contract data.
143
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
144
+ *
145
+ * @param blockNumber - Remove all blocks with number greater than this.
146
+ * @returns The removed blocks.
147
+ */ removeBlocksAfter(blockNumber) {
148
+ return this.store.transactionAsync(async ()=>{
149
+ // First get the blocks to be removed so we can clean up contract data
150
+ const removedBlocks = await this.store.removeBlocksAfter(blockNumber);
151
+ // Clean up contract data and logs for the removed blocks
152
+ await Promise.all([
153
+ this.store.deleteLogs(removedBlocks),
154
+ ...removedBlocks.map((block)=>this.removeBlockDataFromDB(block))
155
+ ]);
156
+ return removedBlocks;
157
+ });
158
+ }
159
+ /**
160
+ * Unwinds checkpoints from the store with reverse contract extraction.
161
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
162
+ * that was stored for the unwound checkpoints.
163
+ *
164
+ * @param from - The checkpoint number to unwind from (must be the current tip).
165
+ * @param checkpointsToUnwind - The number of checkpoints to unwind.
166
+ * @returns True if the operation is successful.
167
+ */ async unwindCheckpoints(from, checkpointsToUnwind) {
168
+ if (checkpointsToUnwind <= 0) {
169
+ throw new Error(`Cannot unwind ${checkpointsToUnwind} blocks`);
170
+ }
171
+ const last = await this.store.getSynchedCheckpointNumber();
172
+ if (from != last) {
173
+ throw new Error(`Cannot unwind checkpoints from checkpoint ${from} when the last checkpoint is ${last}`);
174
+ }
175
+ const blocks = [];
176
+ const lastCheckpointNumber = from + checkpointsToUnwind - 1;
177
+ for(let checkpointNumber = from; checkpointNumber <= lastCheckpointNumber; checkpointNumber++){
178
+ const blocksForCheckpoint = await this.store.getBlocksForCheckpoint(checkpointNumber);
179
+ if (!blocksForCheckpoint) {
180
+ continue;
181
+ }
182
+ blocks.push(...blocksForCheckpoint);
183
+ }
184
+ const opResults = await Promise.all([
185
+ // Prune rolls back to the last proven block, which is by definition valid
186
+ this.store.setPendingChainValidationStatus({
187
+ valid: true
188
+ }),
189
+ // Remove contract data for all blocks being unwound
190
+ ...blocks.map((block)=>this.removeBlockDataFromDB(block)),
191
+ this.store.deleteLogs(blocks),
192
+ this.store.unwindCheckpoints(from, checkpointsToUnwind)
193
+ ]);
194
+ return opResults.every(Boolean);
195
+ }
196
+ /** Extracts and stores contract data from a single block. */ addBlockDataToDB(block) {
197
+ return this.editContractBlockData(block, 0);
198
+ }
199
+ /** Removes contract data associated with a block. */ removeBlockDataFromDB(block) {
200
+ return this.editContractBlockData(block, 1);
201
+ }
202
+ /** Adds or remove contract data associated with a block. */ async editContractBlockData(block, operation) {
203
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
204
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
205
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
206
+ return (await Promise.all([
207
+ this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
208
+ this.updateDeployedContractInstances(privateLogs, block.number, operation),
209
+ this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
210
+ operation === 0 ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number) : Promise.resolve(true)
211
+ ])).every(Boolean);
212
+ }
213
+ /**
214
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
215
+ */ async updatePublishedContractClasses(allLogs, blockNum, operation) {
216
+ const contractClassPublishedEvents = allLogs.filter((log)=>ContractClassPublishedEvent.isContractClassPublishedEvent(log)).map((log)=>ContractClassPublishedEvent.fromLog(log));
217
+ const contractClasses = await Promise.all(contractClassPublishedEvents.map((e)=>e.toContractClassPublic()));
218
+ if (contractClasses.length > 0) {
219
+ contractClasses.forEach((c)=>this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
220
+ if (operation == 0) {
221
+ // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
222
+ const commitments = await Promise.all(contractClasses.map((c)=>computePublicBytecodeCommitment(c.packedBytecode)));
223
+ return await this.store.addContractClasses(contractClasses, commitments, blockNum);
224
+ } else if (operation == 1) {
225
+ return await this.store.deleteContractClasses(contractClasses, blockNum);
226
+ }
227
+ }
228
+ return true;
229
+ }
230
+ /**
231
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
232
+ */ async updateDeployedContractInstances(allLogs, blockNum, operation) {
233
+ const contractInstances = allLogs.filter((log)=>ContractInstancePublishedEvent.isContractInstancePublishedEvent(log)).map((log)=>ContractInstancePublishedEvent.fromLog(log)).map((e)=>e.toContractInstance());
234
+ if (contractInstances.length > 0) {
235
+ contractInstances.forEach((c)=>this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`));
236
+ if (operation == 0) {
237
+ return await this.store.addContractInstances(contractInstances, blockNum);
238
+ } else if (operation == 1) {
239
+ return await this.store.deleteContractInstances(contractInstances, blockNum);
240
+ }
241
+ }
242
+ return true;
243
+ }
244
+ /**
245
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
246
+ */ async updateUpdatedContractInstances(allLogs, timestamp, operation) {
247
+ const contractUpdates = allLogs.filter((log)=>ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log)).map((log)=>ContractInstanceUpdatedEvent.fromLog(log)).map((e)=>e.toContractInstanceUpdate());
248
+ if (contractUpdates.length > 0) {
249
+ contractUpdates.forEach((c)=>this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`));
250
+ if (operation == 0) {
251
+ return await this.store.addContractInstanceUpdates(contractUpdates, timestamp);
252
+ } else if (operation == 1) {
253
+ return await this.store.deleteContractInstanceUpdates(contractUpdates, timestamp);
254
+ }
255
+ }
256
+ return true;
257
+ }
258
+ /**
259
+ * Stores the functions that were broadcasted individually.
260
+ *
261
+ * @dev Beware that there is not a delete variant of this, since they are added to contract classes
262
+ * and will be deleted as part of the class if needed.
263
+ */ async storeBroadcastedIndividualFunctions(allLogs, _blockNum) {
264
+ // Filter out private and utility function broadcast events
265
+ const privateFnEvents = allLogs.filter((log)=>PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log)).map((log)=>PrivateFunctionBroadcastedEvent.fromLog(log));
266
+ const utilityFnEvents = allLogs.filter((log)=>UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log)).map((log)=>UtilityFunctionBroadcastedEvent.fromLog(log));
267
+ // Group all events by contract class id
268
+ for (const [classIdString, classEvents] of Object.entries(groupBy([
269
+ ...privateFnEvents,
270
+ ...utilityFnEvents
271
+ ], (e)=>e.contractClassId.toString()))){
272
+ const contractClassId = Fr.fromHexString(classIdString);
273
+ const contractClass = await this.store.getContractClass(contractClassId);
274
+ if (!contractClass) {
275
+ this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
276
+ continue;
277
+ }
278
+ // Split private and utility functions, and filter out invalid ones
279
+ const allFns = classEvents.map((e)=>e.toFunctionWithMembershipProof());
280
+ const privateFns = allFns.filter((fn)=>'utilityFunctionsTreeRoot' in fn);
281
+ const utilityFns = allFns.filter((fn)=>'privateFunctionsArtifactTreeRoot' in fn);
282
+ const privateFunctionsWithValidity = await Promise.all(privateFns.map(async (fn)=>({
283
+ fn,
284
+ valid: await isValidPrivateFunctionMembershipProof(fn, contractClass)
285
+ })));
286
+ const validPrivateFns = privateFunctionsWithValidity.filter(({ valid })=>valid).map(({ fn })=>fn);
287
+ const utilityFunctionsWithValidity = await Promise.all(utilityFns.map(async (fn)=>({
288
+ fn,
289
+ valid: await isValidUtilityFunctionMembershipProof(fn, contractClass)
290
+ })));
291
+ const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid })=>valid).map(({ fn })=>fn);
292
+ const validFnCount = validPrivateFns.length + validUtilityFns.length;
293
+ if (validFnCount !== allFns.length) {
294
+ this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
295
+ }
296
+ // Store the functions in the contract class in a single operation
297
+ if (validFnCount > 0) {
298
+ this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
299
+ }
300
+ return await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
301
+ }
302
+ return true;
303
+ }
304
+ }