@aztec/archiver 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240

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 (232) hide show
  1. package/README.md +164 -22
  2. package/dest/archiver.d.ts +158 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +881 -0
  5. package/dest/config.d.ts +33 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +31 -14
  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 +112 -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/{archiver/l1 → l1}/bin/retrieve-calldata.d.ts +1 -1
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.js +35 -32
  23. package/dest/l1/calldata_retriever.d.ts +136 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +412 -0
  26. package/dest/l1/data_retrieval.d.ts +97 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver/l1 → l1}/data_retrieval.js +65 -89
  29. package/dest/{archiver/l1 → l1}/debug_tx.d.ts +1 -1
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/{archiver/l1 → l1}/spire_proposer.d.ts +5 -5
  32. package/dest/l1/spire_proposer.d.ts.map +1 -0
  33. package/dest/{archiver/l1 → l1}/spire_proposer.js +9 -17
  34. package/dest/l1/trace_tx.d.ts +43 -0
  35. package/dest/l1/trace_tx.d.ts.map +1 -0
  36. package/dest/l1/types.d.ts +12 -0
  37. package/dest/l1/types.d.ts.map +1 -0
  38. package/dest/l1/validate_historical_logs.d.ts +23 -0
  39. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  40. package/dest/l1/validate_historical_logs.js +108 -0
  41. package/dest/{archiver/l1 → l1}/validate_trace.d.ts +6 -3
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/{archiver/l1 → l1}/validate_trace.js +13 -9
  44. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  45. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  46. package/dest/modules/contract_data_source_adapter.js +40 -0
  47. package/dest/modules/data_source_base.d.ts +113 -0
  48. package/dest/modules/data_source_base.d.ts.map +1 -0
  49. package/dest/modules/data_source_base.js +351 -0
  50. package/dest/modules/data_store_updater.d.ts +105 -0
  51. package/dest/modules/data_store_updater.d.ts.map +1 -0
  52. package/dest/modules/data_store_updater.js +392 -0
  53. package/dest/modules/instrumentation.d.ts +55 -0
  54. package/dest/modules/instrumentation.d.ts.map +1 -0
  55. package/dest/{archiver → modules}/instrumentation.js +61 -19
  56. package/dest/modules/l1_synchronizer.d.ts +77 -0
  57. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  58. package/dest/modules/l1_synchronizer.js +1344 -0
  59. package/dest/modules/validation.d.ts +18 -0
  60. package/dest/modules/validation.d.ts.map +1 -0
  61. package/dest/{archiver → modules}/validation.js +12 -6
  62. package/dest/store/block_store.d.ts +300 -0
  63. package/dest/store/block_store.d.ts.map +1 -0
  64. package/dest/store/block_store.js +1219 -0
  65. package/dest/store/contract_class_store.d.ts +31 -0
  66. package/dest/store/contract_class_store.d.ts.map +1 -0
  67. package/dest/store/contract_class_store.js +80 -0
  68. package/dest/store/contract_instance_store.d.ts +51 -0
  69. package/dest/store/contract_instance_store.d.ts.map +1 -0
  70. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +38 -3
  71. package/dest/store/data_stores.d.ts +68 -0
  72. package/dest/store/data_stores.d.ts.map +1 -0
  73. package/dest/store/data_stores.js +54 -0
  74. package/dest/store/function_names_cache.d.ts +17 -0
  75. package/dest/store/function_names_cache.d.ts.map +1 -0
  76. package/dest/store/function_names_cache.js +30 -0
  77. package/dest/store/l2_tips_cache.d.ts +25 -0
  78. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  79. package/dest/store/l2_tips_cache.js +26 -0
  80. package/dest/store/log_store.d.ts +59 -0
  81. package/dest/store/log_store.d.ts.map +1 -0
  82. package/dest/store/log_store.js +310 -0
  83. package/dest/store/log_store_codec.d.ts +70 -0
  84. package/dest/store/log_store_codec.d.ts.map +1 -0
  85. package/dest/store/log_store_codec.js +101 -0
  86. package/dest/store/message_store.d.ts +50 -0
  87. package/dest/store/message_store.d.ts.map +1 -0
  88. package/dest/{archiver/kv_archiver_store → store}/message_store.js +51 -9
  89. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  90. package/dest/structs/data_retrieval.d.ts.map +1 -0
  91. package/dest/structs/inbox_message.d.ts +15 -0
  92. package/dest/structs/inbox_message.d.ts.map +1 -0
  93. package/dest/{archiver/structs → structs}/published.d.ts +1 -1
  94. package/dest/structs/published.d.ts.map +1 -0
  95. package/dest/test/fake_l1_state.d.ts +214 -0
  96. package/dest/test/fake_l1_state.d.ts.map +1 -0
  97. package/dest/test/fake_l1_state.js +517 -0
  98. package/dest/test/index.d.ts +2 -1
  99. package/dest/test/index.d.ts.map +1 -1
  100. package/dest/test/index.js +4 -1
  101. package/dest/test/mock_archiver.d.ts +2 -2
  102. package/dest/test/mock_archiver.d.ts.map +1 -1
  103. package/dest/test/mock_archiver.js +3 -3
  104. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  105. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  106. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  107. package/dest/test/mock_l2_block_source.d.ts +65 -41
  108. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  109. package/dest/test/mock_l2_block_source.js +330 -151
  110. package/dest/test/mock_structs.d.ts +81 -3
  111. package/dest/test/mock_structs.d.ts.map +1 -1
  112. package/dest/test/mock_structs.js +152 -7
  113. package/dest/test/noop_l1_archiver.d.ts +29 -0
  114. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  115. package/dest/test/noop_l1_archiver.js +85 -0
  116. package/package.json +17 -18
  117. package/src/archiver.ts +681 -0
  118. package/src/{archiver/config.ts → config.ts} +43 -12
  119. package/src/errors.ts +203 -0
  120. package/src/factory.ts +175 -22
  121. package/src/index.ts +27 -3
  122. package/src/interfaces.ts +9 -0
  123. package/src/l1/README.md +55 -0
  124. package/src/{archiver/l1 → l1}/bin/retrieve-calldata.ts +45 -33
  125. package/src/l1/calldata_retriever.ts +522 -0
  126. package/src/{archiver/l1 → l1}/data_retrieval.ts +106 -134
  127. package/src/{archiver/l1 → l1}/spire_proposer.ts +7 -15
  128. package/src/l1/validate_historical_logs.ts +140 -0
  129. package/src/{archiver/l1 → l1}/validate_trace.ts +24 -6
  130. package/src/modules/contract_data_source_adapter.ts +55 -0
  131. package/src/modules/data_source_base.ts +493 -0
  132. package/src/modules/data_store_updater.ts +518 -0
  133. package/src/{archiver → modules}/instrumentation.ts +72 -20
  134. package/src/modules/l1_synchronizer.ts +1257 -0
  135. package/src/{archiver → modules}/validation.ts +15 -9
  136. package/src/store/block_store.ts +1590 -0
  137. package/src/store/contract_class_store.ts +108 -0
  138. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +52 -6
  139. package/src/store/data_stores.ts +104 -0
  140. package/src/store/function_names_cache.ts +37 -0
  141. package/src/store/l2_tips_cache.ts +35 -0
  142. package/src/store/log_store.ts +379 -0
  143. package/src/store/log_store_codec.ts +132 -0
  144. package/src/{archiver/kv_archiver_store → store}/message_store.ts +60 -10
  145. package/src/{archiver/structs → structs}/inbox_message.ts +1 -1
  146. package/src/test/fake_l1_state.ts +770 -0
  147. package/src/test/index.ts +4 -0
  148. package/src/test/mock_archiver.ts +4 -3
  149. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  150. package/src/test/mock_l2_block_source.ts +403 -171
  151. package/src/test/mock_structs.ts +283 -8
  152. package/src/test/noop_l1_archiver.ts +139 -0
  153. package/dest/archiver/archiver.d.ts +0 -307
  154. package/dest/archiver/archiver.d.ts.map +0 -1
  155. package/dest/archiver/archiver.js +0 -2102
  156. package/dest/archiver/archiver_store.d.ts +0 -315
  157. package/dest/archiver/archiver_store.d.ts.map +0 -1
  158. package/dest/archiver/archiver_store.js +0 -4
  159. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  160. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  161. package/dest/archiver/archiver_store_test_suite.js +0 -2770
  162. package/dest/archiver/config.d.ts +0 -22
  163. package/dest/archiver/config.d.ts.map +0 -1
  164. package/dest/archiver/errors.d.ts +0 -36
  165. package/dest/archiver/errors.d.ts.map +0 -1
  166. package/dest/archiver/errors.js +0 -54
  167. package/dest/archiver/index.d.ts +0 -7
  168. package/dest/archiver/index.d.ts.map +0 -1
  169. package/dest/archiver/index.js +0 -4
  170. package/dest/archiver/instrumentation.d.ts +0 -37
  171. package/dest/archiver/instrumentation.d.ts.map +0 -1
  172. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -164
  173. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  174. package/dest/archiver/kv_archiver_store/block_store.js +0 -626
  175. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  176. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  177. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  178. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  179. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  180. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -159
  181. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -316
  183. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -45
  184. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  185. package/dest/archiver/kv_archiver_store/log_store.js +0 -401
  186. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -40
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  188. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +0 -1
  189. package/dest/archiver/l1/calldata_retriever.d.ts +0 -112
  190. package/dest/archiver/l1/calldata_retriever.d.ts.map +0 -1
  191. package/dest/archiver/l1/calldata_retriever.js +0 -471
  192. package/dest/archiver/l1/data_retrieval.d.ts +0 -90
  193. package/dest/archiver/l1/data_retrieval.d.ts.map +0 -1
  194. package/dest/archiver/l1/debug_tx.d.ts.map +0 -1
  195. package/dest/archiver/l1/spire_proposer.d.ts.map +0 -1
  196. package/dest/archiver/l1/trace_tx.d.ts +0 -97
  197. package/dest/archiver/l1/trace_tx.d.ts.map +0 -1
  198. package/dest/archiver/l1/types.d.ts +0 -12
  199. package/dest/archiver/l1/types.d.ts.map +0 -1
  200. package/dest/archiver/l1/validate_trace.d.ts.map +0 -1
  201. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  202. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  203. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  204. package/dest/archiver/structs/published.d.ts.map +0 -1
  205. package/dest/archiver/validation.d.ts +0 -17
  206. package/dest/archiver/validation.d.ts.map +0 -1
  207. package/dest/rpc/index.d.ts +0 -9
  208. package/dest/rpc/index.d.ts.map +0 -1
  209. package/dest/rpc/index.js +0 -15
  210. package/src/archiver/archiver.ts +0 -2265
  211. package/src/archiver/archiver_store.ts +0 -380
  212. package/src/archiver/archiver_store_test_suite.ts +0 -2842
  213. package/src/archiver/errors.ts +0 -90
  214. package/src/archiver/index.ts +0 -6
  215. package/src/archiver/kv_archiver_store/block_store.ts +0 -850
  216. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  217. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -442
  218. package/src/archiver/kv_archiver_store/log_store.ts +0 -516
  219. package/src/archiver/l1/README.md +0 -98
  220. package/src/archiver/l1/calldata_retriever.ts +0 -641
  221. package/src/rpc/index.ts +0 -16
  222. /package/dest/{archiver/l1 → l1}/debug_tx.js +0 -0
  223. /package/dest/{archiver/l1 → l1}/trace_tx.js +0 -0
  224. /package/dest/{archiver/l1 → l1}/types.js +0 -0
  225. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  226. /package/dest/{archiver/structs → structs}/inbox_message.js +0 -0
  227. /package/dest/{archiver/structs → structs}/published.js +0 -0
  228. /package/src/{archiver/l1 → l1}/debug_tx.ts +0 -0
  229. /package/src/{archiver/l1 → l1}/trace_tx.ts +0 -0
  230. /package/src/{archiver/l1 → l1}/types.ts +0 -0
  231. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
  232. /package/src/{archiver/structs → structs}/published.ts +0 -0
@@ -0,0 +1,379 @@
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
+ } from './log_store_codec.js';
30
+
31
+ /**
32
+ * Indexes every emitted private and public log under a composite hex-string key
33
+ * `[contractAddress (public only)]-tag-blockNumber-txIndexWithinBlock-logIndexWithinTx`,
34
+ * where each numeric segment is zero-padded to 8 lowercase hex digits (4 bytes BE) and
35
+ * `contractAddress` / `tag` are the bare 64-hex-char field representations (no `0x` prefix). The
36
+ * fixed-width zero-padded hex segments sort lexicographically in the same order as the canonical
37
+ * `(contract, tag, blockNumber, txIndexWithinBlock, logIndexWithinTx)` tuple, so a single ordered
38
+ * range scan answers every {@link PrivateLogsQuery} / {@link PublicLogsQuery}.
39
+ *
40
+ * Per-block secondary indices (`#privateKeysByBlock`, `#publicKeysByBlock`) record the exact primary
41
+ * keys written for each block so {@link deleteLogs} can drop them on reorg without having to range
42
+ * scan by block (block isn't the leading key segment).
43
+ *
44
+ * Contract-class logs are no longer stored or served by the log store.
45
+ */
46
+ export class LogStore {
47
+ /** Primary map: composite private key (tag + tail = 96 hex chars + separators) -> serialized {@link StoredLogValue}. */
48
+ #privateLogs: AztecAsyncMap<string, Buffer>;
49
+ /** Primary map: composite public key (contract + tag + tail) -> serialized {@link StoredLogValue}. */
50
+ #publicLogs: AztecAsyncMap<string, Buffer>;
51
+
52
+ /** Secondary deletion index: blockNumber -> the exact primary keys written for that block. */
53
+ #privateKeysByBlock: AztecAsyncMap<number, string[]>;
54
+ #publicKeysByBlock: AztecAsyncMap<number, string[]>;
55
+
56
+ #log = createLogger('archiver:log_store');
57
+
58
+ /**
59
+ * @param genesisBlockHash - Hash of the synthetic genesis block. During early sync the PXE anchors to
60
+ * genesis and passes its hash as a query `referenceBlock`; since the archiver never indexes the
61
+ * genesis block, the store recognizes this hash directly and resolves it to the genesis block number
62
+ * rather than mistaking it for a reorg.
63
+ */
64
+ constructor(
65
+ private db: AztecAsyncKVStore,
66
+ private blockStore: BlockStore,
67
+ private readonly genesisBlockHash: BlockHash,
68
+ ) {
69
+ this.#privateLogs = db.openMap('archiver_private_logs');
70
+ this.#publicLogs = db.openMap('archiver_public_logs');
71
+ this.#privateKeysByBlock = db.openMap('archiver_private_log_keys_by_block');
72
+ this.#publicKeysByBlock = db.openMap('archiver_public_log_keys_by_block');
73
+ }
74
+
75
+ /**
76
+ * Indexes every emitted private and public log from the given blocks. Wraps the write in a single
77
+ * `db.transactionAsync` so the primary entries and the per-block secondary indices stay consistent.
78
+ *
79
+ * A block is only ever added once; on reorg the archiver calls {@link deleteLogs} first, so we write
80
+ * the secondary index entries with a plain `set` (overwrite) rather than read-modify-append.
81
+ */
82
+ addLogs(blocks: L2Block[]): Promise<boolean> {
83
+ return this.db.transactionAsync(async () => {
84
+ for (const block of blocks) {
85
+ const blockHash = await block.hash();
86
+ const blockNumber = block.number;
87
+ const blockTimestamp = block.timestamp;
88
+
89
+ const privateKeys: string[] = [];
90
+ const privateValues: Buffer[] = [];
91
+ const publicKeys: string[] = [];
92
+ const publicValues: Buffer[] = [];
93
+
94
+ for (let txIndexWithinBlock = 0; txIndexWithinBlock < block.body.txEffects.length; txIndexWithinBlock++) {
95
+ const txEffect = block.body.txEffects[txIndexWithinBlock];
96
+ const txHash = txEffect.txHash;
97
+
98
+ // Private and public log indices are counted independently per tx, each starting at 0.
99
+ let privateLogIndexWithinTx = 0;
100
+ let publicLogIndexWithinTx = 0;
101
+
102
+ for (const log of txEffect.privateLogs) {
103
+ const tagHex = fieldHex(log.fields[0]);
104
+ const key = encodeKey(tagHex, blockNumber, txIndexWithinBlock, privateLogIndexWithinTx);
105
+ const value = encodeValue({
106
+ txHash,
107
+ blockHash,
108
+ blockTimestamp,
109
+ logData: log.getEmittedFields(),
110
+ });
111
+ privateKeys.push(key);
112
+ privateValues.push(value);
113
+ privateLogIndexWithinTx++;
114
+ }
115
+
116
+ for (const log of txEffect.publicLogs) {
117
+ const contractHex = fieldHex(log.contractAddress);
118
+ const tagHex = fieldHex(log.fields[0]);
119
+ const key = encodeKey(
120
+ encodePublicPrefix(contractHex, tagHex),
121
+ blockNumber,
122
+ txIndexWithinBlock,
123
+ publicLogIndexWithinTx,
124
+ );
125
+ const value = encodeValue({
126
+ txHash,
127
+ blockHash,
128
+ blockTimestamp,
129
+ logData: log.getEmittedFields(),
130
+ });
131
+ publicKeys.push(key);
132
+ publicValues.push(value);
133
+ publicLogIndexWithinTx++;
134
+ }
135
+ }
136
+
137
+ for (let i = 0; i < privateKeys.length; i++) {
138
+ await this.#privateLogs.set(privateKeys[i], privateValues[i]);
139
+ }
140
+ for (let i = 0; i < publicKeys.length; i++) {
141
+ await this.#publicLogs.set(publicKeys[i], publicValues[i]);
142
+ }
143
+
144
+ await this.#privateKeysByBlock.set(blockNumber, privateKeys);
145
+ await this.#publicKeysByBlock.set(blockNumber, publicKeys);
146
+
147
+ this.#log.debug(`Indexed logs for block ${blockNumber}`, {
148
+ blockNumber,
149
+ privateCount: privateKeys.length,
150
+ publicCount: publicKeys.length,
151
+ });
152
+ }
153
+ return true;
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Deletes every log indexed under any of the given blocks. Secondary-index driven, so it doesn't
159
+ * have to range-scan the primary maps.
160
+ */
161
+ deleteLogs(blocks: L2Block[]): Promise<boolean> {
162
+ return this.db.transactionAsync(async () => {
163
+ for (const block of blocks) {
164
+ const blockNumber = block.number;
165
+
166
+ const [privateKeys, publicKeys] = await Promise.all([
167
+ this.#privateKeysByBlock.getAsync(blockNumber),
168
+ this.#publicKeysByBlock.getAsync(blockNumber),
169
+ ]);
170
+
171
+ if (privateKeys) {
172
+ for (const key of privateKeys) {
173
+ await this.#privateLogs.delete(key);
174
+ }
175
+ await this.#privateKeysByBlock.delete(blockNumber);
176
+ }
177
+ if (publicKeys) {
178
+ for (const key of publicKeys) {
179
+ await this.#publicLogs.delete(key);
180
+ }
181
+ await this.#publicKeysByBlock.delete(blockNumber);
182
+ }
183
+ }
184
+ return true;
185
+ });
186
+ }
187
+
188
+ /** Returns one inner array per element of `query.tags`, in input order. */
189
+ getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
190
+ LogStore.#validateQuery(query);
191
+ return this.db.transactionAsync(() => this.#runQuery(query, /* contractHex */ undefined));
192
+ }
193
+
194
+ /** Returns one inner array per element of `query.tags`, in input order. */
195
+ getPublicLogsByTags(query: PublicLogsQuery): Promise<LogResult[][]> {
196
+ LogStore.#validateQuery(query);
197
+ return this.db.transactionAsync(() => this.#runQuery(query, fieldHex(query.contractAddress)));
198
+ }
199
+
200
+ static #validateQuery(query: { txHash?: TxHash; fromBlock?: unknown; toBlock?: unknown }): void {
201
+ if (query.txHash !== undefined && (query.fromBlock !== undefined || query.toBlock !== undefined)) {
202
+ throw new Error('`txHash` is mutually exclusive with `fromBlock`/`toBlock`');
203
+ }
204
+ }
205
+
206
+ async #runQuery(query: PrivateLogsQuery | PublicLogsQuery, contractHex: string | undefined): Promise<LogResult[][]> {
207
+ const isPublic = contractHex !== undefined;
208
+ const tags = (query.tags as ReadonlyArray<TagQuery<Tag | SiloedTag>>) ?? [];
209
+ const primaryMap = isPublic ? this.#publicLogs : this.#privateLogs;
210
+
211
+ // referenceBlock reorg check, in-transaction, against the same db the log primary maps live on. The
212
+ // genesis block is a valid anchor during early sync but is synthetic and never indexed in the block
213
+ // store, so resolve it directly to the genesis block number rather than mistaking it for a reorg.
214
+ let referenceBlockNumber: number | undefined;
215
+ if (query.referenceBlock) {
216
+ if (query.referenceBlock.equals(this.genesisBlockHash)) {
217
+ referenceBlockNumber = INITIAL_L2_BLOCK_NUM - 1;
218
+ } else {
219
+ const refBlk = await this.blockStore.getBlockData({ hash: query.referenceBlock });
220
+ if (!refBlk) {
221
+ throw new Error(
222
+ `Reference block ${query.referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
223
+ );
224
+ }
225
+ referenceBlockNumber = refBlk.header.globalVariables.blockNumber;
226
+ }
227
+ }
228
+
229
+ // Compute the exclusive upper-block bound across `toBlock` and `referenceBlock`.
230
+ // `toBlock` is already exclusive; `referenceBlock` caps inclusively, so its exclusive form is +1.
231
+ let upperExclusive: number | undefined;
232
+ if (query.toBlock !== undefined) {
233
+ upperExclusive = query.toBlock;
234
+ }
235
+ if (referenceBlockNumber !== undefined) {
236
+ const refExclusive = referenceBlockNumber + 1;
237
+ upperExclusive = upperExclusive === undefined ? refExclusive : Math.min(upperExclusive, refExclusive);
238
+ }
239
+
240
+ // Resolve txHash -> (blockNumber, txIndexInBlock) once for the whole query.
241
+ let txLocation: [number, number] | undefined;
242
+ if (query.txHash) {
243
+ const loc = await this.blockStore.getTxLocation(query.txHash);
244
+ if (!loc) {
245
+ return tags.map(() => []);
246
+ }
247
+ txLocation = loc;
248
+ if (upperExclusive !== undefined && txLocation[0] >= upperExclusive) {
249
+ return tags.map(() => []);
250
+ }
251
+ }
252
+
253
+ const fromBlock = query.fromBlock ?? INITIAL_L2_BLOCK_NUM;
254
+ const includeEffects = query.includeEffects === true;
255
+
256
+ const perTagResults: LogResult[][] = [];
257
+ for (const tagEntry of tags) {
258
+ const { tagHex, afterLog } = normalizeTagEntry(tagEntry);
259
+ const prefix = contractHex !== undefined ? encodePublicPrefix(contractHex, tagHex) : tagHex;
260
+
261
+ const end = txLocation
262
+ ? endOfTxRange(prefix, txLocation[0], txLocation[1])
263
+ : endOfTagRange(prefix, upperExclusive);
264
+
265
+ let start: string;
266
+ if (afterLog) {
267
+ // Cursor wins as the start; `fromBlock` is ignored (fine if the cursor sits below it). The cursor
268
+ // carries `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`, which slot directly into the
269
+ // composite key — no tx-hash lookup needed.
270
+ start = incKey(encodeKey(prefix, afterLog.blockNumber, afterLog.txIndexWithinBlock, afterLog.logIndexWithinTx));
271
+ } else if (txLocation) {
272
+ start = encodeKey(prefix, txLocation[0], txLocation[1], 0);
273
+ } else {
274
+ start = encodeKey(prefix, fromBlock, 0, 0);
275
+ }
276
+
277
+ const limit = query.limitPerTag ?? MAX_LOGS_PER_TAG;
278
+ const out: LogResult[] = [];
279
+ for await (const [rawKey, rawVal] of primaryMap.entriesAsync({ start, end, limit })) {
280
+ const tail = decodeKeyTail(rawKey);
281
+ const value = decodeValue(rawVal);
282
+ out.push({
283
+ logData: value.logData,
284
+ blockNumber: tail.blockNumber,
285
+ blockHash: value.blockHash,
286
+ blockTimestamp: value.blockTimestamp,
287
+ txHash: value.txHash,
288
+ txIndexWithinBlock: tail.txIndexWithinBlock,
289
+ logIndexWithinTx: tail.logIndexWithinTx,
290
+ });
291
+ }
292
+ perTagResults.push(out);
293
+ }
294
+
295
+ if (includeEffects) {
296
+ // Dedupe by txHash across the entire page so a tx with many tagged logs costs one fetch.
297
+ const txHashByKey = new Map<string, TxHash>();
298
+ for (const arr of perTagResults) {
299
+ for (const log of arr) {
300
+ txHashByKey.set(log.txHash.toString(), log.txHash);
301
+ }
302
+ }
303
+ const uniqueTxs = Array.from(txHashByKey.values());
304
+ if (uniqueTxs.length > 0) {
305
+ const effects = await this.blockStore.getNoteHashesAndNullifiers(uniqueTxs);
306
+ const byTxHash = new Map<string, [Fr[], Fr[]]>();
307
+ uniqueTxs.forEach((tx, i) => byTxHash.set(tx.toString(), effects[i]));
308
+ for (let i = 0; i < perTagResults.length; i++) {
309
+ perTagResults[i] = perTagResults[i].map(log => {
310
+ const [noteHashes, nullifiers] = byTxHash.get(log.txHash.toString()) ?? [[], []];
311
+ return { ...log, noteHashes, nullifiers };
312
+ });
313
+ }
314
+ }
315
+ }
316
+
317
+ return perTagResults;
318
+ }
319
+
320
+ /**
321
+ * Reads back every private log indexed for the given block via the per-block secondary index. Order
322
+ * matches the canonical composite-key order (`tag`, `blockNumber`, `txIndexWithinBlock`,
323
+ * `logIndexWithinTx`). Used by the data-store-updater test suite to verify the indexed-vs-block-body
324
+ * counts without depending on the removed `getPublicLogs(LogFilter)` API.
325
+ */
326
+ getPrivateLogsForBlock(blockNumber: number): Promise<LogResult[]> {
327
+ return this.db.transactionAsync(() =>
328
+ this.#readBlockLogs(this.#privateKeysByBlock, this.#privateLogs, blockNumber),
329
+ );
330
+ }
331
+
332
+ /** {@inheritDoc LogStore.getPrivateLogsForBlock} */
333
+ getPublicLogsForBlock(blockNumber: number): Promise<LogResult[]> {
334
+ return this.db.transactionAsync(() => this.#readBlockLogs(this.#publicKeysByBlock, this.#publicLogs, blockNumber));
335
+ }
336
+
337
+ async #readBlockLogs(
338
+ keysByBlock: AztecAsyncMap<number, string[]>,
339
+ primaryMap: AztecAsyncMap<string, Buffer>,
340
+ blockNumber: number,
341
+ ): Promise<LogResult[]> {
342
+ const keys = await keysByBlock.getAsync(blockNumber);
343
+ if (!keys || keys.length === 0) {
344
+ return [];
345
+ }
346
+ const results: LogResult[] = [];
347
+ for (const key of keys) {
348
+ const raw = await primaryMap.getAsync(key);
349
+ if (!raw) {
350
+ continue;
351
+ }
352
+ const tail = decodeKeyTail(key);
353
+ const value = decodeValue(raw);
354
+ results.push({
355
+ logData: value.logData,
356
+ blockNumber: tail.blockNumber,
357
+ blockHash: value.blockHash,
358
+ blockTimestamp: value.blockTimestamp,
359
+ txHash: value.txHash,
360
+ txIndexWithinBlock: tail.txIndexWithinBlock,
361
+ logIndexWithinTx: tail.logIndexWithinTx,
362
+ });
363
+ }
364
+ return results;
365
+ }
366
+ }
367
+
368
+ /** Pulls `{ tagHex, afterLog }` out of a {@link TagQuery}, normalizing the bare-tag form. */
369
+ function normalizeTagEntry<T extends Tag | SiloedTag>(
370
+ entry: TagQuery<T>,
371
+ ): {
372
+ tagHex: string;
373
+ afterLog: LogCursor | undefined;
374
+ } {
375
+ if (typeof entry === 'object' && entry !== null && 'tag' in entry) {
376
+ return { tagHex: fieldHex(entry.tag.value), afterLog: entry.afterLog };
377
+ }
378
+ return { tagHex: fieldHex((entry as T).value), afterLog: undefined };
379
+ }
@@ -0,0 +1,132 @@
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
+ /** Encodes a number as 8-char zero-padded lowercase hex (matches a u32 big-endian byte buffer's lex order). */
41
+ export function u32Hex(n: number): string {
42
+ return n.toString(16).padStart(NUMERIC_HEX_LEN, '0');
43
+ }
44
+
45
+ /**
46
+ * Encodes the composite primary key as `prefix-block-txIdx-logIdx` where `prefix` is the leading
47
+ * segment (`tag` for private; `contract-tag` for public) and the trailing triple is fixed-width
48
+ * 8-char zero-padded hex so byte-order matches `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`.
49
+ */
50
+ export function encodeKey(prefix: string, blockNumber: number, txIndex: number, logIndex: number): string {
51
+ return `${prefix}${SEP}${u32Hex(blockNumber)}${SEP}${u32Hex(txIndex)}${SEP}${u32Hex(logIndex)}`;
52
+ }
53
+
54
+ /**
55
+ * Decodes the trailing `(blockNumber, txIndexWithinBlock, logIndexWithinTx)` triple from a composite
56
+ * key. The leading prefix segments are ignored — we only ever read them off the input query, never
57
+ * back off the key.
58
+ */
59
+ export function decodeKeyTail(key: string): ParsedKeyTail {
60
+ const parts = key.split(SEP);
61
+ const len = parts.length;
62
+ return {
63
+ blockNumber: BlockNumber(parseInt(parts[len - 3], 16)),
64
+ txIndexWithinBlock: parseInt(parts[len - 2], 16),
65
+ logIndexWithinTx: parseInt(parts[len - 1], 16),
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Exclusive end bound for a `(contract, tag)`-prefix scan. With an `upperBlockExclusive` we cut at
71
+ * `(prefix, upper, 0, 0)`. With no bound we use `prefix + '-' + HEX_SENTINEL`, which sorts strictly
72
+ * after every real key under `prefix` (`g` is greater than any hex digit).
73
+ */
74
+ export function endOfTagRange(prefix: string, upperBlockExclusive: number | undefined): string {
75
+ if (upperBlockExclusive === undefined) {
76
+ return `${prefix}${SEP}${HEX_SENTINEL}`;
77
+ }
78
+ return encodeKey(prefix, upperBlockExclusive, 0, 0);
79
+ }
80
+
81
+ /**
82
+ * Exclusive end bound for a tx-strict scan: every key strictly inside `(prefix, txBlk, txIdx, *)`.
83
+ * `prefix-block-txIdx-` followed by the hex sentinel is the first key past every real logIndex for
84
+ * this tx and strictly less than the next tx's first key.
85
+ */
86
+ export function endOfTxRange(prefix: string, txBlk: number, txIdx: number): string {
87
+ return `${prefix}${SEP}${u32Hex(txBlk)}${SEP}${u32Hex(txIdx)}${SEP}${HEX_SENTINEL}`;
88
+ }
89
+
90
+ /**
91
+ * Returns the smallest string strictly greater than a fully-encoded composite key. The encoded key
92
+ * ends in a hex digit, and `'g'` sorts strictly after any hex digit, so appending `'g'` is the
93
+ * smallest possible successor in our key alphabet. Used to turn an inclusive cursor into an
94
+ * exclusive `start`.
95
+ */
96
+ export function incKey(key: string): string {
97
+ return key + HEX_SENTINEL;
98
+ }
99
+
100
+ export function encodeValue(value: StoredLogValue): Buffer {
101
+ const head = Buffer.allocUnsafe(32 + 32 + 8 + 4);
102
+ value.txHash.toBuffer().copy(head, 0);
103
+ value.blockHash.toBuffer().copy(head, 32);
104
+ head.writeBigUInt64BE(value.blockTimestamp, 64);
105
+ head.writeUInt32BE(value.logData.length, 72);
106
+ const fieldBufs = value.logData.map(f => f.toBuffer());
107
+ return Buffer.concat([head, ...fieldBufs]);
108
+ }
109
+
110
+ export function decodeValue(buffer: Buffer | Uint8Array): StoredLogValue {
111
+ const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
112
+ let off = 0;
113
+ const txHash = TxHash.fromBuffer(buf.subarray(off, off + 32));
114
+ off += 32;
115
+ const blockHash = BlockHash.fromBuffer(buf.subarray(off, off + 32));
116
+ off += 32;
117
+ const blockTimestamp = buf.readBigUInt64BE(off);
118
+ off += 8;
119
+ const logDataLen = buf.readUInt32BE(off);
120
+ off += 4;
121
+ const logData: Fr[] = new Array(logDataLen);
122
+ for (let i = 0; i < logDataLen; i++) {
123
+ logData[i] = Fr.fromBuffer(buf.subarray(off, off + 32));
124
+ off += 32;
125
+ }
126
+ return { txHash, blockHash, blockTimestamp, logData };
127
+ }
128
+
129
+ /** Encodes the public-log key prefix as `contractHex-tagHex`. */
130
+ export function encodePublicPrefix(contractHex: string, tagHex: string): string {
131
+ return `${contractHex}${SEP}${tagHex}`;
132
+ }
@@ -14,6 +14,7 @@ import {
14
14
  } from '@aztec/kv-store';
15
15
  import { InboxLeaf } from '@aztec/stdlib/messaging';
16
16
 
17
+ import { L1ToL2MessagesNotReadyError } from '../errors.js';
17
18
  import {
18
19
  type InboxMessage,
19
20
  deserializeInboxMessage,
@@ -40,6 +41,10 @@ export class MessageStore {
40
41
  #lastSynchedL1Block: AztecAsyncSingleton<Buffer>;
41
42
  /** Stores total messages stored */
42
43
  #totalMessageCount: AztecAsyncSingleton<bigint>;
44
+ /** Stores the checkpoint number whose message tree is currently being filled on L1. */
45
+ #inboxTreeInProgress: AztecAsyncSingleton<bigint>;
46
+ /** Stores the L1 finalized block as of the last successful message sync. */
47
+ #messagesFinalizedL1Block: AztecAsyncSingleton<Buffer>;
43
48
 
44
49
  #log = createLogger('archiver:message_store');
45
50
 
@@ -48,6 +53,8 @@ export class MessageStore {
48
53
  this.#l1ToL2MessageIndices = db.openMap('archiver_l1_to_l2_message_indices');
49
54
  this.#lastSynchedL1Block = db.openSingleton('archiver_last_l1_block_id');
50
55
  this.#totalMessageCount = db.openSingleton('archiver_l1_to_l2_message_count');
56
+ this.#inboxTreeInProgress = db.openSingleton('archiver_inbox_tree_in_progress');
57
+ this.#messagesFinalizedL1Block = db.openSingleton('archiver_messages_finalized_l1_block');
51
58
  }
52
59
 
53
60
  public async getTotalL1ToL2MessageCount(): Promise<bigint> {
@@ -71,6 +78,26 @@ export class MessageStore {
71
78
  await this.#lastSynchedL1Block.set(buffer);
72
79
  }
73
80
 
81
+ /** Gets the L1 finalized block as of the last successful message sync. */
82
+ public async getMessagesFinalizedL1Block(): Promise<L1BlockId | undefined> {
83
+ const buffer = await this.#messagesFinalizedL1Block.getAsync();
84
+ if (!buffer) {
85
+ return undefined;
86
+ }
87
+ const reader = BufferReader.asReader(buffer);
88
+ return { l1BlockNumber: reader.readUInt256(), l1BlockHash: Buffer32.fromBuffer(reader.readBytes(Buffer32.SIZE)) };
89
+ }
90
+
91
+ /** Monotonically advances the persisted L1 finalized block for message sync. Never regresses. */
92
+ private async maybeAdvanceFinalizedL1Block(l1Block: L1BlockId): Promise<void> {
93
+ const existing = await this.getMessagesFinalizedL1Block();
94
+ if (existing && l1Block.l1BlockNumber <= existing.l1BlockNumber) {
95
+ return;
96
+ }
97
+ const buffer = serializeToBuffer([l1Block.l1BlockNumber, l1Block.l1BlockHash]);
98
+ await this.#messagesFinalizedL1Block.set(buffer);
99
+ }
100
+
74
101
  /**
75
102
  * Append L1 to L2 messages to the store.
76
103
  * Requires new messages to be in order and strictly after the last message added.
@@ -137,7 +164,7 @@ export class MessageStore {
137
164
  );
138
165
  }
139
166
 
140
- // Check the first message in a block has the correct index.
167
+ // Check the first message in a checkpoint has the correct index.
141
168
  if (
142
169
  (!lastMessage || message.checkpointNumber > lastMessage.checkpointNumber) &&
143
170
  message.index !== expectedStart
@@ -157,15 +184,6 @@ export class MessageStore {
157
184
  lastMessage = message;
158
185
  }
159
186
 
160
- // Update the L1 sync point to that of the last message added.
161
- const currentSyncPoint = await this.getSynchedL1Block();
162
- if (!currentSyncPoint || currentSyncPoint.l1BlockNumber < lastMessage!.l1BlockNumber) {
163
- await this.setSynchedL1Block({
164
- l1BlockNumber: lastMessage!.l1BlockNumber,
165
- l1BlockHash: lastMessage!.l1BlockHash,
166
- });
167
- }
168
-
169
187
  // Update total message count with the number of inserted messages.
170
188
  await this.increaseTotalMessageCount(messageCount);
171
189
  });
@@ -185,7 +203,39 @@ export class MessageStore {
185
203
  return msg ? deserializeInboxMessage(msg) : undefined;
186
204
  }
187
205
 
206
+ /** Returns the inbox tree-in-progress checkpoint number from L1, or undefined if not yet set. */
207
+ public getInboxTreeInProgress(): Promise<bigint | undefined> {
208
+ return this.#inboxTreeInProgress.getAsync();
209
+ }
210
+
211
+ /**
212
+ * Atomically updates the message sync state: the L1 sync point, the inbox tree-in-progress marker, and
213
+ * (optionally) the L1 finalized block as of this sync. The finalized block is advanced monotonically.
214
+ */
215
+ public setMessageSyncState(
216
+ l1Block: L1BlockId,
217
+ treeInProgress: bigint | undefined,
218
+ finalizedL1Block?: L1BlockId,
219
+ ): Promise<void> {
220
+ return this.db.transactionAsync(async () => {
221
+ await this.setSynchedL1Block(l1Block);
222
+ if (treeInProgress !== undefined) {
223
+ await this.#inboxTreeInProgress.set(treeInProgress);
224
+ } else {
225
+ await this.#inboxTreeInProgress.delete();
226
+ }
227
+ if (finalizedL1Block !== undefined) {
228
+ await this.maybeAdvanceFinalizedL1Block(finalizedL1Block);
229
+ }
230
+ });
231
+ }
232
+
188
233
  public async getL1ToL2Messages(checkpointNumber: CheckpointNumber): Promise<Fr[]> {
234
+ const treeInProgress = await this.#inboxTreeInProgress.getAsync();
235
+ if (treeInProgress !== undefined && BigInt(checkpointNumber) >= treeInProgress) {
236
+ throw new L1ToL2MessagesNotReadyError(checkpointNumber, treeInProgress);
237
+ }
238
+
189
239
  const messages: Fr[] = [];
190
240
 
191
241
  const [startIndex, endIndex] = InboxLeaf.indexRangeForCheckpoint(checkpointNumber);
@@ -8,7 +8,7 @@ export type InboxMessage = {
8
8
  index: bigint;
9
9
  leaf: Fr;
10
10
  checkpointNumber: CheckpointNumber;
11
- l1BlockNumber: bigint; // L1 block number - NOT Aztec L2
11
+ l1BlockNumber: bigint;
12
12
  l1BlockHash: Buffer32;
13
13
  rollingHash: Buffer16;
14
14
  };