@aztec/archiver 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 (121) hide show
  1. package/README.md +19 -11
  2. package/dest/archiver.d.ts +71 -16
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +276 -71
  5. package/dest/config.d.ts +7 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +43 -14
  8. package/dest/errors.d.ts +50 -2
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +74 -2
  11. package/dest/factory.d.ts +19 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +67 -24
  14. package/dest/index.d.ts +11 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -2
  17. package/dest/l1/calldata_retriever.d.ts +9 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +22 -11
  20. package/dest/l1/data_retrieval.d.ts +30 -13
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +36 -37
  23. package/dest/l1/trace_tx.d.ts +12 -66
  24. package/dest/l1/trace_tx.d.ts.map +1 -1
  25. package/dest/l1/validate_historical_logs.d.ts +23 -0
  26. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  27. package/dest/l1/validate_historical_logs.js +108 -0
  28. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  29. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  30. package/dest/modules/contract_data_source_adapter.js +32 -0
  31. package/dest/modules/data_source_base.d.ts +71 -48
  32. package/dest/modules/data_source_base.d.ts.map +1 -1
  33. package/dest/modules/data_source_base.js +250 -144
  34. package/dest/modules/data_store_updater.d.ts +30 -13
  35. package/dest/modules/data_store_updater.d.ts.map +1 -1
  36. package/dest/modules/data_store_updater.js +129 -111
  37. package/dest/modules/instrumentation.d.ts +26 -2
  38. package/dest/modules/instrumentation.d.ts.map +1 -1
  39. package/dest/modules/instrumentation.js +58 -9
  40. package/dest/modules/l1_synchronizer.d.ts +13 -8
  41. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  42. package/dest/modules/l1_synchronizer.js +463 -224
  43. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  44. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  45. package/dest/modules/outbox_trees_resolver.js +162 -0
  46. package/dest/modules/validation.d.ts +30 -7
  47. package/dest/modules/validation.d.ts.map +1 -1
  48. package/dest/modules/validation.js +35 -17
  49. package/dest/store/block_store.d.ts +175 -68
  50. package/dest/store/block_store.d.ts.map +1 -1
  51. package/dest/store/block_store.js +627 -239
  52. package/dest/store/contract_class_store.d.ts +17 -4
  53. package/dest/store/contract_class_store.d.ts.map +1 -1
  54. package/dest/store/contract_class_store.js +37 -67
  55. package/dest/store/contract_instance_store.d.ts +28 -1
  56. package/dest/store/contract_instance_store.d.ts.map +1 -1
  57. package/dest/store/contract_instance_store.js +49 -1
  58. package/dest/store/data_stores.d.ts +68 -0
  59. package/dest/store/data_stores.d.ts.map +1 -0
  60. package/dest/store/data_stores.js +54 -0
  61. package/dest/store/function_names_cache.d.ts +17 -0
  62. package/dest/store/function_names_cache.d.ts.map +1 -0
  63. package/dest/store/function_names_cache.js +30 -0
  64. package/dest/store/l2_tips_cache.d.ts +13 -7
  65. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  66. package/dest/store/l2_tips_cache.js +13 -76
  67. package/dest/store/log_store.d.ts +42 -37
  68. package/dest/store/log_store.d.ts.map +1 -1
  69. package/dest/store/log_store.js +259 -443
  70. package/dest/store/log_store_codec.d.ts +78 -0
  71. package/dest/store/log_store_codec.d.ts.map +1 -0
  72. package/dest/store/log_store_codec.js +110 -0
  73. package/dest/store/message_store.d.ts +11 -1
  74. package/dest/store/message_store.d.ts.map +1 -1
  75. package/dest/store/message_store.js +50 -8
  76. package/dest/test/fake_l1_state.d.ts +8 -3
  77. package/dest/test/fake_l1_state.d.ts.map +1 -1
  78. package/dest/test/fake_l1_state.js +78 -21
  79. package/dest/test/mock_l2_block_source.d.ts +48 -50
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +228 -179
  82. package/dest/test/mock_structs.d.ts +1 -1
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +2 -2
  85. package/dest/test/noop_l1_archiver.d.ts +14 -6
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  87. package/dest/test/noop_l1_archiver.js +26 -10
  88. package/package.json +15 -14
  89. package/src/archiver.ts +361 -77
  90. package/src/config.ts +51 -13
  91. package/src/errors.ts +117 -2
  92. package/src/factory.ts +81 -22
  93. package/src/index.ts +18 -2
  94. package/src/l1/calldata_retriever.ts +29 -11
  95. package/src/l1/data_retrieval.ts +60 -54
  96. package/src/l1/validate_historical_logs.ts +140 -0
  97. package/src/modules/contract_data_source_adapter.ts +46 -0
  98. package/src/modules/data_source_base.ts +325 -187
  99. package/src/modules/data_store_updater.ts +155 -139
  100. package/src/modules/instrumentation.ts +63 -10
  101. package/src/modules/l1_synchronizer.ts +630 -273
  102. package/src/modules/outbox_trees_resolver.ts +199 -0
  103. package/src/modules/validation.ts +80 -23
  104. package/src/store/block_store.ts +766 -290
  105. package/src/store/contract_class_store.ts +43 -101
  106. package/src/store/contract_instance_store.ts +61 -1
  107. package/src/store/data_stores.ts +104 -0
  108. package/src/store/function_names_cache.ts +37 -0
  109. package/src/store/l2_tips_cache.ts +16 -70
  110. package/src/store/log_store.ts +298 -609
  111. package/src/store/log_store_codec.ts +143 -0
  112. package/src/store/message_store.ts +59 -9
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +99 -32
  115. package/src/test/mock_l2_block_source.ts +285 -232
  116. package/src/test/mock_structs.ts +5 -2
  117. package/src/test/noop_l1_archiver.ts +54 -11
  118. package/dest/store/kv_archiver_store.d.ts +0 -362
  119. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  120. package/dest/store/kv_archiver_store.js +0 -475
  121. package/src/store/kv_archiver_store.ts +0 -685
@@ -1,691 +1,380 @@
1
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
2
  import { Fr } from '@aztec/foundation/curves/bn254';
5
3
  import { createLogger } from '@aztec/foundation/log';
6
- import { BufferReader, numToUInt32BE } from '@aztec/foundation/serialize';
7
4
  import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
8
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
9
- import { BlockHash, L2Block } from '@aztec/stdlib/block';
5
+ import type { BlockHash, L2Block } from '@aztec/stdlib/block';
10
6
  import { MAX_LOGS_PER_TAG } from '@aztec/stdlib/interfaces/api-limit';
11
- import type { GetContractClassLogsResponse, GetPublicLogsResponse } from '@aztec/stdlib/interfaces/client';
12
- import {
13
- ContractClassLog,
14
- ExtendedContractClassLog,
15
- ExtendedPublicLog,
16
- type LogFilter,
17
- LogId,
18
- PublicLog,
19
- type SiloedTag,
7
+ import type {
8
+ LogCursor,
9
+ LogResult,
10
+ PrivateLogsQuery,
11
+ PublicLogsQuery,
12
+ SiloedTag,
20
13
  Tag,
21
- TxScopedL2Log,
14
+ TagQuery,
22
15
  } from '@aztec/stdlib/logs';
23
16
  import { TxHash } from '@aztec/stdlib/tx';
24
17
 
25
18
  import type { BlockStore } from './block_store.js';
19
+ import {
20
+ decodeKeyTail,
21
+ decodeValue,
22
+ encodeKey,
23
+ encodePublicPrefix,
24
+ encodeValue,
25
+ endOfTagRange,
26
+ endOfTxRange,
27
+ fieldHex,
28
+ incKey,
29
+ tagHexForLog,
30
+ } from './log_store_codec.js';
26
31
 
27
32
  /**
28
- * A store for logs
33
+ * Indexes every emitted private and public log under a composite hex-string key
34
+ * `[contractAddress (public only)]-tag-blockNumber-txIndexWithinBlock-logIndexWithinTx`,
35
+ * where each numeric segment is zero-padded to 8 lowercase hex digits (4 bytes BE) and
36
+ * `contractAddress` / `tag` are the bare 64-hex-char field representations (no `0x` prefix). The
37
+ * fixed-width zero-padded hex segments sort lexicographically in the same order as the canonical
38
+ * `(contract, tag, blockNumber, txIndexWithinBlock, logIndexWithinTx)` tuple, so a single ordered
39
+ * range scan answers every {@link PrivateLogsQuery} / {@link PublicLogsQuery}.
40
+ *
41
+ * Per-block secondary indices (`#privateKeysByBlock`, `#publicKeysByBlock`) record the exact primary
42
+ * keys written for each block so {@link deleteLogs} can drop them on reorg without having to range
43
+ * scan by block (block isn't the leading key segment).
44
+ *
45
+ * Contract-class logs are no longer stored or served by the log store.
29
46
  */
30
47
  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;
48
+ /** Primary map: composite private key (tag + tail = 96 hex chars + separators) -> serialized {@link StoredLogValue}. */
49
+ #privateLogs: AztecAsyncMap<string, Buffer>;
50
+ /** Primary map: composite public key (contract + tag + tail) -> serialized {@link StoredLogValue}. */
51
+ #publicLogs: AztecAsyncMap<string, Buffer>;
52
+
53
+ /** Secondary deletion index: blockNumber -> the exact primary keys written for that block. */
54
+ #privateKeysByBlock: AztecAsyncMap<number, string[]>;
55
+ #publicKeysByBlock: AztecAsyncMap<number, string[]>;
56
+
40
57
  #log = createLogger('archiver:log_store');
41
58
 
59
+ /**
60
+ * @param genesisBlockHash - Hash of the synthetic genesis block. During early sync the PXE anchors to
61
+ * genesis and passes its hash as a query `referenceBlock`; since the archiver never indexes the
62
+ * genesis block, the store recognizes this hash directly and resolves it to the genesis block number
63
+ * rather than mistaking it for a reorg.
64
+ */
42
65
  constructor(
43
66
  private db: AztecAsyncKVStore,
44
67
  private blockStore: BlockStore,
45
- logsMaxPageSize: number = 1000,
68
+ private readonly genesisBlockHash: BlockHash,
46
69
  ) {
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;
70
+ this.#privateLogs = db.openMap('archiver_private_logs');
71
+ this.#publicLogs = db.openMap('archiver_public_logs');
72
+ this.#privateKeysByBlock = db.openMap('archiver_private_log_keys_by_block');
73
+ this.#publicKeysByBlock = db.openMap('archiver_public_log_keys_by_block');
55
74
  }
56
75
 
57
76
  /**
58
- * Extracts tagged logs from a single block, grouping them into private and public maps.
77
+ * Indexes every emitted private and public log from the given blocks. Wraps the write in a single
78
+ * `db.transactionAsync` so the primary entries and the per-block secondary indices stay consistent.
59
79
  *
60
- * @param block - The L2 block to extract logs from.
61
- * @returns An object containing the private and public tagged logs for the block.
80
+ * A block is only ever added once; on reorg the archiver calls {@link deleteLogs} first, so we write
81
+ * the secondary index entries with a plain `set` (overwrite) rather than read-modify-append.
62
82
  */
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
- privateTaggedLogs.set(
169
- taggedLogBuffer.tag,
170
- taggedLogBuffer.logBuffers!.concat(privateTaggedLogs.get(taggedLogBuffer.tag)!),
171
- );
172
- }
173
- }
174
-
175
- for (const block of newBlocks) {
176
- const privateTagsInBlock: string[] = [];
177
- for (const [tag, logs] of privateTaggedLogs.entries()) {
178
- await this.#privateLogsByTag.set(tag, logs);
179
- privateTagsInBlock.push(tag);
180
- }
181
- await this.#privateLogKeysByBlock.set(block.number, privateTagsInBlock);
182
- }
183
- }
184
-
185
- async #addPublicLogs(blocks: L2Block[]): Promise<void> {
186
- const newBlocks = await filterAsync(
187
- blocks,
188
- async block => !(await this.#publicLogKeysByBlock.hasAsync(block.number)),
189
- );
190
-
191
- const { publicTaggedLogs } = this.#extractTaggedLogs(newBlocks);
192
- const keysOfPublicLogsToUpdate = Array.from(publicTaggedLogs.keys());
83
+ addLogs(blocks: L2Block[]): Promise<boolean> {
84
+ return this.db.transactionAsync(async () => {
85
+ for (const block of blocks) {
86
+ const blockHash = await block.hash();
87
+ const blockNumber = block.number;
88
+ const blockTimestamp = block.timestamp;
89
+
90
+ const privateKeys: string[] = [];
91
+ const privateValues: Buffer[] = [];
92
+ const publicKeys: string[] = [];
93
+ const publicValues: Buffer[] = [];
94
+
95
+ for (let txIndexWithinBlock = 0; txIndexWithinBlock < block.body.txEffects.length; txIndexWithinBlock++) {
96
+ const txEffect = block.body.txEffects[txIndexWithinBlock];
97
+ const txHash = txEffect.txHash;
98
+
99
+ // Private and public log indices are counted independently per tx, each starting at 0.
100
+ let privateLogIndexWithinTx = 0;
101
+ let publicLogIndexWithinTx = 0;
102
+
103
+ for (const log of txEffect.privateLogs) {
104
+ const tagHex = tagHexForLog(log.fields);
105
+ const key = encodeKey(tagHex, blockNumber, txIndexWithinBlock, privateLogIndexWithinTx);
106
+ const value = encodeValue({
107
+ txHash,
108
+ blockHash,
109
+ blockTimestamp,
110
+ logData: log.getEmittedFields(),
111
+ });
112
+ privateKeys.push(key);
113
+ privateValues.push(value);
114
+ privateLogIndexWithinTx++;
115
+ }
116
+
117
+ for (const log of txEffect.publicLogs) {
118
+ const contractHex = fieldHex(log.contractAddress);
119
+ const tagHex = tagHexForLog(log.fields);
120
+ const key = encodeKey(
121
+ encodePublicPrefix(contractHex, tagHex),
122
+ blockNumber,
123
+ txIndexWithinBlock,
124
+ publicLogIndexWithinTx,
125
+ );
126
+ const value = encodeValue({
127
+ txHash,
128
+ blockHash,
129
+ blockTimestamp,
130
+ logData: log.getEmittedFields(),
131
+ });
132
+ publicKeys.push(key);
133
+ publicValues.push(value);
134
+ publicLogIndexWithinTx++;
135
+ }
136
+ }
193
137
 
194
- const currentPublicTaggedLogs = await Promise.all(
195
- keysOfPublicLogsToUpdate.map(async key => ({
196
- tag: key,
197
- logBuffers: await this.#publicLogsByContractAndTag.getAsync(key),
198
- })),
199
- );
138
+ for (let i = 0; i < privateKeys.length; i++) {
139
+ await this.#privateLogs.set(privateKeys[i], privateValues[i]);
140
+ }
141
+ for (let i = 0; i < publicKeys.length; i++) {
142
+ await this.#publicLogs.set(publicKeys[i], publicValues[i]);
143
+ }
200
144
 
201
- for (const taggedLogBuffer of currentPublicTaggedLogs) {
202
- if (taggedLogBuffer.logBuffers && taggedLogBuffer.logBuffers.length > 0) {
203
- publicTaggedLogs.set(
204
- taggedLogBuffer.tag,
205
- taggedLogBuffer.logBuffers!.concat(publicTaggedLogs.get(taggedLogBuffer.tag)!),
206
- );
207
- }
208
- }
145
+ await this.#privateKeysByBlock.set(blockNumber, privateKeys);
146
+ await this.#publicKeysByBlock.set(blockNumber, publicKeys);
209
147
 
210
- for (const block of newBlocks) {
211
- const blockHash = await block.hash();
212
- const publicTagsInBlock: string[] = [];
213
- for (const [tag, logs] of publicTaggedLogs.entries()) {
214
- await this.#publicLogsByContractAndTag.set(tag, logs);
215
- publicTagsInBlock.push(tag);
148
+ this.#log.debug(`Indexed logs for block ${blockNumber}`, {
149
+ blockNumber,
150
+ privateCount: privateKeys.length,
151
+ publicCount: publicKeys.length,
152
+ });
216
153
  }
217
- await this.#publicLogKeysByBlock.set(block.number, publicTagsInBlock);
218
-
219
- const publicLogsInBlock = block.body.txEffects
220
- .map((txEffect, txIndex) =>
221
- [
222
- numToUInt32BE(txIndex),
223
- txEffect.txHash.toBuffer(),
224
- numToUInt32BE(txEffect.publicLogs.length),
225
- txEffect.publicLogs.map(log => log.toBuffer()),
226
- ].flat(),
227
- )
228
- .flat();
229
-
230
- await this.#publicLogsByBlock.set(block.number, this.#packWithBlockHash(blockHash, publicLogsInBlock));
231
- }
232
- }
233
-
234
- async #addContractClassLogs(blocks: L2Block[]): Promise<void> {
235
- const newBlocks = await filterAsync(
236
- blocks,
237
- async block => !(await this.#contractClassLogsByBlock.hasAsync(block.number)),
238
- );
239
-
240
- for (const block of newBlocks) {
241
- const blockHash = await block.hash();
242
-
243
- const contractClassLogsInBlock = block.body.txEffects
244
- .map((txEffect, txIndex) =>
245
- [
246
- numToUInt32BE(txIndex),
247
- txEffect.txHash.toBuffer(),
248
- numToUInt32BE(txEffect.contractClassLogs.length),
249
- txEffect.contractClassLogs.map(log => log.toBuffer()),
250
- ].flat(),
251
- )
252
- .flat();
253
-
254
- await this.#contractClassLogsByBlock.set(
255
- block.number,
256
- this.#packWithBlockHash(blockHash, contractClassLogsInBlock),
257
- );
258
- }
259
- }
260
-
261
- /**
262
- * Append new logs to the store's list.
263
- * @param blocks - The blocks for which to add the logs.
264
- * @returns True if the operation is successful.
265
- */
266
- addLogs(blocks: L2Block[]): Promise<boolean> {
267
- return this.db.transactionAsync(async () => {
268
- await Promise.all([
269
- this.#addPrivateLogs(blocks),
270
- this.#addPublicLogs(blocks),
271
- this.#addContractClassLogs(blocks),
272
- ]);
273
154
  return true;
274
155
  });
275
156
  }
276
157
 
277
- #packWithBlockHash(blockHash: BlockHash, data: Buffer<ArrayBufferLike>[]): Buffer<ArrayBufferLike> {
278
- return Buffer.concat([blockHash.toBuffer(), ...data]);
279
- }
280
-
281
- #unpackBlockHash(reader: BufferReader): BlockHash {
282
- const blockHash = reader.remainingBytes() > 0 ? reader.readObject(Fr) : undefined;
283
-
284
- if (!blockHash) {
285
- throw new Error('Failed to read block hash from log entry buffer');
286
- }
287
-
288
- return new BlockHash(blockHash);
289
- }
290
-
158
+ /**
159
+ * Deletes every log indexed under any of the given blocks. Secondary-index driven, so it doesn't
160
+ * have to range-scan the primary maps.
161
+ */
291
162
  deleteLogs(blocks: L2Block[]): Promise<boolean> {
292
163
  return this.db.transactionAsync(async () => {
293
- const blockNumbers = new Set(blocks.map(block => block.number));
294
- const firstBlockToDelete = Math.min(...blockNumbers);
295
-
296
- // Collect all unique private tags across all blocks being deleted
297
- const allPrivateTags = new Set(
298
- compactArray(await Promise.all(blocks.map(block => this.#privateLogKeysByBlock.getAsync(block.number)))).flat(),
299
- );
300
-
301
- // Trim private logs: for each tag, delete all instances including and after the first block being deleted.
302
- // This hinges on the invariant that logs for a given tag are always inserted in order of block number, which is enforced in #addPrivateLogs.
303
- for (const tag of allPrivateTags) {
304
- const existing = await this.#privateLogsByTag.getAsync(tag);
305
- if (existing === undefined || existing.length === 0) {
306
- continue;
164
+ for (const block of blocks) {
165
+ const blockNumber = block.number;
166
+
167
+ const [privateKeys, publicKeys] = await Promise.all([
168
+ this.#privateKeysByBlock.getAsync(blockNumber),
169
+ this.#publicKeysByBlock.getAsync(blockNumber),
170
+ ]);
171
+
172
+ if (privateKeys) {
173
+ for (const key of privateKeys) {
174
+ await this.#privateLogs.delete(key);
175
+ }
176
+ await this.#privateKeysByBlock.delete(blockNumber);
307
177
  }
308
- const lastIndexToKeep = existing.findLastIndex(
309
- buf => TxScopedL2Log.getBlockNumberFromBuffer(buf) < firstBlockToDelete,
310
- );
311
- const remaining = existing.slice(0, lastIndexToKeep + 1);
312
- await (remaining.length > 0 ? this.#privateLogsByTag.set(tag, remaining) : this.#privateLogsByTag.delete(tag));
313
- }
314
-
315
- // Collect all unique public keys across all blocks being deleted
316
- const allPublicKeys = new Set(
317
- compactArray(await Promise.all(blocks.map(block => this.#publicLogKeysByBlock.getAsync(block.number)))).flat(),
318
- );
319
-
320
- // And do the same as we did with private logs
321
- for (const key of allPublicKeys) {
322
- const existing = await this.#publicLogsByContractAndTag.getAsync(key);
323
- if (existing === undefined || existing.length === 0) {
324
- continue;
178
+ if (publicKeys) {
179
+ for (const key of publicKeys) {
180
+ await this.#publicLogs.delete(key);
181
+ }
182
+ await this.#publicKeysByBlock.delete(blockNumber);
325
183
  }
326
- const lastIndexToKeep = existing.findLastIndex(
327
- buf => TxScopedL2Log.getBlockNumberFromBuffer(buf) < firstBlockToDelete,
328
- );
329
- const remaining = existing.slice(0, lastIndexToKeep + 1);
330
- await (remaining.length > 0
331
- ? this.#publicLogsByContractAndTag.set(key, remaining)
332
- : this.#publicLogsByContractAndTag.delete(key));
333
184
  }
334
-
335
- // After trimming the tagged logs, we can delete the block-level keys that track which tags are in which blocks.
336
- await Promise.all(
337
- blocks.map(block =>
338
- Promise.all([
339
- this.#publicLogsByBlock.delete(block.number),
340
- this.#privateLogKeysByBlock.delete(block.number),
341
- this.#publicLogKeysByBlock.delete(block.number),
342
- this.#contractClassLogsByBlock.delete(block.number),
343
- ]),
344
- ),
345
- );
346
-
347
185
  return true;
348
186
  });
349
187
  }
350
188
 
351
- /**
352
- * Gets private logs that match any of the `tags`. For each tag, an array of matching logs is returned. An empty
353
- * array implies no logs match that tag.
354
- * @param tags - The tags to search for.
355
- * @param page - The page number (0-indexed) for pagination.
356
- * @returns An array of log arrays, one per tag. Returns at most MAX_LOGS_PER_TAG logs per tag per page. If
357
- * MAX_LOGS_PER_TAG logs are returned for a tag, the caller should fetch the next page to check for more logs.
358
- */
359
- async getPrivateLogsByTags(tags: SiloedTag[], page: number = 0): Promise<TxScopedL2Log[][]> {
360
- const logs = await Promise.all(tags.map(tag => this.#privateLogsByTag.getAsync(tag.toString())));
361
- const start = page * MAX_LOGS_PER_TAG;
362
- const end = start + MAX_LOGS_PER_TAG;
363
-
364
- return logs.map(
365
- logBuffers => logBuffers?.slice(start, end).map(logBuffer => TxScopedL2Log.fromBuffer(logBuffer)) ?? [],
366
- );
189
+ /** Returns one inner array per element of `query.tags`, in input order. */
190
+ getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
191
+ LogStore.#validateQuery(query);
192
+ return this.db.transactionAsync(() => this.#runQuery(query, /* contractHex */ undefined));
367
193
  }
368
194
 
369
- /**
370
- * Gets public logs that match any of the `tags` from the specified contract. For each tag, an array of matching
371
- * logs is returned. An empty array implies no logs match that tag.
372
- * @param contractAddress - The contract address to search logs for.
373
- * @param tags - The tags to search for.
374
- * @param page - The page number (0-indexed) for pagination.
375
- * @returns An array of log arrays, one per tag. Returns at most MAX_LOGS_PER_TAG logs per tag per page. If
376
- * MAX_LOGS_PER_TAG logs are returned for a tag, the caller should fetch the next page to check for more logs.
377
- */
378
- async getPublicLogsByTagsFromContract(
379
- contractAddress: AztecAddress,
380
- tags: Tag[],
381
- page: number = 0,
382
- ): Promise<TxScopedL2Log[][]> {
383
- const logs = await Promise.all(
384
- tags.map(tag => {
385
- const key = `${contractAddress.toString()}_${tag.value.toString()}`;
386
- return this.#publicLogsByContractAndTag.getAsync(key);
387
- }),
388
- );
389
- const start = page * MAX_LOGS_PER_TAG;
390
- const end = start + MAX_LOGS_PER_TAG;
391
-
392
- return logs.map(
393
- logBuffers => logBuffers?.slice(start, end).map(logBuffer => TxScopedL2Log.fromBuffer(logBuffer)) ?? [],
394
- );
195
+ /** Returns one inner array per element of `query.tags`, in input order. */
196
+ getPublicLogsByTags(query: PublicLogsQuery): Promise<LogResult[][]> {
197
+ LogStore.#validateQuery(query);
198
+ return this.db.transactionAsync(() => this.#runQuery(query, fieldHex(query.contractAddress)));
395
199
  }
396
200
 
397
- /**
398
- * Gets public logs based on the provided filter.
399
- * @param filter - The filter to apply to the logs.
400
- * @returns The requested logs.
401
- */
402
- getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
403
- if (filter.afterLog) {
404
- return this.#filterPublicLogsBetweenBlocks(filter);
405
- } else if (filter.txHash) {
406
- return this.#filterPublicLogsOfTx(filter);
407
- } else {
408
- return this.#filterPublicLogsBetweenBlocks(filter);
201
+ static #validateQuery(query: { txHash?: TxHash; fromBlock?: unknown; toBlock?: unknown }): void {
202
+ if (query.txHash !== undefined && (query.fromBlock !== undefined || query.toBlock !== undefined)) {
203
+ throw new Error('`txHash` is mutually exclusive with `fromBlock`/`toBlock`');
409
204
  }
410
205
  }
411
206
 
412
- async #filterPublicLogsOfTx(filter: LogFilter): Promise<GetPublicLogsResponse> {
413
- if (!filter.txHash) {
414
- throw new Error('Missing txHash');
207
+ async #runQuery(query: PrivateLogsQuery | PublicLogsQuery, contractHex: string | undefined): Promise<LogResult[][]> {
208
+ const isPublic = contractHex !== undefined;
209
+ const tags = (query.tags as ReadonlyArray<TagQuery<Tag | SiloedTag>>) ?? [];
210
+ const primaryMap = isPublic ? this.#publicLogs : this.#privateLogs;
211
+
212
+ // referenceBlock reorg check, in-transaction, against the same db the log primary maps live on. The
213
+ // genesis block is a valid anchor during early sync but is synthetic and never indexed in the block
214
+ // store, so resolve it directly to the genesis block number rather than mistaking it for a reorg.
215
+ let referenceBlockNumber: number | undefined;
216
+ if (query.referenceBlock) {
217
+ if (query.referenceBlock.equals(this.genesisBlockHash)) {
218
+ referenceBlockNumber = INITIAL_L2_BLOCK_NUM - 1;
219
+ } else {
220
+ const refBlk = await this.blockStore.getBlockData({ hash: query.referenceBlock });
221
+ if (!refBlk) {
222
+ throw new Error(
223
+ `Reference block ${query.referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
224
+ );
225
+ }
226
+ referenceBlockNumber = refBlk.header.globalVariables.blockNumber;
227
+ }
415
228
  }
416
229
 
417
- const [blockNumber, txIndex] = (await this.blockStore.getTxLocation(filter.txHash)) ?? [];
418
- if (typeof blockNumber !== 'number' || typeof txIndex !== 'number') {
419
- return { logs: [], maxLogsHit: false };
230
+ // Compute the exclusive upper-block bound across `toBlock` and `referenceBlock`.
231
+ // `toBlock` is already exclusive; `referenceBlock` caps inclusively, so its exclusive form is +1.
232
+ let upperExclusive: number | undefined;
233
+ if (query.toBlock !== undefined) {
234
+ upperExclusive = query.toBlock;
235
+ }
236
+ if (referenceBlockNumber !== undefined) {
237
+ const refExclusive = referenceBlockNumber + 1;
238
+ upperExclusive = upperExclusive === undefined ? refExclusive : Math.min(upperExclusive, refExclusive);
420
239
  }
421
240
 
422
- const buffer = (await this.#publicLogsByBlock.getAsync(blockNumber)) ?? Buffer.alloc(0);
423
- const publicLogsInBlock: { txHash: TxHash; logs: PublicLog[] }[] = [];
424
- const reader = new BufferReader(buffer);
425
-
426
- const blockHash = this.#unpackBlockHash(reader);
427
-
428
- while (reader.remainingBytes() > 0) {
429
- const indexOfTx = reader.readNumber();
430
- const txHash = reader.readObject(TxHash);
431
- const numLogsInTx = reader.readNumber();
432
- publicLogsInBlock[indexOfTx] = { txHash, logs: [] };
433
- for (let i = 0; i < numLogsInTx; i++) {
434
- publicLogsInBlock[indexOfTx].logs.push(reader.readObject(PublicLog));
241
+ // Resolve txHash -> (blockNumber, txIndexInBlock) once for the whole query.
242
+ let txLocation: [number, number] | undefined;
243
+ if (query.txHash) {
244
+ const loc = await this.blockStore.getTxLocation(query.txHash);
245
+ if (!loc) {
246
+ return tags.map(() => []);
247
+ }
248
+ txLocation = loc;
249
+ if (upperExclusive !== undefined && txLocation[0] >= upperExclusive) {
250
+ return tags.map(() => []);
435
251
  }
436
252
  }
437
253
 
438
- const txData = publicLogsInBlock[txIndex];
439
-
440
- const logs: ExtendedPublicLog[] = [];
441
- const maxLogsHit = this.#accumulatePublicLogs(
442
- logs,
443
- blockNumber,
444
- blockHash,
445
- txIndex,
446
- txData.txHash,
447
- txData.logs,
448
- filter,
449
- );
450
-
451
- return { logs, maxLogsHit };
452
- }
453
-
454
- async #filterPublicLogsBetweenBlocks(filter: LogFilter): Promise<GetPublicLogsResponse> {
455
- const start =
456
- filter.afterLog?.blockNumber ?? Math.max(filter.fromBlock ?? INITIAL_L2_BLOCK_NUM, INITIAL_L2_BLOCK_NUM);
457
- const end = filter.toBlock;
254
+ const fromBlock = query.fromBlock ?? INITIAL_L2_BLOCK_NUM;
255
+ const includeEffects = query.includeEffects === true;
256
+
257
+ const perTagResults: LogResult[][] = [];
258
+ for (const tagEntry of tags) {
259
+ const { tagHex, afterLog } = normalizeTagEntry(tagEntry);
260
+ const prefix = contractHex !== undefined ? encodePublicPrefix(contractHex, tagHex) : tagHex;
261
+
262
+ const end = txLocation
263
+ ? endOfTxRange(prefix, txLocation[0], txLocation[1])
264
+ : endOfTagRange(prefix, upperExclusive);
265
+
266
+ let start: string;
267
+ if (afterLog) {
268
+ // Cursor wins as the start; `fromBlock` is ignored (fine if the cursor sits below it). The cursor
269
+ // carries `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`, which slot directly into the
270
+ // composite key no tx-hash lookup needed.
271
+ start = incKey(encodeKey(prefix, afterLog.blockNumber, afterLog.txIndexWithinBlock, afterLog.logIndexWithinTx));
272
+ } else if (txLocation) {
273
+ start = encodeKey(prefix, txLocation[0], txLocation[1], 0);
274
+ } else {
275
+ start = encodeKey(prefix, fromBlock, 0, 0);
276
+ }
458
277
 
459
- if (typeof end === 'number' && end < start) {
460
- return {
461
- logs: [],
462
- maxLogsHit: true,
463
- };
278
+ const limit = query.limitPerTag ?? MAX_LOGS_PER_TAG;
279
+ const out: LogResult[] = [];
280
+ for await (const [rawKey, rawVal] of primaryMap.entriesAsync({ start, end, limit })) {
281
+ const tail = decodeKeyTail(rawKey);
282
+ const value = decodeValue(rawVal);
283
+ out.push({
284
+ logData: value.logData,
285
+ blockNumber: tail.blockNumber,
286
+ blockHash: value.blockHash,
287
+ blockTimestamp: value.blockTimestamp,
288
+ txHash: value.txHash,
289
+ txIndexWithinBlock: tail.txIndexWithinBlock,
290
+ logIndexWithinTx: tail.logIndexWithinTx,
291
+ });
292
+ }
293
+ perTagResults.push(out);
464
294
  }
465
295
 
466
- const logs: ExtendedPublicLog[] = [];
467
-
468
- let maxLogsHit = false;
469
- loopOverBlocks: for await (const [blockNumber, logBuffer] of this.#publicLogsByBlock.entriesAsync({ start, end })) {
470
- const publicLogsInBlock: { txHash: TxHash; logs: PublicLog[] }[] = [];
471
- const reader = new BufferReader(logBuffer);
472
-
473
- const blockHash = this.#unpackBlockHash(reader);
474
-
475
- while (reader.remainingBytes() > 0) {
476
- const indexOfTx = reader.readNumber();
477
- const txHash = reader.readObject(TxHash);
478
- const numLogsInTx = reader.readNumber();
479
- publicLogsInBlock[indexOfTx] = { txHash, logs: [] };
480
- for (let i = 0; i < numLogsInTx; i++) {
481
- publicLogsInBlock[indexOfTx].logs.push(reader.readObject(PublicLog));
296
+ if (includeEffects) {
297
+ // Dedupe by txHash across the entire page so a tx with many tagged logs costs one fetch.
298
+ const txHashByKey = new Map<string, TxHash>();
299
+ for (const arr of perTagResults) {
300
+ for (const log of arr) {
301
+ txHashByKey.set(log.txHash.toString(), log.txHash);
482
302
  }
483
303
  }
484
- for (let txIndex = filter.afterLog?.txIndex ?? 0; txIndex < publicLogsInBlock.length; txIndex++) {
485
- const txData = publicLogsInBlock[txIndex];
486
- maxLogsHit = this.#accumulatePublicLogs(
487
- logs,
488
- blockNumber,
489
- blockHash,
490
- txIndex,
491
- txData.txHash,
492
- txData.logs,
493
- filter,
494
- );
495
- if (maxLogsHit) {
496
- this.#log.debug(`Max logs hit at block ${blockNumber}`);
497
- break loopOverBlocks;
304
+ const uniqueTxs = Array.from(txHashByKey.values());
305
+ if (uniqueTxs.length > 0) {
306
+ const effects = await this.blockStore.getNoteHashesAndNullifiers(uniqueTxs);
307
+ const byTxHash = new Map<string, [Fr[], Fr[]]>();
308
+ uniqueTxs.forEach((tx, i) => byTxHash.set(tx.toString(), effects[i]));
309
+ for (let i = 0; i < perTagResults.length; i++) {
310
+ perTagResults[i] = perTagResults[i].map(log => {
311
+ const [noteHashes, nullifiers] = byTxHash.get(log.txHash.toString()) ?? [[], []];
312
+ return { ...log, noteHashes, nullifiers };
313
+ });
498
314
  }
499
315
  }
500
316
  }
501
317
 
502
- return { logs, maxLogsHit };
318
+ return perTagResults;
503
319
  }
504
320
 
505
321
  /**
506
- * Gets contract class logs based on the provided filter.
507
- * @param filter - The filter to apply to the logs.
508
- * @returns The requested logs.
322
+ * Reads back every private log indexed for the given block via the per-block secondary index. Order
323
+ * matches the canonical composite-key order (`tag`, `blockNumber`, `txIndexWithinBlock`,
324
+ * `logIndexWithinTx`). Used by the data-store-updater test suite to verify the indexed-vs-block-body
325
+ * counts without depending on the removed `getPublicLogs(LogFilter)` API.
509
326
  */
510
- getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
511
- if (filter.afterLog) {
512
- return this.#filterContractClassLogsBetweenBlocks(filter);
513
- } else if (filter.txHash) {
514
- return this.#filterContractClassLogsOfTx(filter);
515
- } else {
516
- return this.#filterContractClassLogsBetweenBlocks(filter);
517
- }
518
- }
519
-
520
- async #filterContractClassLogsOfTx(filter: LogFilter): Promise<GetContractClassLogsResponse> {
521
- if (!filter.txHash) {
522
- throw new Error('Missing txHash');
523
- }
524
-
525
- const [blockNumber, txIndex] = (await this.blockStore.getTxLocation(filter.txHash)) ?? [];
526
- if (typeof blockNumber !== 'number' || typeof txIndex !== 'number') {
527
- return { logs: [], maxLogsHit: false };
528
- }
529
- const contractClassLogsBuffer = (await this.#contractClassLogsByBlock.getAsync(blockNumber)) ?? Buffer.alloc(0);
530
- const contractClassLogsInBlock: { txHash: TxHash; logs: ContractClassLog[] }[] = [];
531
-
532
- const reader = new BufferReader(contractClassLogsBuffer);
533
- const blockHash = this.#unpackBlockHash(reader);
534
-
535
- while (reader.remainingBytes() > 0) {
536
- const indexOfTx = reader.readNumber();
537
- const txHash = reader.readObject(TxHash);
538
- const numLogsInTx = reader.readNumber();
539
- contractClassLogsInBlock[indexOfTx] = { txHash, logs: [] };
540
- for (let i = 0; i < numLogsInTx; i++) {
541
- contractClassLogsInBlock[indexOfTx].logs.push(reader.readObject(ContractClassLog));
542
- }
543
- }
544
-
545
- const txData = contractClassLogsInBlock[txIndex];
546
-
547
- const logs: ExtendedContractClassLog[] = [];
548
- const maxLogsHit = this.#accumulateContractClassLogs(
549
- logs,
550
- blockNumber,
551
- blockHash,
552
- txIndex,
553
- txData.txHash,
554
- txData.logs,
555
- filter,
327
+ getPrivateLogsForBlock(blockNumber: number): Promise<LogResult[]> {
328
+ return this.db.transactionAsync(() =>
329
+ this.#readBlockLogs(this.#privateKeysByBlock, this.#privateLogs, blockNumber),
556
330
  );
557
-
558
- return { logs, maxLogsHit };
559
331
  }
560
332
 
561
- async #filterContractClassLogsBetweenBlocks(filter: LogFilter): Promise<GetContractClassLogsResponse> {
562
- const start =
563
- filter.afterLog?.blockNumber ?? Math.max(filter.fromBlock ?? INITIAL_L2_BLOCK_NUM, INITIAL_L2_BLOCK_NUM);
564
- const end = filter.toBlock;
565
-
566
- if (typeof end === 'number' && end < start) {
567
- return {
568
- logs: [],
569
- maxLogsHit: true,
570
- };
571
- }
572
-
573
- const logs: ExtendedContractClassLog[] = [];
574
-
575
- let maxLogsHit = false;
576
- loopOverBlocks: for await (const [blockNumber, logBuffer] of this.#contractClassLogsByBlock.entriesAsync({
577
- start,
578
- end,
579
- })) {
580
- const contractClassLogsInBlock: { txHash: TxHash; logs: ContractClassLog[] }[] = [];
581
- const reader = new BufferReader(logBuffer);
582
- const blockHash = this.#unpackBlockHash(reader);
583
- while (reader.remainingBytes() > 0) {
584
- const indexOfTx = reader.readNumber();
585
- const txHash = reader.readObject(TxHash);
586
- const numLogsInTx = reader.readNumber();
587
- contractClassLogsInBlock[indexOfTx] = { txHash, logs: [] };
588
- for (let i = 0; i < numLogsInTx; i++) {
589
- contractClassLogsInBlock[indexOfTx].logs.push(reader.readObject(ContractClassLog));
590
- }
591
- }
592
- for (let txIndex = filter.afterLog?.txIndex ?? 0; txIndex < contractClassLogsInBlock.length; txIndex++) {
593
- const txData = contractClassLogsInBlock[txIndex];
594
- maxLogsHit = this.#accumulateContractClassLogs(
595
- logs,
596
- blockNumber,
597
- blockHash,
598
- txIndex,
599
- txData.txHash,
600
- txData.logs,
601
- filter,
602
- );
603
- if (maxLogsHit) {
604
- this.#log.debug(`Max logs hit at block ${blockNumber}`);
605
- break loopOverBlocks;
606
- }
607
- }
608
- }
609
-
610
- return { logs, maxLogsHit };
333
+ /** {@inheritDoc LogStore.getPrivateLogsForBlock} */
334
+ getPublicLogsForBlock(blockNumber: number): Promise<LogResult[]> {
335
+ return this.db.transactionAsync(() => this.#readBlockLogs(this.#publicKeysByBlock, this.#publicLogs, blockNumber));
611
336
  }
612
337
 
613
- #accumulatePublicLogs(
614
- results: ExtendedPublicLog[],
338
+ async #readBlockLogs(
339
+ keysByBlock: AztecAsyncMap<number, string[]>,
340
+ primaryMap: AztecAsyncMap<string, Buffer>,
615
341
  blockNumber: number,
616
- blockHash: BlockHash,
617
- txIndex: number,
618
- txHash: TxHash,
619
- txLogs: PublicLog[],
620
- filter: LogFilter = {},
621
- ): boolean {
622
- if (filter.fromBlock && blockNumber < filter.fromBlock) {
623
- return false;
342
+ ): Promise<LogResult[]> {
343
+ const keys = await keysByBlock.getAsync(blockNumber);
344
+ if (!keys || keys.length === 0) {
345
+ return [];
624
346
  }
625
- if (filter.toBlock && blockNumber >= filter.toBlock) {
626
- return false;
627
- }
628
- if (filter.txHash && !txHash.equals(filter.txHash)) {
629
- return false;
630
- }
631
-
632
- let maxLogsHit = false;
633
- let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
634
- for (; logIndex < txLogs.length; logIndex++) {
635
- const log = txLogs[logIndex];
636
- if (
637
- (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) &&
638
- (!filter.tag || log.fields[0]?.equals(filter.tag))
639
- ) {
640
- results.push(
641
- new ExtendedPublicLog(new LogId(BlockNumber(blockNumber), blockHash, txHash, txIndex, logIndex), log),
642
- );
643
-
644
- if (results.length >= this.#logsMaxPageSize) {
645
- maxLogsHit = true;
646
- break;
647
- }
347
+ const results: LogResult[] = [];
348
+ for (const key of keys) {
349
+ const raw = await primaryMap.getAsync(key);
350
+ if (!raw) {
351
+ continue;
648
352
  }
353
+ const tail = decodeKeyTail(key);
354
+ const value = decodeValue(raw);
355
+ results.push({
356
+ logData: value.logData,
357
+ blockNumber: tail.blockNumber,
358
+ blockHash: value.blockHash,
359
+ blockTimestamp: value.blockTimestamp,
360
+ txHash: value.txHash,
361
+ txIndexWithinBlock: tail.txIndexWithinBlock,
362
+ logIndexWithinTx: tail.logIndexWithinTx,
363
+ });
649
364
  }
650
-
651
- return maxLogsHit;
365
+ return results;
652
366
  }
367
+ }
653
368
 
654
- #accumulateContractClassLogs(
655
- results: ExtendedContractClassLog[],
656
- blockNumber: number,
657
- blockHash: BlockHash,
658
- txIndex: number,
659
- txHash: TxHash,
660
- txLogs: ContractClassLog[],
661
- filter: LogFilter = {},
662
- ): boolean {
663
- if (filter.fromBlock && blockNumber < filter.fromBlock) {
664
- return false;
665
- }
666
- if (filter.toBlock && blockNumber >= filter.toBlock) {
667
- return false;
668
- }
669
- if (filter.txHash && !txHash.equals(filter.txHash)) {
670
- return false;
671
- }
672
-
673
- let maxLogsHit = false;
674
- let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
675
- for (; logIndex < txLogs.length; logIndex++) {
676
- const log = txLogs[logIndex];
677
- if (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) {
678
- results.push(
679
- new ExtendedContractClassLog(new LogId(BlockNumber(blockNumber), blockHash, txHash, txIndex, logIndex), log),
680
- );
681
-
682
- if (results.length >= this.#logsMaxPageSize) {
683
- maxLogsHit = true;
684
- break;
685
- }
686
- }
687
- }
688
-
689
- return maxLogsHit;
369
+ /** Pulls `{ tagHex, afterLog }` out of a {@link TagQuery}, normalizing the bare-tag form. */
370
+ function normalizeTagEntry<T extends Tag | SiloedTag>(
371
+ entry: TagQuery<T>,
372
+ ): {
373
+ tagHex: string;
374
+ afterLog: LogCursor | undefined;
375
+ } {
376
+ if (typeof entry === 'object' && entry !== null && 'tag' in entry) {
377
+ return { tagHex: fieldHex(entry.tag.value), afterLog: entry.afterLog };
690
378
  }
379
+ return { tagHex: fieldHex((entry as T).value), afterLog: undefined };
691
380
  }