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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +164 -22
  2. package/dest/archiver.d.ts +194 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +949 -0
  5. package/dest/config.d.ts +34 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +95 -0
  8. package/dest/errors.d.ts +87 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +129 -0
  11. package/dest/factory.d.ts +16 -10
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +117 -20
  14. package/dest/index.d.ts +19 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +17 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +143 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +413 -0
  26. package/dest/l1/data_retrieval.d.ts +102 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +85 -165
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +43 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_historical_logs.d.ts +23 -0
  42. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  43. package/dest/l1/validate_historical_logs.js +108 -0
  44. package/dest/l1/validate_trace.d.ts +32 -0
  45. package/dest/l1/validate_trace.d.ts.map +1 -0
  46. package/dest/l1/validate_trace.js +154 -0
  47. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  48. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  49. package/dest/modules/contract_data_source_adapter.js +32 -0
  50. package/dest/modules/data_source_base.d.ts +112 -0
  51. package/dest/modules/data_source_base.d.ts.map +1 -0
  52. package/dest/modules/data_source_base.js +322 -0
  53. package/dest/modules/data_store_updater.d.ts +105 -0
  54. package/dest/modules/data_store_updater.d.ts.map +1 -0
  55. package/dest/modules/data_store_updater.js +393 -0
  56. package/dest/modules/instrumentation.d.ts +63 -0
  57. package/dest/modules/instrumentation.d.ts.map +1 -0
  58. package/dest/modules/instrumentation.js +166 -0
  59. package/dest/modules/l1_synchronizer.d.ts +77 -0
  60. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  61. package/dest/modules/l1_synchronizer.js +1381 -0
  62. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  63. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  64. package/dest/modules/outbox_trees_resolver.js +162 -0
  65. package/dest/modules/validation.d.ts +40 -0
  66. package/dest/modules/validation.d.ts.map +1 -0
  67. package/dest/{archiver → modules}/validation.js +41 -17
  68. package/dest/store/block_store.d.ts +303 -0
  69. package/dest/store/block_store.d.ts.map +1 -0
  70. package/dest/store/block_store.js +1206 -0
  71. package/dest/store/contract_class_store.d.ts +31 -0
  72. package/dest/store/contract_class_store.d.ts.map +1 -0
  73. package/dest/store/contract_class_store.js +98 -0
  74. package/dest/store/contract_instance_store.d.ts +51 -0
  75. package/dest/store/contract_instance_store.d.ts.map +1 -0
  76. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +55 -3
  77. package/dest/store/data_stores.d.ts +68 -0
  78. package/dest/store/data_stores.d.ts.map +1 -0
  79. package/dest/store/data_stores.js +54 -0
  80. package/dest/store/function_names_cache.d.ts +17 -0
  81. package/dest/store/function_names_cache.d.ts.map +1 -0
  82. package/dest/store/function_names_cache.js +30 -0
  83. package/dest/store/l2_tips_cache.d.ts +25 -0
  84. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  85. package/dest/store/l2_tips_cache.js +26 -0
  86. package/dest/store/log_store.d.ts +59 -0
  87. package/dest/store/log_store.d.ts.map +1 -0
  88. package/dest/store/log_store.js +310 -0
  89. package/dest/store/log_store_codec.d.ts +78 -0
  90. package/dest/store/log_store_codec.d.ts.map +1 -0
  91. package/dest/store/log_store_codec.js +110 -0
  92. package/dest/store/message_store.d.ts +50 -0
  93. package/dest/store/message_store.d.ts.map +1 -0
  94. package/dest/{archiver/kv_archiver_store → store}/message_store.js +66 -23
  95. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  96. package/dest/structs/data_retrieval.d.ts.map +1 -0
  97. package/dest/structs/inbox_message.d.ts +15 -0
  98. package/dest/structs/inbox_message.d.ts.map +1 -0
  99. package/dest/{archiver/structs → structs}/inbox_message.js +6 -6
  100. package/dest/structs/published.d.ts +2 -0
  101. package/dest/structs/published.d.ts.map +1 -0
  102. package/dest/test/fake_l1_state.d.ts +214 -0
  103. package/dest/test/fake_l1_state.d.ts.map +1 -0
  104. package/dest/test/fake_l1_state.js +517 -0
  105. package/dest/test/index.d.ts +2 -1
  106. package/dest/test/index.d.ts.map +1 -1
  107. package/dest/test/index.js +4 -1
  108. package/dest/test/mock_archiver.d.ts +5 -6
  109. package/dest/test/mock_archiver.d.ts.map +1 -1
  110. package/dest/test/mock_archiver.js +8 -12
  111. package/dest/test/mock_l1_to_l2_message_source.d.ts +6 -7
  112. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  113. package/dest/test/mock_l1_to_l2_message_source.js +19 -14
  114. package/dest/test/mock_l2_block_source.d.ts +68 -40
  115. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  116. package/dest/test/mock_l2_block_source.js +347 -145
  117. package/dest/test/mock_structs.d.ts +83 -4
  118. package/dest/test/mock_structs.d.ts.map +1 -1
  119. package/dest/test/mock_structs.js +157 -12
  120. package/dest/test/noop_l1_archiver.d.ts +34 -0
  121. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  122. package/dest/test/noop_l1_archiver.js +88 -0
  123. package/package.json +18 -18
  124. package/src/archiver.ts +785 -0
  125. package/src/config.ts +125 -0
  126. package/src/errors.ts +203 -0
  127. package/src/factory.ts +185 -22
  128. package/src/index.ts +27 -3
  129. package/src/interfaces.ts +9 -0
  130. package/src/l1/README.md +55 -0
  131. package/src/l1/bin/retrieve-calldata.ts +194 -0
  132. package/src/l1/calldata_retriever.ts +529 -0
  133. package/src/{archiver → l1}/data_retrieval.ts +157 -243
  134. package/src/l1/debug_tx.ts +99 -0
  135. package/src/l1/spire_proposer.ts +152 -0
  136. package/src/l1/trace_tx.ts +128 -0
  137. package/src/l1/types.ts +13 -0
  138. package/src/l1/validate_historical_logs.ts +140 -0
  139. package/src/l1/validate_trace.ts +229 -0
  140. package/src/modules/contract_data_source_adapter.ts +46 -0
  141. package/src/modules/data_source_base.ts +466 -0
  142. package/src/modules/data_store_updater.ts +519 -0
  143. package/src/modules/instrumentation.ts +217 -0
  144. package/src/modules/l1_synchronizer.ts +1320 -0
  145. package/src/modules/outbox_trees_resolver.ts +199 -0
  146. package/src/modules/validation.ts +186 -0
  147. package/src/store/block_store.ts +1551 -0
  148. package/src/store/contract_class_store.ts +126 -0
  149. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +70 -7
  150. package/src/store/data_stores.ts +104 -0
  151. package/src/store/function_names_cache.ts +37 -0
  152. package/src/store/l2_tips_cache.ts +35 -0
  153. package/src/store/log_store.ts +380 -0
  154. package/src/store/log_store_codec.ts +143 -0
  155. package/src/{archiver/kv_archiver_store → store}/message_store.ts +81 -28
  156. package/src/{archiver/structs → structs}/inbox_message.ts +8 -9
  157. package/src/{archiver/structs → structs}/published.ts +0 -1
  158. package/src/test/fake_l1_state.ts +770 -0
  159. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  160. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  161. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  162. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  163. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  164. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  165. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  166. package/src/test/index.ts +4 -0
  167. package/src/test/mock_archiver.ts +10 -14
  168. package/src/test/mock_l1_to_l2_message_source.ts +16 -15
  169. package/src/test/mock_l2_block_source.ts +416 -161
  170. package/src/test/mock_structs.ts +292 -14
  171. package/src/test/noop_l1_archiver.ts +158 -0
  172. package/dest/archiver/archiver.d.ts +0 -290
  173. package/dest/archiver/archiver.d.ts.map +0 -1
  174. package/dest/archiver/archiver.js +0 -1434
  175. package/dest/archiver/archiver_store.d.ts +0 -256
  176. package/dest/archiver/archiver_store.d.ts.map +0 -1
  177. package/dest/archiver/archiver_store.js +0 -4
  178. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  179. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  180. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  181. package/dest/archiver/config.d.ts +0 -21
  182. package/dest/archiver/config.d.ts.map +0 -1
  183. package/dest/archiver/config.js +0 -55
  184. package/dest/archiver/data_retrieval.d.ts +0 -80
  185. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  186. package/dest/archiver/errors.d.ts +0 -12
  187. package/dest/archiver/errors.d.ts.map +0 -1
  188. package/dest/archiver/errors.js +0 -17
  189. package/dest/archiver/index.d.ts +0 -7
  190. package/dest/archiver/index.d.ts.map +0 -1
  191. package/dest/archiver/index.js +0 -4
  192. package/dest/archiver/instrumentation.d.ts +0 -35
  193. package/dest/archiver/instrumentation.d.ts.map +0 -1
  194. package/dest/archiver/instrumentation.js +0 -140
  195. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -125
  196. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  197. package/dest/archiver/kv_archiver_store/block_store.js +0 -371
  198. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  199. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  200. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  201. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  202. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  203. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -169
  204. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  205. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  206. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  207. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  208. package/dest/archiver/kv_archiver_store/log_store.js +0 -337
  209. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  210. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  211. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  212. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  213. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  214. package/dest/archiver/structs/published.d.ts +0 -3
  215. package/dest/archiver/structs/published.d.ts.map +0 -1
  216. package/dest/archiver/validation.d.ts +0 -17
  217. package/dest/archiver/validation.d.ts.map +0 -1
  218. package/dest/rpc/index.d.ts +0 -9
  219. package/dest/rpc/index.d.ts.map +0 -1
  220. package/dest/rpc/index.js +0 -15
  221. package/src/archiver/archiver.ts +0 -1880
  222. package/src/archiver/archiver_store.ts +0 -310
  223. package/src/archiver/archiver_store_test_suite.ts +0 -1295
  224. package/src/archiver/config.ts +0 -79
  225. package/src/archiver/errors.ts +0 -26
  226. package/src/archiver/index.ts +0 -6
  227. package/src/archiver/instrumentation.ts +0 -187
  228. package/src/archiver/kv_archiver_store/block_store.ts +0 -482
  229. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  230. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -423
  231. package/src/archiver/kv_archiver_store/log_store.ts +0 -407
  232. package/src/archiver/validation.ts +0 -124
  233. package/src/rpc/index.ts +0 -16
  234. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  235. /package/dest/{archiver/structs → structs}/published.js +0 -0
  236. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,380 @@
1
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
5
+ import type { BlockHash, L2Block } from '@aztec/stdlib/block';
6
+ import { MAX_LOGS_PER_TAG } from '@aztec/stdlib/interfaces/api-limit';
7
+ import type {
8
+ LogCursor,
9
+ LogResult,
10
+ PrivateLogsQuery,
11
+ PublicLogsQuery,
12
+ SiloedTag,
13
+ Tag,
14
+ TagQuery,
15
+ } from '@aztec/stdlib/logs';
16
+ import { TxHash } from '@aztec/stdlib/tx';
17
+
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';
31
+
32
+ /**
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.
46
+ */
47
+ export class LogStore {
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
+
57
+ #log = createLogger('archiver:log_store');
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
+ */
65
+ constructor(
66
+ private db: AztecAsyncKVStore,
67
+ private blockStore: BlockStore,
68
+ private readonly genesisBlockHash: BlockHash,
69
+ ) {
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');
74
+ }
75
+
76
+ /**
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.
79
+ *
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.
82
+ */
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
+ }
137
+
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
+ }
144
+
145
+ await this.#privateKeysByBlock.set(blockNumber, privateKeys);
146
+ await this.#publicKeysByBlock.set(blockNumber, publicKeys);
147
+
148
+ this.#log.debug(`Indexed logs for block ${blockNumber}`, {
149
+ blockNumber,
150
+ privateCount: privateKeys.length,
151
+ publicCount: publicKeys.length,
152
+ });
153
+ }
154
+ return true;
155
+ });
156
+ }
157
+
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
+ */
162
+ deleteLogs(blocks: L2Block[]): Promise<boolean> {
163
+ return this.db.transactionAsync(async () => {
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);
177
+ }
178
+ if (publicKeys) {
179
+ for (const key of publicKeys) {
180
+ await this.#publicLogs.delete(key);
181
+ }
182
+ await this.#publicKeysByBlock.delete(blockNumber);
183
+ }
184
+ }
185
+ return true;
186
+ });
187
+ }
188
+
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));
193
+ }
194
+
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)));
199
+ }
200
+
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`');
204
+ }
205
+ }
206
+
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
+ }
228
+ }
229
+
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);
239
+ }
240
+
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(() => []);
251
+ }
252
+ }
253
+
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
+ }
277
+
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);
294
+ }
295
+
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);
302
+ }
303
+ }
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
+ });
314
+ }
315
+ }
316
+ }
317
+
318
+ return perTagResults;
319
+ }
320
+
321
+ /**
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.
326
+ */
327
+ getPrivateLogsForBlock(blockNumber: number): Promise<LogResult[]> {
328
+ return this.db.transactionAsync(() =>
329
+ this.#readBlockLogs(this.#privateKeysByBlock, this.#privateLogs, blockNumber),
330
+ );
331
+ }
332
+
333
+ /** {@inheritDoc LogStore.getPrivateLogsForBlock} */
334
+ getPublicLogsForBlock(blockNumber: number): Promise<LogResult[]> {
335
+ return this.db.transactionAsync(() => this.#readBlockLogs(this.#publicKeysByBlock, this.#publicLogs, blockNumber));
336
+ }
337
+
338
+ async #readBlockLogs(
339
+ keysByBlock: AztecAsyncMap<number, string[]>,
340
+ primaryMap: AztecAsyncMap<string, Buffer>,
341
+ blockNumber: number,
342
+ ): Promise<LogResult[]> {
343
+ const keys = await keysByBlock.getAsync(blockNumber);
344
+ if (!keys || keys.length === 0) {
345
+ return [];
346
+ }
347
+ const results: LogResult[] = [];
348
+ for (const key of keys) {
349
+ const raw = await primaryMap.getAsync(key);
350
+ if (!raw) {
351
+ continue;
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
+ });
364
+ }
365
+ return results;
366
+ }
367
+ }
368
+
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 };
378
+ }
379
+ return { tagHex: fieldHex((entry as T).value), afterLog: undefined };
380
+ }
@@ -0,0 +1,143 @@
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { BlockHash } from '@aztec/stdlib/block';
4
+ import { TxHash } from '@aztec/stdlib/tx';
5
+
6
+ export const NUMERIC_HEX_LEN = 8;
7
+ export const SEP = '-';
8
+
9
+ /**
10
+ * Sentinel appended after a numeric hex segment to build an end bound strictly greater than any
11
+ * real key for that namespace. `'g'` sorts lexicographically after every hex digit (`0`-`9`, `a`-`f`),
12
+ * so `prefix + '-g'` is a clean exclusive upper bound.
13
+ */
14
+ export const HEX_SENTINEL = 'g';
15
+
16
+ export type ParsedKeyTail = {
17
+ blockNumber: BlockNumber;
18
+ txIndexWithinBlock: number;
19
+ logIndexWithinTx: number;
20
+ };
21
+
22
+ /**
23
+ * Per-kind stored value layout (no msgpackr):
24
+ * txHash(32) ++ blockHash(32) ++ blockTimestamp(u64 BE = 8) ++ logDataLen(u32 BE = 4) ++ logData[i].toBuffer()...
25
+ * `blockNumber`, `txIndexWithinBlock`, and `logIndexWithinTx` are decoded from the composite key.
26
+ */
27
+ export type StoredLogValue = {
28
+ txHash: TxHash;
29
+ blockHash: BlockHash;
30
+ blockTimestamp: bigint;
31
+ logData: Fr[];
32
+ };
33
+
34
+ /** Returns the 64-char lowercase hex representation of a field, stripping the `0x` prefix. */
35
+ export function fieldHex(value: Fr | { toString: () => string }): string {
36
+ // Fr.toString() and AztecAddress.toString() both return `0x` + 64 lowercase hex chars.
37
+ return value.toString().slice(2);
38
+ }
39
+
40
+ /**
41
+ * Tag prefix for a log: the hex of its first field, or the empty string when the log carries no fields.
42
+ * A protocol-valid public log can have zero fields (e.g. a raw AVM `EMITPUBLICLOG` with `logSize = 0`),
43
+ * which has no tag to index by. Encoding it under the empty tag keeps it retrievable via the per-block
44
+ * read (and droppable on reorg) while never matching a real 64-hex-char tag query — instead of reading
45
+ * `fields[0]` off an empty array and aborting the whole block-ingestion transaction.
46
+ */
47
+ export function tagHexForLog(fields: Fr[]): string {
48
+ return fields.length > 0 ? fieldHex(fields[0]) : '';
49
+ }
50
+
51
+ /** Encodes a number as 8-char zero-padded lowercase hex (matches a u32 big-endian byte buffer's lex order). */
52
+ export function u32Hex(n: number): string {
53
+ return n.toString(16).padStart(NUMERIC_HEX_LEN, '0');
54
+ }
55
+
56
+ /**
57
+ * Encodes the composite primary key as `prefix-block-txIdx-logIdx` where `prefix` is the leading
58
+ * segment (`tag` for private; `contract-tag` for public) and the trailing triple is fixed-width
59
+ * 8-char zero-padded hex so byte-order matches `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`.
60
+ */
61
+ export function encodeKey(prefix: string, blockNumber: number, txIndex: number, logIndex: number): string {
62
+ return `${prefix}${SEP}${u32Hex(blockNumber)}${SEP}${u32Hex(txIndex)}${SEP}${u32Hex(logIndex)}`;
63
+ }
64
+
65
+ /**
66
+ * Decodes the trailing `(blockNumber, txIndexWithinBlock, logIndexWithinTx)` triple from a composite
67
+ * key. The leading prefix segments are ignored — we only ever read them off the input query, never
68
+ * back off the key.
69
+ */
70
+ export function decodeKeyTail(key: string): ParsedKeyTail {
71
+ const parts = key.split(SEP);
72
+ const len = parts.length;
73
+ return {
74
+ blockNumber: BlockNumber(parseInt(parts[len - 3], 16)),
75
+ txIndexWithinBlock: parseInt(parts[len - 2], 16),
76
+ logIndexWithinTx: parseInt(parts[len - 1], 16),
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Exclusive end bound for a `(contract, tag)`-prefix scan. With an `upperBlockExclusive` we cut at
82
+ * `(prefix, upper, 0, 0)`. With no bound we use `prefix + '-' + HEX_SENTINEL`, which sorts strictly
83
+ * after every real key under `prefix` (`g` is greater than any hex digit).
84
+ */
85
+ export function endOfTagRange(prefix: string, upperBlockExclusive: number | undefined): string {
86
+ if (upperBlockExclusive === undefined) {
87
+ return `${prefix}${SEP}${HEX_SENTINEL}`;
88
+ }
89
+ return encodeKey(prefix, upperBlockExclusive, 0, 0);
90
+ }
91
+
92
+ /**
93
+ * Exclusive end bound for a tx-strict scan: every key strictly inside `(prefix, txBlk, txIdx, *)`.
94
+ * `prefix-block-txIdx-` followed by the hex sentinel is the first key past every real logIndex for
95
+ * this tx and strictly less than the next tx's first key.
96
+ */
97
+ export function endOfTxRange(prefix: string, txBlk: number, txIdx: number): string {
98
+ return `${prefix}${SEP}${u32Hex(txBlk)}${SEP}${u32Hex(txIdx)}${SEP}${HEX_SENTINEL}`;
99
+ }
100
+
101
+ /**
102
+ * Returns the smallest string strictly greater than a fully-encoded composite key. The encoded key
103
+ * ends in a hex digit, and `'g'` sorts strictly after any hex digit, so appending `'g'` is the
104
+ * smallest possible successor in our key alphabet. Used to turn an inclusive cursor into an
105
+ * exclusive `start`.
106
+ */
107
+ export function incKey(key: string): string {
108
+ return key + HEX_SENTINEL;
109
+ }
110
+
111
+ export function encodeValue(value: StoredLogValue): Buffer {
112
+ const head = Buffer.allocUnsafe(32 + 32 + 8 + 4);
113
+ value.txHash.toBuffer().copy(head, 0);
114
+ value.blockHash.toBuffer().copy(head, 32);
115
+ head.writeBigUInt64BE(value.blockTimestamp, 64);
116
+ head.writeUInt32BE(value.logData.length, 72);
117
+ const fieldBufs = value.logData.map(f => f.toBuffer());
118
+ return Buffer.concat([head, ...fieldBufs]);
119
+ }
120
+
121
+ export function decodeValue(buffer: Buffer | Uint8Array): StoredLogValue {
122
+ const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
123
+ let off = 0;
124
+ const txHash = TxHash.fromBuffer(buf.subarray(off, off + 32));
125
+ off += 32;
126
+ const blockHash = BlockHash.fromBuffer(buf.subarray(off, off + 32));
127
+ off += 32;
128
+ const blockTimestamp = buf.readBigUInt64BE(off);
129
+ off += 8;
130
+ const logDataLen = buf.readUInt32BE(off);
131
+ off += 4;
132
+ const logData: Fr[] = new Array(logDataLen);
133
+ for (let i = 0; i < logDataLen; i++) {
134
+ logData[i] = Fr.fromBuffer(buf.subarray(off, off + 32));
135
+ off += 32;
136
+ }
137
+ return { txHash, blockHash, blockTimestamp, logData };
138
+ }
139
+
140
+ /** Encodes the public-log key prefix as `contractHex-tagHex`. */
141
+ export function encodePublicPrefix(contractHex: string, tagHex: string): string {
142
+ return `${contractHex}${SEP}${tagHex}`;
143
+ }