@aztec/archiver 0.0.1-commit.9b94fc1 → 0.0.1-commit.9badcec54

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 (213) hide show
  1. package/README.md +162 -22
  2. package/dest/archiver.d.ts +140 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +750 -0
  5. package/dest/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +24 -7
  8. package/dest/errors.d.ts +65 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +91 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +99 -15
  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/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +135 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +403 -0
  26. package/dest/l1/data_retrieval.d.ts +88 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +87 -160
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +91 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +222 -0
  47. package/dest/modules/data_store_updater.d.ts +86 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +333 -0
  50. package/dest/modules/instrumentation.d.ts +52 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/modules/instrumentation.js +138 -0
  53. package/dest/modules/l1_synchronizer.d.ts +73 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1154 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +9 -3
  59. package/dest/store/block_store.d.ts +230 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +942 -0
  62. package/dest/store/contract_class_store.d.ts +17 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/store/contract_class_store.js +64 -0
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +7 -3
  68. package/dest/store/kv_archiver_store.d.ts +377 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +494 -0
  71. package/dest/store/l2_tips_cache.d.ts +20 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +109 -0
  74. package/dest/store/log_store.d.ts +57 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +531 -0
  77. package/dest/store/message_store.d.ts +44 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +36 -23
  80. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +210 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +490 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +23 -12
  99. package/dest/test/mock_l2_block_source.d.ts +59 -20
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +276 -85
  102. package/dest/test/mock_structs.d.ts +83 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +157 -11
  105. package/dest/test/noop_l1_archiver.d.ts +26 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +71 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +510 -0
  110. package/src/{archiver/config.ts → config.ts} +37 -14
  111. package/src/errors.ts +146 -0
  112. package/src/factory.ts +154 -17
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +55 -0
  116. package/src/l1/bin/retrieve-calldata.ts +194 -0
  117. package/src/l1/calldata_retriever.ts +512 -0
  118. package/src/{archiver → l1}/data_retrieval.ts +146 -233
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +152 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +347 -0
  125. package/src/modules/data_store_updater.ts +437 -0
  126. package/src/modules/instrumentation.ts +196 -0
  127. package/src/modules/l1_synchronizer.ts +961 -0
  128. package/src/{archiver → modules}/validation.ts +13 -8
  129. package/src/store/block_store.ts +1245 -0
  130. package/src/store/contract_class_store.ts +82 -0
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +10 -7
  132. package/src/store/kv_archiver_store.ts +713 -0
  133. package/src/store/l2_tips_cache.ts +134 -0
  134. package/src/store/log_store.ts +733 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +48 -28
  136. package/src/{archiver/structs → structs}/inbox_message.ts +7 -7
  137. package/src/{archiver/structs → structs}/published.ts +0 -1
  138. package/src/test/fake_l1_state.ts +747 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +19 -11
  149. package/src/test/mock_l2_block_source.ts +346 -93
  150. package/src/test/mock_structs.ts +289 -13
  151. package/src/test/noop_l1_archiver.ts +114 -0
  152. package/dest/archiver/archiver.d.ts +0 -287
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1408
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/errors.d.ts +0 -12
  166. package/dest/archiver/errors.d.ts.map +0 -1
  167. package/dest/archiver/errors.js +0 -17
  168. package/dest/archiver/index.d.ts +0 -7
  169. package/dest/archiver/index.d.ts.map +0 -1
  170. package/dest/archiver/index.js +0 -4
  171. package/dest/archiver/instrumentation.d.ts +0 -35
  172. package/dest/archiver/instrumentation.d.ts.map +0 -1
  173. package/dest/archiver/instrumentation.js +0 -140
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  175. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  176. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  178. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  179. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  180. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  181. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  183. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  184. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  185. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  186. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  187. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  188. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  189. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  190. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  191. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  192. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  193. package/dest/archiver/structs/published.d.ts +0 -3
  194. package/dest/archiver/structs/published.d.ts.map +0 -1
  195. package/dest/archiver/validation.d.ts +0 -17
  196. package/dest/archiver/validation.d.ts.map +0 -1
  197. package/dest/rpc/index.d.ts +0 -9
  198. package/dest/rpc/index.d.ts.map +0 -1
  199. package/dest/rpc/index.js +0 -15
  200. package/src/archiver/archiver.ts +0 -1858
  201. package/src/archiver/archiver_store.ts +0 -305
  202. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  203. package/src/archiver/errors.ts +0 -26
  204. package/src/archiver/index.ts +0 -6
  205. package/src/archiver/instrumentation.ts +0 -187
  206. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  207. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  208. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  209. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  210. package/src/rpc/index.ts +0 -16
  211. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  212. /package/dest/{archiver/structs → structs}/published.js +0 -0
  213. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,733 @@
1
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { compactArray, filterAsync } from '@aztec/foundation/collection';
4
+ import { createLogger } from '@aztec/foundation/log';
5
+ import { BufferReader, numToUInt32BE } from '@aztec/foundation/serialize';
6
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
7
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
8
+ import { BlockHash, L2Block } from '@aztec/stdlib/block';
9
+ import { MAX_LOGS_PER_TAG } from '@aztec/stdlib/interfaces/api-limit';
10
+ import type { GetContractClassLogsResponse, GetPublicLogsResponse } from '@aztec/stdlib/interfaces/client';
11
+ import {
12
+ ContractClassLog,
13
+ ExtendedContractClassLog,
14
+ ExtendedPublicLog,
15
+ type LogFilter,
16
+ LogId,
17
+ PublicLog,
18
+ type SiloedTag,
19
+ Tag,
20
+ TxScopedL2Log,
21
+ } from '@aztec/stdlib/logs';
22
+ import { TxHash } from '@aztec/stdlib/tx';
23
+
24
+ import { OutOfOrderLogInsertionError } from '../errors.js';
25
+ import type { BlockStore } from './block_store.js';
26
+
27
+ /**
28
+ * A store for logs
29
+ */
30
+ export class LogStore {
31
+ // `tag` --> private logs
32
+ #privateLogsByTag: AztecAsyncMap<string, Buffer[]>;
33
+ // `{contractAddress}_${tag}` --> public logs
34
+ #publicLogsByContractAndTag: AztecAsyncMap<string, Buffer[]>;
35
+ #privateLogKeysByBlock: AztecAsyncMap<number, string[]>;
36
+ #publicLogKeysByBlock: AztecAsyncMap<number, string[]>;
37
+ #publicLogsByBlock: AztecAsyncMap<number, Buffer>;
38
+ #contractClassLogsByBlock: AztecAsyncMap<number, Buffer>;
39
+ #logsMaxPageSize: number;
40
+ #log = createLogger('archiver:log_store');
41
+
42
+ constructor(
43
+ private db: AztecAsyncKVStore,
44
+ private blockStore: BlockStore,
45
+ logsMaxPageSize: number = 1000,
46
+ ) {
47
+ this.#privateLogsByTag = db.openMap('archiver_private_tagged_logs_by_tag');
48
+ this.#publicLogsByContractAndTag = db.openMap('archiver_public_tagged_logs_by_tag');
49
+ this.#privateLogKeysByBlock = db.openMap('archiver_private_log_keys_by_block');
50
+ this.#publicLogKeysByBlock = db.openMap('archiver_public_log_keys_by_block');
51
+ this.#publicLogsByBlock = db.openMap('archiver_public_logs_by_block');
52
+ this.#contractClassLogsByBlock = db.openMap('archiver_contract_class_logs_by_block');
53
+
54
+ this.#logsMaxPageSize = logsMaxPageSize;
55
+ }
56
+
57
+ /**
58
+ * Extracts tagged logs from a single block, grouping them into private and public maps.
59
+ *
60
+ * @param block - The L2 block to extract logs from.
61
+ * @returns An object containing the private and public tagged logs for the block.
62
+ */
63
+ #extractTaggedLogsFromBlock(block: L2Block) {
64
+ // SiloedTag (as string) -> array of log buffers.
65
+ const privateTaggedLogs = new Map<string, Buffer[]>();
66
+ // "{contractAddress}_{tag}" (as string) -> array of log buffers.
67
+ const publicTaggedLogs = new Map<string, Buffer[]>();
68
+
69
+ block.body.txEffects.forEach(txEffect => {
70
+ const txHash = txEffect.txHash;
71
+
72
+ txEffect.privateLogs.forEach(log => {
73
+ // Private logs use SiloedTag (already siloed by kernel)
74
+ const tag = log.fields[0];
75
+ this.#log.debug(`Found private log with tag ${tag.toString()} in block ${block.number}`);
76
+
77
+ const currentLogs = privateTaggedLogs.get(tag.toString()) ?? [];
78
+ currentLogs.push(
79
+ new TxScopedL2Log(
80
+ txHash,
81
+ block.number,
82
+ block.timestamp,
83
+ log.getEmittedFields(),
84
+ txEffect.noteHashes,
85
+ txEffect.nullifiers[0],
86
+ ).toBuffer(),
87
+ );
88
+ privateTaggedLogs.set(tag.toString(), currentLogs);
89
+ });
90
+
91
+ txEffect.publicLogs.forEach(log => {
92
+ // Public logs use Tag directly (not siloed) and are stored with contract address
93
+ const tag = log.fields[0];
94
+ const contractAddress = log.contractAddress;
95
+ const key = `${contractAddress.toString()}_${tag.toString()}`;
96
+ this.#log.debug(
97
+ `Found public log with tag ${tag.toString()} from contract ${contractAddress.toString()} in block ${block.number}`,
98
+ );
99
+
100
+ const currentLogs = publicTaggedLogs.get(key) ?? [];
101
+ currentLogs.push(
102
+ new TxScopedL2Log(
103
+ txHash,
104
+ block.number,
105
+ block.timestamp,
106
+ log.getEmittedFields(),
107
+ txEffect.noteHashes,
108
+ txEffect.nullifiers[0],
109
+ ).toBuffer(),
110
+ );
111
+ publicTaggedLogs.set(key, currentLogs);
112
+ });
113
+ });
114
+
115
+ return { privateTaggedLogs, publicTaggedLogs };
116
+ }
117
+
118
+ /**
119
+ * Extracts and aggregates tagged logs from a list of blocks.
120
+ * @param blocks - The blocks to extract logs from.
121
+ * @returns A map from tag (as string) to an array of serialized private logs belonging to that tag, and a map from
122
+ * "{contractAddress}_{tag}" (as string) to an array of serialized public logs belonging to that key.
123
+ */
124
+ #extractTaggedLogs(blocks: L2Block[]): {
125
+ privateTaggedLogs: Map<string, Buffer[]>;
126
+ publicTaggedLogs: Map<string, Buffer[]>;
127
+ } {
128
+ const taggedLogsInBlocks = blocks.map(block => this.#extractTaggedLogsFromBlock(block));
129
+
130
+ // Now we merge the maps from each block into a single map.
131
+ const privateTaggedLogs = taggedLogsInBlocks.reduce((acc, { privateTaggedLogs }) => {
132
+ for (const [tag, logs] of privateTaggedLogs.entries()) {
133
+ const currentLogs = acc.get(tag) ?? [];
134
+ acc.set(tag, currentLogs.concat(logs));
135
+ }
136
+ return acc;
137
+ }, new Map<string, Buffer[]>());
138
+
139
+ const publicTaggedLogs = taggedLogsInBlocks.reduce((acc, { publicTaggedLogs }) => {
140
+ for (const [key, logs] of publicTaggedLogs.entries()) {
141
+ const currentLogs = acc.get(key) ?? [];
142
+ acc.set(key, currentLogs.concat(logs));
143
+ }
144
+ return acc;
145
+ }, new Map<string, Buffer[]>());
146
+
147
+ return { privateTaggedLogs, publicTaggedLogs };
148
+ }
149
+
150
+ async #addPrivateLogs(blocks: L2Block[]): Promise<void> {
151
+ const newBlocks = await filterAsync(
152
+ blocks,
153
+ async block => !(await this.#privateLogKeysByBlock.hasAsync(block.number)),
154
+ );
155
+
156
+ const { privateTaggedLogs } = this.#extractTaggedLogs(newBlocks);
157
+ const keysOfPrivateLogsToUpdate = Array.from(privateTaggedLogs.keys());
158
+
159
+ const currentPrivateTaggedLogs = await Promise.all(
160
+ keysOfPrivateLogsToUpdate.map(async key => ({
161
+ tag: key,
162
+ logBuffers: await this.#privateLogsByTag.getAsync(key),
163
+ })),
164
+ );
165
+
166
+ for (const taggedLogBuffer of currentPrivateTaggedLogs) {
167
+ if (taggedLogBuffer.logBuffers && taggedLogBuffer.logBuffers.length > 0) {
168
+ const newLogs = privateTaggedLogs.get(taggedLogBuffer.tag)!;
169
+ if (newLogs.length === 0) {
170
+ continue;
171
+ }
172
+ const lastExisting = TxScopedL2Log.fromBuffer(taggedLogBuffer.logBuffers.at(-1)!);
173
+ const firstNew = TxScopedL2Log.fromBuffer(newLogs[0]);
174
+ if (lastExisting.blockNumber > firstNew.blockNumber) {
175
+ throw new OutOfOrderLogInsertionError(
176
+ 'private',
177
+ taggedLogBuffer.tag,
178
+ lastExisting.blockNumber,
179
+ firstNew.blockNumber,
180
+ );
181
+ }
182
+ privateTaggedLogs.set(taggedLogBuffer.tag, taggedLogBuffer.logBuffers.concat(newLogs));
183
+ }
184
+ }
185
+
186
+ for (const block of newBlocks) {
187
+ const privateTagsInBlock: string[] = [];
188
+ for (const [tag, logs] of privateTaggedLogs.entries()) {
189
+ await this.#privateLogsByTag.set(tag, logs);
190
+ privateTagsInBlock.push(tag);
191
+ }
192
+ await this.#privateLogKeysByBlock.set(block.number, privateTagsInBlock);
193
+ }
194
+ }
195
+
196
+ async #addPublicLogs(blocks: L2Block[]): Promise<void> {
197
+ const newBlocks = await filterAsync(
198
+ blocks,
199
+ async block => !(await this.#publicLogKeysByBlock.hasAsync(block.number)),
200
+ );
201
+
202
+ const { publicTaggedLogs } = this.#extractTaggedLogs(newBlocks);
203
+ const keysOfPublicLogsToUpdate = Array.from(publicTaggedLogs.keys());
204
+
205
+ const currentPublicTaggedLogs = await Promise.all(
206
+ keysOfPublicLogsToUpdate.map(async key => ({
207
+ tag: key,
208
+ logBuffers: await this.#publicLogsByContractAndTag.getAsync(key),
209
+ })),
210
+ );
211
+
212
+ for (const taggedLogBuffer of currentPublicTaggedLogs) {
213
+ if (taggedLogBuffer.logBuffers && taggedLogBuffer.logBuffers.length > 0) {
214
+ const newLogs = publicTaggedLogs.get(taggedLogBuffer.tag)!;
215
+ if (newLogs.length === 0) {
216
+ continue;
217
+ }
218
+ const lastExisting = TxScopedL2Log.fromBuffer(taggedLogBuffer.logBuffers.at(-1)!);
219
+ const firstNew = TxScopedL2Log.fromBuffer(newLogs[0]);
220
+ if (lastExisting.blockNumber > firstNew.blockNumber) {
221
+ throw new OutOfOrderLogInsertionError(
222
+ 'public',
223
+ taggedLogBuffer.tag,
224
+ lastExisting.blockNumber,
225
+ firstNew.blockNumber,
226
+ );
227
+ }
228
+ publicTaggedLogs.set(taggedLogBuffer.tag, taggedLogBuffer.logBuffers.concat(newLogs));
229
+ }
230
+ }
231
+
232
+ for (const block of newBlocks) {
233
+ const blockHash = await block.hash();
234
+ const publicTagsInBlock: string[] = [];
235
+ for (const [tag, logs] of publicTaggedLogs.entries()) {
236
+ await this.#publicLogsByContractAndTag.set(tag, logs);
237
+ publicTagsInBlock.push(tag);
238
+ }
239
+ await this.#publicLogKeysByBlock.set(block.number, publicTagsInBlock);
240
+
241
+ const publicLogsInBlock = block.body.txEffects
242
+ .map((txEffect, txIndex) =>
243
+ [
244
+ numToUInt32BE(txIndex),
245
+ txEffect.txHash.toBuffer(),
246
+ numToUInt32BE(txEffect.publicLogs.length),
247
+ txEffect.publicLogs.map(log => log.toBuffer()),
248
+ ].flat(),
249
+ )
250
+ .flat();
251
+
252
+ await this.#publicLogsByBlock.set(block.number, this.#packWithBlockHash(blockHash, publicLogsInBlock));
253
+ }
254
+ }
255
+
256
+ async #addContractClassLogs(blocks: L2Block[]): Promise<void> {
257
+ const newBlocks = await filterAsync(
258
+ blocks,
259
+ async block => !(await this.#contractClassLogsByBlock.hasAsync(block.number)),
260
+ );
261
+
262
+ for (const block of newBlocks) {
263
+ const blockHash = await block.hash();
264
+
265
+ const contractClassLogsInBlock = block.body.txEffects
266
+ .map((txEffect, txIndex) =>
267
+ [
268
+ numToUInt32BE(txIndex),
269
+ txEffect.txHash.toBuffer(),
270
+ numToUInt32BE(txEffect.contractClassLogs.length),
271
+ txEffect.contractClassLogs.map(log => log.toBuffer()),
272
+ ].flat(),
273
+ )
274
+ .flat();
275
+
276
+ await this.#contractClassLogsByBlock.set(
277
+ block.number,
278
+ this.#packWithBlockHash(blockHash, contractClassLogsInBlock),
279
+ );
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Append new logs to the store's list.
285
+ * @param blocks - The blocks for which to add the logs.
286
+ * @returns True if the operation is successful.
287
+ */
288
+ addLogs(blocks: L2Block[]): Promise<boolean> {
289
+ return this.db.transactionAsync(async () => {
290
+ await Promise.all([
291
+ this.#addPrivateLogs(blocks),
292
+ this.#addPublicLogs(blocks),
293
+ this.#addContractClassLogs(blocks),
294
+ ]);
295
+ return true;
296
+ });
297
+ }
298
+
299
+ #packWithBlockHash(blockHash: BlockHash, data: Buffer<ArrayBufferLike>[]): Buffer<ArrayBufferLike> {
300
+ return Buffer.concat([blockHash.toBuffer(), ...data]);
301
+ }
302
+
303
+ #unpackBlockHash(reader: BufferReader): BlockHash {
304
+ if (reader.remainingBytes() === 0) {
305
+ throw new Error('Failed to read block hash from log entry buffer');
306
+ }
307
+
308
+ return BlockHash.fromBuffer(reader);
309
+ }
310
+
311
+ deleteLogs(blocks: L2Block[]): Promise<boolean> {
312
+ return this.db.transactionAsync(async () => {
313
+ const blockNumbers = new Set(blocks.map(block => block.number));
314
+ const firstBlockToDelete = Math.min(...blockNumbers);
315
+
316
+ // Collect all unique private tags across all blocks being deleted
317
+ const allPrivateTags = new Set(
318
+ compactArray(await Promise.all(blocks.map(block => this.#privateLogKeysByBlock.getAsync(block.number)))).flat(),
319
+ );
320
+
321
+ // Trim private logs: for each tag, delete all instances including and after the first block being deleted.
322
+ // This hinges on the invariant that logs for a given tag are always inserted in order of block number, which is enforced in #addPrivateLogs.
323
+ for (const tag of allPrivateTags) {
324
+ const existing = await this.#privateLogsByTag.getAsync(tag);
325
+ if (existing === undefined || existing.length === 0) {
326
+ continue;
327
+ }
328
+ const lastIndexToKeep = existing.findLastIndex(
329
+ buf => TxScopedL2Log.getBlockNumberFromBuffer(buf) < firstBlockToDelete,
330
+ );
331
+ const remaining = existing.slice(0, lastIndexToKeep + 1);
332
+ await (remaining.length > 0 ? this.#privateLogsByTag.set(tag, remaining) : this.#privateLogsByTag.delete(tag));
333
+ }
334
+
335
+ // Collect all unique public keys across all blocks being deleted
336
+ const allPublicKeys = new Set(
337
+ compactArray(await Promise.all(blocks.map(block => this.#publicLogKeysByBlock.getAsync(block.number)))).flat(),
338
+ );
339
+
340
+ // And do the same as we did with private logs
341
+ for (const key of allPublicKeys) {
342
+ const existing = await this.#publicLogsByContractAndTag.getAsync(key);
343
+ if (existing === undefined || existing.length === 0) {
344
+ continue;
345
+ }
346
+ const lastIndexToKeep = existing.findLastIndex(
347
+ buf => TxScopedL2Log.getBlockNumberFromBuffer(buf) < firstBlockToDelete,
348
+ );
349
+ const remaining = existing.slice(0, lastIndexToKeep + 1);
350
+ await (remaining.length > 0
351
+ ? this.#publicLogsByContractAndTag.set(key, remaining)
352
+ : this.#publicLogsByContractAndTag.delete(key));
353
+ }
354
+
355
+ // After trimming the tagged logs, we can delete the block-level keys that track which tags are in which blocks.
356
+ await Promise.all(
357
+ blocks.map(block =>
358
+ Promise.all([
359
+ this.#publicLogsByBlock.delete(block.number),
360
+ this.#privateLogKeysByBlock.delete(block.number),
361
+ this.#publicLogKeysByBlock.delete(block.number),
362
+ this.#contractClassLogsByBlock.delete(block.number),
363
+ ]),
364
+ ),
365
+ );
366
+
367
+ return true;
368
+ });
369
+ }
370
+
371
+ /**
372
+ * Gets private logs that match any of the `tags`. For each tag, an array of matching logs is returned. An empty
373
+ * array implies no logs match that tag.
374
+ * @param tags - The tags to search for.
375
+ * @param page - The page number (0-indexed) for pagination.
376
+ * @param upToBlockNumber - If set, only return logs from blocks up to and including this block number.
377
+ * @returns An array of log arrays, one per tag. Returns at most MAX_LOGS_PER_TAG logs per tag per page. If
378
+ * MAX_LOGS_PER_TAG logs are returned for a tag, the caller should fetch the next page to check for more logs.
379
+ */
380
+ async getPrivateLogsByTags(
381
+ tags: SiloedTag[],
382
+ page: number = 0,
383
+ upToBlockNumber?: BlockNumber,
384
+ ): Promise<TxScopedL2Log[][]> {
385
+ const logs = await Promise.all(tags.map(tag => this.#privateLogsByTag.getAsync(tag.toString())));
386
+
387
+ const start = page * MAX_LOGS_PER_TAG;
388
+ const end = start + MAX_LOGS_PER_TAG;
389
+
390
+ return logs.map(logBuffers => {
391
+ const deserialized = logBuffers?.slice(start, end).map(buf => TxScopedL2Log.fromBuffer(buf)) ?? [];
392
+ if (upToBlockNumber !== undefined) {
393
+ const cutoff = deserialized.findIndex(log => log.blockNumber > upToBlockNumber);
394
+ if (cutoff !== -1) {
395
+ return deserialized.slice(0, cutoff);
396
+ }
397
+ }
398
+ return deserialized;
399
+ });
400
+ }
401
+
402
+ /**
403
+ * Gets public logs that match any of the `tags` from the specified contract. For each tag, an array of matching
404
+ * logs is returned. An empty array implies no logs match that tag.
405
+ * @param contractAddress - The contract address to search logs for.
406
+ * @param tags - The tags to search for.
407
+ * @param page - The page number (0-indexed) for pagination.
408
+ * @param upToBlockNumber - If set, only return logs from blocks up to and including this block number.
409
+ * @returns An array of log arrays, one per tag. Returns at most MAX_LOGS_PER_TAG logs per tag per page. If
410
+ * MAX_LOGS_PER_TAG logs are returned for a tag, the caller should fetch the next page to check for more logs.
411
+ */
412
+ async getPublicLogsByTagsFromContract(
413
+ contractAddress: AztecAddress,
414
+ tags: Tag[],
415
+ page: number = 0,
416
+ upToBlockNumber?: BlockNumber,
417
+ ): Promise<TxScopedL2Log[][]> {
418
+ const logs = await Promise.all(
419
+ tags.map(tag => {
420
+ const key = `${contractAddress.toString()}_${tag.value.toString()}`;
421
+ return this.#publicLogsByContractAndTag.getAsync(key);
422
+ }),
423
+ );
424
+ const start = page * MAX_LOGS_PER_TAG;
425
+ const end = start + MAX_LOGS_PER_TAG;
426
+
427
+ return logs.map(logBuffers => {
428
+ const deserialized = logBuffers?.slice(start, end).map(buf => TxScopedL2Log.fromBuffer(buf)) ?? [];
429
+ if (upToBlockNumber !== undefined) {
430
+ const cutoff = deserialized.findIndex(log => log.blockNumber > upToBlockNumber);
431
+ if (cutoff !== -1) {
432
+ return deserialized.slice(0, cutoff);
433
+ }
434
+ }
435
+ return deserialized;
436
+ });
437
+ }
438
+
439
+ /**
440
+ * Gets public logs based on the provided filter.
441
+ * @param filter - The filter to apply to the logs.
442
+ * @returns The requested logs.
443
+ */
444
+ getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
445
+ if (filter.afterLog) {
446
+ return this.#filterPublicLogsBetweenBlocks(filter);
447
+ } else if (filter.txHash) {
448
+ return this.#filterPublicLogsOfTx(filter);
449
+ } else {
450
+ return this.#filterPublicLogsBetweenBlocks(filter);
451
+ }
452
+ }
453
+
454
+ async #filterPublicLogsOfTx(filter: LogFilter): Promise<GetPublicLogsResponse> {
455
+ if (!filter.txHash) {
456
+ throw new Error('Missing txHash');
457
+ }
458
+
459
+ const [blockNumber, txIndex] = (await this.blockStore.getTxLocation(filter.txHash)) ?? [];
460
+ if (typeof blockNumber !== 'number' || typeof txIndex !== 'number') {
461
+ return { logs: [], maxLogsHit: false };
462
+ }
463
+
464
+ const buffer = (await this.#publicLogsByBlock.getAsync(blockNumber)) ?? Buffer.alloc(0);
465
+ const publicLogsInBlock: { txHash: TxHash; logs: PublicLog[] }[] = [];
466
+ const reader = new BufferReader(buffer);
467
+
468
+ const blockHash = this.#unpackBlockHash(reader);
469
+
470
+ while (reader.remainingBytes() > 0) {
471
+ const indexOfTx = reader.readNumber();
472
+ const txHash = reader.readObject(TxHash);
473
+ const numLogsInTx = reader.readNumber();
474
+ publicLogsInBlock[indexOfTx] = { txHash, logs: [] };
475
+ for (let i = 0; i < numLogsInTx; i++) {
476
+ publicLogsInBlock[indexOfTx].logs.push(reader.readObject(PublicLog));
477
+ }
478
+ }
479
+
480
+ const txData = publicLogsInBlock[txIndex];
481
+
482
+ const logs: ExtendedPublicLog[] = [];
483
+ const maxLogsHit = this.#accumulatePublicLogs(
484
+ logs,
485
+ blockNumber,
486
+ blockHash,
487
+ txIndex,
488
+ txData.txHash,
489
+ txData.logs,
490
+ filter,
491
+ );
492
+
493
+ return { logs, maxLogsHit };
494
+ }
495
+
496
+ async #filterPublicLogsBetweenBlocks(filter: LogFilter): Promise<GetPublicLogsResponse> {
497
+ const start =
498
+ filter.afterLog?.blockNumber ?? Math.max(filter.fromBlock ?? INITIAL_L2_BLOCK_NUM, INITIAL_L2_BLOCK_NUM);
499
+ const end = filter.toBlock;
500
+
501
+ if (typeof end === 'number' && end < start) {
502
+ return {
503
+ logs: [],
504
+ maxLogsHit: true,
505
+ };
506
+ }
507
+
508
+ const logs: ExtendedPublicLog[] = [];
509
+
510
+ let maxLogsHit = false;
511
+ loopOverBlocks: for await (const [blockNumber, logBuffer] of this.#publicLogsByBlock.entriesAsync({ start, end })) {
512
+ const publicLogsInBlock: { txHash: TxHash; logs: PublicLog[] }[] = [];
513
+ const reader = new BufferReader(logBuffer);
514
+
515
+ const blockHash = this.#unpackBlockHash(reader);
516
+
517
+ while (reader.remainingBytes() > 0) {
518
+ const indexOfTx = reader.readNumber();
519
+ const txHash = reader.readObject(TxHash);
520
+ const numLogsInTx = reader.readNumber();
521
+ publicLogsInBlock[indexOfTx] = { txHash, logs: [] };
522
+ for (let i = 0; i < numLogsInTx; i++) {
523
+ publicLogsInBlock[indexOfTx].logs.push(reader.readObject(PublicLog));
524
+ }
525
+ }
526
+ for (let txIndex = filter.afterLog?.txIndex ?? 0; txIndex < publicLogsInBlock.length; txIndex++) {
527
+ const txData = publicLogsInBlock[txIndex];
528
+ maxLogsHit = this.#accumulatePublicLogs(
529
+ logs,
530
+ blockNumber,
531
+ blockHash,
532
+ txIndex,
533
+ txData.txHash,
534
+ txData.logs,
535
+ filter,
536
+ );
537
+ if (maxLogsHit) {
538
+ this.#log.debug(`Max logs hit at block ${blockNumber}`);
539
+ break loopOverBlocks;
540
+ }
541
+ }
542
+ }
543
+
544
+ return { logs, maxLogsHit };
545
+ }
546
+
547
+ /**
548
+ * Gets contract class logs based on the provided filter.
549
+ * @param filter - The filter to apply to the logs.
550
+ * @returns The requested logs.
551
+ */
552
+ getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
553
+ if (filter.afterLog) {
554
+ return this.#filterContractClassLogsBetweenBlocks(filter);
555
+ } else if (filter.txHash) {
556
+ return this.#filterContractClassLogsOfTx(filter);
557
+ } else {
558
+ return this.#filterContractClassLogsBetweenBlocks(filter);
559
+ }
560
+ }
561
+
562
+ async #filterContractClassLogsOfTx(filter: LogFilter): Promise<GetContractClassLogsResponse> {
563
+ if (!filter.txHash) {
564
+ throw new Error('Missing txHash');
565
+ }
566
+
567
+ const [blockNumber, txIndex] = (await this.blockStore.getTxLocation(filter.txHash)) ?? [];
568
+ if (typeof blockNumber !== 'number' || typeof txIndex !== 'number') {
569
+ return { logs: [], maxLogsHit: false };
570
+ }
571
+ const contractClassLogsBuffer = (await this.#contractClassLogsByBlock.getAsync(blockNumber)) ?? Buffer.alloc(0);
572
+ const contractClassLogsInBlock: { txHash: TxHash; logs: ContractClassLog[] }[] = [];
573
+
574
+ const reader = new BufferReader(contractClassLogsBuffer);
575
+ const blockHash = this.#unpackBlockHash(reader);
576
+
577
+ while (reader.remainingBytes() > 0) {
578
+ const indexOfTx = reader.readNumber();
579
+ const txHash = reader.readObject(TxHash);
580
+ const numLogsInTx = reader.readNumber();
581
+ contractClassLogsInBlock[indexOfTx] = { txHash, logs: [] };
582
+ for (let i = 0; i < numLogsInTx; i++) {
583
+ contractClassLogsInBlock[indexOfTx].logs.push(reader.readObject(ContractClassLog));
584
+ }
585
+ }
586
+
587
+ const txData = contractClassLogsInBlock[txIndex];
588
+
589
+ const logs: ExtendedContractClassLog[] = [];
590
+ const maxLogsHit = this.#accumulateContractClassLogs(
591
+ logs,
592
+ blockNumber,
593
+ blockHash,
594
+ txIndex,
595
+ txData.txHash,
596
+ txData.logs,
597
+ filter,
598
+ );
599
+
600
+ return { logs, maxLogsHit };
601
+ }
602
+
603
+ async #filterContractClassLogsBetweenBlocks(filter: LogFilter): Promise<GetContractClassLogsResponse> {
604
+ const start =
605
+ filter.afterLog?.blockNumber ?? Math.max(filter.fromBlock ?? INITIAL_L2_BLOCK_NUM, INITIAL_L2_BLOCK_NUM);
606
+ const end = filter.toBlock;
607
+
608
+ if (typeof end === 'number' && end < start) {
609
+ return {
610
+ logs: [],
611
+ maxLogsHit: true,
612
+ };
613
+ }
614
+
615
+ const logs: ExtendedContractClassLog[] = [];
616
+
617
+ let maxLogsHit = false;
618
+ loopOverBlocks: for await (const [blockNumber, logBuffer] of this.#contractClassLogsByBlock.entriesAsync({
619
+ start,
620
+ end,
621
+ })) {
622
+ const contractClassLogsInBlock: { txHash: TxHash; logs: ContractClassLog[] }[] = [];
623
+ const reader = new BufferReader(logBuffer);
624
+ const blockHash = this.#unpackBlockHash(reader);
625
+ while (reader.remainingBytes() > 0) {
626
+ const indexOfTx = reader.readNumber();
627
+ const txHash = reader.readObject(TxHash);
628
+ const numLogsInTx = reader.readNumber();
629
+ contractClassLogsInBlock[indexOfTx] = { txHash, logs: [] };
630
+ for (let i = 0; i < numLogsInTx; i++) {
631
+ contractClassLogsInBlock[indexOfTx].logs.push(reader.readObject(ContractClassLog));
632
+ }
633
+ }
634
+ for (let txIndex = filter.afterLog?.txIndex ?? 0; txIndex < contractClassLogsInBlock.length; txIndex++) {
635
+ const txData = contractClassLogsInBlock[txIndex];
636
+ maxLogsHit = this.#accumulateContractClassLogs(
637
+ logs,
638
+ blockNumber,
639
+ blockHash,
640
+ txIndex,
641
+ txData.txHash,
642
+ txData.logs,
643
+ filter,
644
+ );
645
+ if (maxLogsHit) {
646
+ this.#log.debug(`Max logs hit at block ${blockNumber}`);
647
+ break loopOverBlocks;
648
+ }
649
+ }
650
+ }
651
+
652
+ return { logs, maxLogsHit };
653
+ }
654
+
655
+ #accumulatePublicLogs(
656
+ results: ExtendedPublicLog[],
657
+ blockNumber: number,
658
+ blockHash: BlockHash,
659
+ txIndex: number,
660
+ txHash: TxHash,
661
+ txLogs: PublicLog[],
662
+ filter: LogFilter = {},
663
+ ): boolean {
664
+ if (filter.fromBlock && blockNumber < filter.fromBlock) {
665
+ return false;
666
+ }
667
+ if (filter.toBlock && blockNumber >= filter.toBlock) {
668
+ return false;
669
+ }
670
+ if (filter.txHash && !txHash.equals(filter.txHash)) {
671
+ return false;
672
+ }
673
+
674
+ let maxLogsHit = false;
675
+ let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
676
+ for (; logIndex < txLogs.length; logIndex++) {
677
+ const log = txLogs[logIndex];
678
+ if (
679
+ (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) &&
680
+ (!filter.tag || log.fields[0]?.equals(filter.tag))
681
+ ) {
682
+ results.push(
683
+ new ExtendedPublicLog(new LogId(BlockNumber(blockNumber), blockHash, txHash, txIndex, logIndex), log),
684
+ );
685
+
686
+ if (results.length >= this.#logsMaxPageSize) {
687
+ maxLogsHit = true;
688
+ break;
689
+ }
690
+ }
691
+ }
692
+
693
+ return maxLogsHit;
694
+ }
695
+
696
+ #accumulateContractClassLogs(
697
+ results: ExtendedContractClassLog[],
698
+ blockNumber: number,
699
+ blockHash: BlockHash,
700
+ txIndex: number,
701
+ txHash: TxHash,
702
+ txLogs: ContractClassLog[],
703
+ filter: LogFilter = {},
704
+ ): boolean {
705
+ if (filter.fromBlock && blockNumber < filter.fromBlock) {
706
+ return false;
707
+ }
708
+ if (filter.toBlock && blockNumber >= filter.toBlock) {
709
+ return false;
710
+ }
711
+ if (filter.txHash && !txHash.equals(filter.txHash)) {
712
+ return false;
713
+ }
714
+
715
+ let maxLogsHit = false;
716
+ let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
717
+ for (; logIndex < txLogs.length; logIndex++) {
718
+ const log = txLogs[logIndex];
719
+ if (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) {
720
+ results.push(
721
+ new ExtendedContractClassLog(new LogId(BlockNumber(blockNumber), blockHash, txHash, txIndex, logIndex), log),
722
+ );
723
+
724
+ if (results.length >= this.#logsMaxPageSize) {
725
+ maxLogsHit = true;
726
+ break;
727
+ }
728
+ }
729
+ }
730
+
731
+ return maxLogsHit;
732
+ }
733
+ }