@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,310 @@
1
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { createLogger } from '@aztec/foundation/log';
3
+ import { MAX_LOGS_PER_TAG } from '@aztec/stdlib/interfaces/api-limit';
4
+ import { decodeKeyTail, decodeValue, encodeKey, encodePublicPrefix, encodeValue, endOfTagRange, endOfTxRange, fieldHex, incKey, tagHexForLog } from './log_store_codec.js';
5
+ /**
6
+ * Indexes every emitted private and public log under a composite hex-string key
7
+ * `[contractAddress (public only)]-tag-blockNumber-txIndexWithinBlock-logIndexWithinTx`,
8
+ * where each numeric segment is zero-padded to 8 lowercase hex digits (4 bytes BE) and
9
+ * `contractAddress` / `tag` are the bare 64-hex-char field representations (no `0x` prefix). The
10
+ * fixed-width zero-padded hex segments sort lexicographically in the same order as the canonical
11
+ * `(contract, tag, blockNumber, txIndexWithinBlock, logIndexWithinTx)` tuple, so a single ordered
12
+ * range scan answers every {@link PrivateLogsQuery} / {@link PublicLogsQuery}.
13
+ *
14
+ * Per-block secondary indices (`#privateKeysByBlock`, `#publicKeysByBlock`) record the exact primary
15
+ * keys written for each block so {@link deleteLogs} can drop them on reorg without having to range
16
+ * scan by block (block isn't the leading key segment).
17
+ *
18
+ * Contract-class logs are no longer stored or served by the log store.
19
+ */ export class LogStore {
20
+ db;
21
+ blockStore;
22
+ genesisBlockHash;
23
+ /** Primary map: composite private key (tag + tail = 96 hex chars + separators) -> serialized {@link StoredLogValue}. */ #privateLogs;
24
+ /** Primary map: composite public key (contract + tag + tail) -> serialized {@link StoredLogValue}. */ #publicLogs;
25
+ /** Secondary deletion index: blockNumber -> the exact primary keys written for that block. */ #privateKeysByBlock;
26
+ #publicKeysByBlock;
27
+ #log;
28
+ /**
29
+ * @param genesisBlockHash - Hash of the synthetic genesis block. During early sync the PXE anchors to
30
+ * genesis and passes its hash as a query `referenceBlock`; since the archiver never indexes the
31
+ * genesis block, the store recognizes this hash directly and resolves it to the genesis block number
32
+ * rather than mistaking it for a reorg.
33
+ */ constructor(db, blockStore, genesisBlockHash){
34
+ this.db = db;
35
+ this.blockStore = blockStore;
36
+ this.genesisBlockHash = genesisBlockHash;
37
+ this.#log = createLogger('archiver:log_store');
38
+ this.#privateLogs = db.openMap('archiver_private_logs');
39
+ this.#publicLogs = db.openMap('archiver_public_logs');
40
+ this.#privateKeysByBlock = db.openMap('archiver_private_log_keys_by_block');
41
+ this.#publicKeysByBlock = db.openMap('archiver_public_log_keys_by_block');
42
+ }
43
+ /**
44
+ * Indexes every emitted private and public log from the given blocks. Wraps the write in a single
45
+ * `db.transactionAsync` so the primary entries and the per-block secondary indices stay consistent.
46
+ *
47
+ * A block is only ever added once; on reorg the archiver calls {@link deleteLogs} first, so we write
48
+ * the secondary index entries with a plain `set` (overwrite) rather than read-modify-append.
49
+ */ addLogs(blocks) {
50
+ return this.db.transactionAsync(async ()=>{
51
+ for (const block of blocks){
52
+ const blockHash = await block.hash();
53
+ const blockNumber = block.number;
54
+ const blockTimestamp = block.timestamp;
55
+ const privateKeys = [];
56
+ const privateValues = [];
57
+ const publicKeys = [];
58
+ const publicValues = [];
59
+ for(let txIndexWithinBlock = 0; txIndexWithinBlock < block.body.txEffects.length; txIndexWithinBlock++){
60
+ const txEffect = block.body.txEffects[txIndexWithinBlock];
61
+ const txHash = txEffect.txHash;
62
+ // Private and public log indices are counted independently per tx, each starting at 0.
63
+ let privateLogIndexWithinTx = 0;
64
+ let publicLogIndexWithinTx = 0;
65
+ for (const log of txEffect.privateLogs){
66
+ const tagHex = tagHexForLog(log.fields);
67
+ const key = encodeKey(tagHex, blockNumber, txIndexWithinBlock, privateLogIndexWithinTx);
68
+ const value = encodeValue({
69
+ txHash,
70
+ blockHash,
71
+ blockTimestamp,
72
+ logData: log.getEmittedFields()
73
+ });
74
+ privateKeys.push(key);
75
+ privateValues.push(value);
76
+ privateLogIndexWithinTx++;
77
+ }
78
+ for (const log of txEffect.publicLogs){
79
+ const contractHex = fieldHex(log.contractAddress);
80
+ const tagHex = tagHexForLog(log.fields);
81
+ const key = encodeKey(encodePublicPrefix(contractHex, tagHex), blockNumber, txIndexWithinBlock, publicLogIndexWithinTx);
82
+ const value = encodeValue({
83
+ txHash,
84
+ blockHash,
85
+ blockTimestamp,
86
+ logData: log.getEmittedFields()
87
+ });
88
+ publicKeys.push(key);
89
+ publicValues.push(value);
90
+ publicLogIndexWithinTx++;
91
+ }
92
+ }
93
+ for(let i = 0; i < privateKeys.length; i++){
94
+ await this.#privateLogs.set(privateKeys[i], privateValues[i]);
95
+ }
96
+ for(let i = 0; i < publicKeys.length; i++){
97
+ await this.#publicLogs.set(publicKeys[i], publicValues[i]);
98
+ }
99
+ await this.#privateKeysByBlock.set(blockNumber, privateKeys);
100
+ await this.#publicKeysByBlock.set(blockNumber, publicKeys);
101
+ this.#log.debug(`Indexed logs for block ${blockNumber}`, {
102
+ blockNumber,
103
+ privateCount: privateKeys.length,
104
+ publicCount: publicKeys.length
105
+ });
106
+ }
107
+ return true;
108
+ });
109
+ }
110
+ /**
111
+ * Deletes every log indexed under any of the given blocks. Secondary-index driven, so it doesn't
112
+ * have to range-scan the primary maps.
113
+ */ deleteLogs(blocks) {
114
+ return this.db.transactionAsync(async ()=>{
115
+ for (const block of blocks){
116
+ const blockNumber = block.number;
117
+ const [privateKeys, publicKeys] = await Promise.all([
118
+ this.#privateKeysByBlock.getAsync(blockNumber),
119
+ this.#publicKeysByBlock.getAsync(blockNumber)
120
+ ]);
121
+ if (privateKeys) {
122
+ for (const key of privateKeys){
123
+ await this.#privateLogs.delete(key);
124
+ }
125
+ await this.#privateKeysByBlock.delete(blockNumber);
126
+ }
127
+ if (publicKeys) {
128
+ for (const key of publicKeys){
129
+ await this.#publicLogs.delete(key);
130
+ }
131
+ await this.#publicKeysByBlock.delete(blockNumber);
132
+ }
133
+ }
134
+ return true;
135
+ });
136
+ }
137
+ /** Returns one inner array per element of `query.tags`, in input order. */ getPrivateLogsByTags(query) {
138
+ LogStore.#validateQuery(query);
139
+ return this.db.transactionAsync(()=>this.#runQuery(query, /* contractHex */ undefined));
140
+ }
141
+ /** Returns one inner array per element of `query.tags`, in input order. */ getPublicLogsByTags(query) {
142
+ LogStore.#validateQuery(query);
143
+ return this.db.transactionAsync(()=>this.#runQuery(query, fieldHex(query.contractAddress)));
144
+ }
145
+ static #validateQuery(query) {
146
+ if (query.txHash !== undefined && (query.fromBlock !== undefined || query.toBlock !== undefined)) {
147
+ throw new Error('`txHash` is mutually exclusive with `fromBlock`/`toBlock`');
148
+ }
149
+ }
150
+ async #runQuery(query, contractHex) {
151
+ const isPublic = contractHex !== undefined;
152
+ const tags = query.tags ?? [];
153
+ const primaryMap = isPublic ? this.#publicLogs : this.#privateLogs;
154
+ // referenceBlock reorg check, in-transaction, against the same db the log primary maps live on. The
155
+ // genesis block is a valid anchor during early sync but is synthetic and never indexed in the block
156
+ // store, so resolve it directly to the genesis block number rather than mistaking it for a reorg.
157
+ let referenceBlockNumber;
158
+ if (query.referenceBlock) {
159
+ if (query.referenceBlock.equals(this.genesisBlockHash)) {
160
+ referenceBlockNumber = INITIAL_L2_BLOCK_NUM - 1;
161
+ } else {
162
+ const refBlk = await this.blockStore.getBlockData({
163
+ hash: query.referenceBlock
164
+ });
165
+ if (!refBlk) {
166
+ throw new Error(`Reference block ${query.referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
167
+ }
168
+ referenceBlockNumber = refBlk.header.globalVariables.blockNumber;
169
+ }
170
+ }
171
+ // Compute the exclusive upper-block bound across `toBlock` and `referenceBlock`.
172
+ // `toBlock` is already exclusive; `referenceBlock` caps inclusively, so its exclusive form is +1.
173
+ let upperExclusive;
174
+ if (query.toBlock !== undefined) {
175
+ upperExclusive = query.toBlock;
176
+ }
177
+ if (referenceBlockNumber !== undefined) {
178
+ const refExclusive = referenceBlockNumber + 1;
179
+ upperExclusive = upperExclusive === undefined ? refExclusive : Math.min(upperExclusive, refExclusive);
180
+ }
181
+ // Resolve txHash -> (blockNumber, txIndexInBlock) once for the whole query.
182
+ let txLocation;
183
+ if (query.txHash) {
184
+ const loc = await this.blockStore.getTxLocation(query.txHash);
185
+ if (!loc) {
186
+ return tags.map(()=>[]);
187
+ }
188
+ txLocation = loc;
189
+ if (upperExclusive !== undefined && txLocation[0] >= upperExclusive) {
190
+ return tags.map(()=>[]);
191
+ }
192
+ }
193
+ const fromBlock = query.fromBlock ?? INITIAL_L2_BLOCK_NUM;
194
+ const includeEffects = query.includeEffects === true;
195
+ const perTagResults = [];
196
+ for (const tagEntry of tags){
197
+ const { tagHex, afterLog } = normalizeTagEntry(tagEntry);
198
+ const prefix = contractHex !== undefined ? encodePublicPrefix(contractHex, tagHex) : tagHex;
199
+ const end = txLocation ? endOfTxRange(prefix, txLocation[0], txLocation[1]) : endOfTagRange(prefix, upperExclusive);
200
+ let start;
201
+ if (afterLog) {
202
+ // Cursor wins as the start; `fromBlock` is ignored (fine if the cursor sits below it). The cursor
203
+ // carries `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`, which slot directly into the
204
+ // composite key — no tx-hash lookup needed.
205
+ start = incKey(encodeKey(prefix, afterLog.blockNumber, afterLog.txIndexWithinBlock, afterLog.logIndexWithinTx));
206
+ } else if (txLocation) {
207
+ start = encodeKey(prefix, txLocation[0], txLocation[1], 0);
208
+ } else {
209
+ start = encodeKey(prefix, fromBlock, 0, 0);
210
+ }
211
+ const limit = query.limitPerTag ?? MAX_LOGS_PER_TAG;
212
+ const out = [];
213
+ for await (const [rawKey, rawVal] of primaryMap.entriesAsync({
214
+ start,
215
+ end,
216
+ limit
217
+ })){
218
+ const tail = decodeKeyTail(rawKey);
219
+ const value = decodeValue(rawVal);
220
+ out.push({
221
+ logData: value.logData,
222
+ blockNumber: tail.blockNumber,
223
+ blockHash: value.blockHash,
224
+ blockTimestamp: value.blockTimestamp,
225
+ txHash: value.txHash,
226
+ txIndexWithinBlock: tail.txIndexWithinBlock,
227
+ logIndexWithinTx: tail.logIndexWithinTx
228
+ });
229
+ }
230
+ perTagResults.push(out);
231
+ }
232
+ if (includeEffects) {
233
+ // Dedupe by txHash across the entire page so a tx with many tagged logs costs one fetch.
234
+ const txHashByKey = new Map();
235
+ for (const arr of perTagResults){
236
+ for (const log of arr){
237
+ txHashByKey.set(log.txHash.toString(), log.txHash);
238
+ }
239
+ }
240
+ const uniqueTxs = Array.from(txHashByKey.values());
241
+ if (uniqueTxs.length > 0) {
242
+ const effects = await this.blockStore.getNoteHashesAndNullifiers(uniqueTxs);
243
+ const byTxHash = new Map();
244
+ uniqueTxs.forEach((tx, i)=>byTxHash.set(tx.toString(), effects[i]));
245
+ for(let i = 0; i < perTagResults.length; i++){
246
+ perTagResults[i] = perTagResults[i].map((log)=>{
247
+ const [noteHashes, nullifiers] = byTxHash.get(log.txHash.toString()) ?? [
248
+ [],
249
+ []
250
+ ];
251
+ return {
252
+ ...log,
253
+ noteHashes,
254
+ nullifiers
255
+ };
256
+ });
257
+ }
258
+ }
259
+ }
260
+ return perTagResults;
261
+ }
262
+ /**
263
+ * Reads back every private log indexed for the given block via the per-block secondary index. Order
264
+ * matches the canonical composite-key order (`tag`, `blockNumber`, `txIndexWithinBlock`,
265
+ * `logIndexWithinTx`). Used by the data-store-updater test suite to verify the indexed-vs-block-body
266
+ * counts without depending on the removed `getPublicLogs(LogFilter)` API.
267
+ */ getPrivateLogsForBlock(blockNumber) {
268
+ return this.db.transactionAsync(()=>this.#readBlockLogs(this.#privateKeysByBlock, this.#privateLogs, blockNumber));
269
+ }
270
+ /** {@inheritDoc LogStore.getPrivateLogsForBlock} */ getPublicLogsForBlock(blockNumber) {
271
+ return this.db.transactionAsync(()=>this.#readBlockLogs(this.#publicKeysByBlock, this.#publicLogs, blockNumber));
272
+ }
273
+ async #readBlockLogs(keysByBlock, primaryMap, blockNumber) {
274
+ const keys = await keysByBlock.getAsync(blockNumber);
275
+ if (!keys || keys.length === 0) {
276
+ return [];
277
+ }
278
+ const results = [];
279
+ for (const key of keys){
280
+ const raw = await primaryMap.getAsync(key);
281
+ if (!raw) {
282
+ continue;
283
+ }
284
+ const tail = decodeKeyTail(key);
285
+ const value = decodeValue(raw);
286
+ results.push({
287
+ logData: value.logData,
288
+ blockNumber: tail.blockNumber,
289
+ blockHash: value.blockHash,
290
+ blockTimestamp: value.blockTimestamp,
291
+ txHash: value.txHash,
292
+ txIndexWithinBlock: tail.txIndexWithinBlock,
293
+ logIndexWithinTx: tail.logIndexWithinTx
294
+ });
295
+ }
296
+ return results;
297
+ }
298
+ }
299
+ /** Pulls `{ tagHex, afterLog }` out of a {@link TagQuery}, normalizing the bare-tag form. */ function normalizeTagEntry(entry) {
300
+ if (typeof entry === 'object' && entry !== null && 'tag' in entry) {
301
+ return {
302
+ tagHex: fieldHex(entry.tag.value),
303
+ afterLog: entry.afterLog
304
+ };
305
+ }
306
+ return {
307
+ tagHex: fieldHex(entry.value),
308
+ afterLog: undefined
309
+ };
310
+ }
@@ -0,0 +1,78 @@
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
+ export declare const NUMERIC_HEX_LEN = 8;
6
+ export declare const SEP = "-";
7
+ /**
8
+ * Sentinel appended after a numeric hex segment to build an end bound strictly greater than any
9
+ * real key for that namespace. `'g'` sorts lexicographically after every hex digit (`0`-`9`, `a`-`f`),
10
+ * so `prefix + '-g'` is a clean exclusive upper bound.
11
+ */
12
+ export declare const HEX_SENTINEL = "g";
13
+ export type ParsedKeyTail = {
14
+ blockNumber: BlockNumber;
15
+ txIndexWithinBlock: number;
16
+ logIndexWithinTx: number;
17
+ };
18
+ /**
19
+ * Per-kind stored value layout (no msgpackr):
20
+ * txHash(32) ++ blockHash(32) ++ blockTimestamp(u64 BE = 8) ++ logDataLen(u32 BE = 4) ++ logData[i].toBuffer()...
21
+ * `blockNumber`, `txIndexWithinBlock`, and `logIndexWithinTx` are decoded from the composite key.
22
+ */
23
+ export type StoredLogValue = {
24
+ txHash: TxHash;
25
+ blockHash: BlockHash;
26
+ blockTimestamp: bigint;
27
+ logData: Fr[];
28
+ };
29
+ /** Returns the 64-char lowercase hex representation of a field, stripping the `0x` prefix. */
30
+ export declare function fieldHex(value: Fr | {
31
+ toString: () => string;
32
+ }): string;
33
+ /**
34
+ * Tag prefix for a log: the hex of its first field, or the empty string when the log carries no fields.
35
+ * A protocol-valid public log can have zero fields (e.g. a raw AVM `EMITPUBLICLOG` with `logSize = 0`),
36
+ * which has no tag to index by. Encoding it under the empty tag keeps it retrievable via the per-block
37
+ * read (and droppable on reorg) while never matching a real 64-hex-char tag query — instead of reading
38
+ * `fields[0]` off an empty array and aborting the whole block-ingestion transaction.
39
+ */
40
+ export declare function tagHexForLog(fields: Fr[]): string;
41
+ /** Encodes a number as 8-char zero-padded lowercase hex (matches a u32 big-endian byte buffer's lex order). */
42
+ export declare function u32Hex(n: number): string;
43
+ /**
44
+ * Encodes the composite primary key as `prefix-block-txIdx-logIdx` where `prefix` is the leading
45
+ * segment (`tag` for private; `contract-tag` for public) and the trailing triple is fixed-width
46
+ * 8-char zero-padded hex so byte-order matches `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`.
47
+ */
48
+ export declare function encodeKey(prefix: string, blockNumber: number, txIndex: number, logIndex: number): string;
49
+ /**
50
+ * Decodes the trailing `(blockNumber, txIndexWithinBlock, logIndexWithinTx)` triple from a composite
51
+ * key. The leading prefix segments are ignored — we only ever read them off the input query, never
52
+ * back off the key.
53
+ */
54
+ export declare function decodeKeyTail(key: string): ParsedKeyTail;
55
+ /**
56
+ * Exclusive end bound for a `(contract, tag)`-prefix scan. With an `upperBlockExclusive` we cut at
57
+ * `(prefix, upper, 0, 0)`. With no bound we use `prefix + '-' + HEX_SENTINEL`, which sorts strictly
58
+ * after every real key under `prefix` (`g` is greater than any hex digit).
59
+ */
60
+ export declare function endOfTagRange(prefix: string, upperBlockExclusive: number | undefined): string;
61
+ /**
62
+ * Exclusive end bound for a tx-strict scan: every key strictly inside `(prefix, txBlk, txIdx, *)`.
63
+ * `prefix-block-txIdx-` followed by the hex sentinel is the first key past every real logIndex for
64
+ * this tx and strictly less than the next tx's first key.
65
+ */
66
+ export declare function endOfTxRange(prefix: string, txBlk: number, txIdx: number): string;
67
+ /**
68
+ * Returns the smallest string strictly greater than a fully-encoded composite key. The encoded key
69
+ * ends in a hex digit, and `'g'` sorts strictly after any hex digit, so appending `'g'` is the
70
+ * smallest possible successor in our key alphabet. Used to turn an inclusive cursor into an
71
+ * exclusive `start`.
72
+ */
73
+ export declare function incKey(key: string): string;
74
+ export declare function encodeValue(value: StoredLogValue): Buffer;
75
+ export declare function decodeValue(buffer: Buffer | Uint8Array): StoredLogValue;
76
+ /** Encodes the public-log key prefix as `contractHex-tagHex`. */
77
+ export declare function encodePublicPrefix(contractHex: string, tagHex: string): string;
78
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nX3N0b3JlX2NvZGVjLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc3RvcmUvbG9nX3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Aa,CAAC,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAK7F;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAEjF;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE1C;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,CAQzD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,GAAG,cAAc,CAiBvE;AAED,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAE9E"}
@@ -0,0 +1,110 @@
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
+ export const NUMERIC_HEX_LEN = 8;
6
+ export const SEP = '-';
7
+ /**
8
+ * Sentinel appended after a numeric hex segment to build an end bound strictly greater than any
9
+ * real key for that namespace. `'g'` sorts lexicographically after every hex digit (`0`-`9`, `a`-`f`),
10
+ * so `prefix + '-g'` is a clean exclusive upper bound.
11
+ */ export const HEX_SENTINEL = 'g';
12
+ /** Returns the 64-char lowercase hex representation of a field, stripping the `0x` prefix. */ export function fieldHex(value) {
13
+ // Fr.toString() and AztecAddress.toString() both return `0x` + 64 lowercase hex chars.
14
+ return value.toString().slice(2);
15
+ }
16
+ /**
17
+ * Tag prefix for a log: the hex of its first field, or the empty string when the log carries no fields.
18
+ * A protocol-valid public log can have zero fields (e.g. a raw AVM `EMITPUBLICLOG` with `logSize = 0`),
19
+ * which has no tag to index by. Encoding it under the empty tag keeps it retrievable via the per-block
20
+ * read (and droppable on reorg) while never matching a real 64-hex-char tag query — instead of reading
21
+ * `fields[0]` off an empty array and aborting the whole block-ingestion transaction.
22
+ */ export function tagHexForLog(fields) {
23
+ return fields.length > 0 ? fieldHex(fields[0]) : '';
24
+ }
25
+ /** Encodes a number as 8-char zero-padded lowercase hex (matches a u32 big-endian byte buffer's lex order). */ export function u32Hex(n) {
26
+ return n.toString(16).padStart(NUMERIC_HEX_LEN, '0');
27
+ }
28
+ /**
29
+ * Encodes the composite primary key as `prefix-block-txIdx-logIdx` where `prefix` is the leading
30
+ * segment (`tag` for private; `contract-tag` for public) and the trailing triple is fixed-width
31
+ * 8-char zero-padded hex so byte-order matches `(blockNumber, txIndexWithinBlock, logIndexWithinTx)`.
32
+ */ export function encodeKey(prefix, blockNumber, txIndex, logIndex) {
33
+ return `${prefix}${SEP}${u32Hex(blockNumber)}${SEP}${u32Hex(txIndex)}${SEP}${u32Hex(logIndex)}`;
34
+ }
35
+ /**
36
+ * Decodes the trailing `(blockNumber, txIndexWithinBlock, logIndexWithinTx)` triple from a composite
37
+ * key. The leading prefix segments are ignored — we only ever read them off the input query, never
38
+ * back off the key.
39
+ */ export function decodeKeyTail(key) {
40
+ const parts = key.split(SEP);
41
+ const len = parts.length;
42
+ return {
43
+ blockNumber: BlockNumber(parseInt(parts[len - 3], 16)),
44
+ txIndexWithinBlock: parseInt(parts[len - 2], 16),
45
+ logIndexWithinTx: parseInt(parts[len - 1], 16)
46
+ };
47
+ }
48
+ /**
49
+ * Exclusive end bound for a `(contract, tag)`-prefix scan. With an `upperBlockExclusive` we cut at
50
+ * `(prefix, upper, 0, 0)`. With no bound we use `prefix + '-' + HEX_SENTINEL`, which sorts strictly
51
+ * after every real key under `prefix` (`g` is greater than any hex digit).
52
+ */ export function endOfTagRange(prefix, upperBlockExclusive) {
53
+ if (upperBlockExclusive === undefined) {
54
+ return `${prefix}${SEP}${HEX_SENTINEL}`;
55
+ }
56
+ return encodeKey(prefix, upperBlockExclusive, 0, 0);
57
+ }
58
+ /**
59
+ * Exclusive end bound for a tx-strict scan: every key strictly inside `(prefix, txBlk, txIdx, *)`.
60
+ * `prefix-block-txIdx-` followed by the hex sentinel is the first key past every real logIndex for
61
+ * this tx and strictly less than the next tx's first key.
62
+ */ export function endOfTxRange(prefix, txBlk, txIdx) {
63
+ return `${prefix}${SEP}${u32Hex(txBlk)}${SEP}${u32Hex(txIdx)}${SEP}${HEX_SENTINEL}`;
64
+ }
65
+ /**
66
+ * Returns the smallest string strictly greater than a fully-encoded composite key. The encoded key
67
+ * ends in a hex digit, and `'g'` sorts strictly after any hex digit, so appending `'g'` is the
68
+ * smallest possible successor in our key alphabet. Used to turn an inclusive cursor into an
69
+ * exclusive `start`.
70
+ */ export function incKey(key) {
71
+ return key + HEX_SENTINEL;
72
+ }
73
+ export function encodeValue(value) {
74
+ const head = Buffer.allocUnsafe(32 + 32 + 8 + 4);
75
+ value.txHash.toBuffer().copy(head, 0);
76
+ value.blockHash.toBuffer().copy(head, 32);
77
+ head.writeBigUInt64BE(value.blockTimestamp, 64);
78
+ head.writeUInt32BE(value.logData.length, 72);
79
+ const fieldBufs = value.logData.map((f)=>f.toBuffer());
80
+ return Buffer.concat([
81
+ head,
82
+ ...fieldBufs
83
+ ]);
84
+ }
85
+ export function decodeValue(buffer) {
86
+ const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
87
+ let off = 0;
88
+ const txHash = TxHash.fromBuffer(buf.subarray(off, off + 32));
89
+ off += 32;
90
+ const blockHash = BlockHash.fromBuffer(buf.subarray(off, off + 32));
91
+ off += 32;
92
+ const blockTimestamp = buf.readBigUInt64BE(off);
93
+ off += 8;
94
+ const logDataLen = buf.readUInt32BE(off);
95
+ off += 4;
96
+ const logData = new Array(logDataLen);
97
+ for(let i = 0; i < logDataLen; i++){
98
+ logData[i] = Fr.fromBuffer(buf.subarray(off, off + 32));
99
+ off += 32;
100
+ }
101
+ return {
102
+ txHash,
103
+ blockHash,
104
+ blockTimestamp,
105
+ logData
106
+ };
107
+ }
108
+ /** Encodes the public-log key prefix as `contractHex-tagHex`. */ export function encodePublicPrefix(contractHex, tagHex) {
109
+ return `${contractHex}${SEP}${tagHex}`;
110
+ }
@@ -0,0 +1,50 @@
1
+ import type { L1BlockId } from '@aztec/ethereum/l1-types';
2
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
3
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
+ import { type AztecAsyncKVStore, type CustomRange } from '@aztec/kv-store';
5
+ import { type InboxMessage } from '../structs/inbox_message.js';
6
+ export declare class MessageStoreError extends Error {
7
+ readonly inboxMessage: InboxMessage;
8
+ constructor(message: string, inboxMessage: InboxMessage);
9
+ }
10
+ export declare class MessageStore {
11
+ #private;
12
+ private db;
13
+ constructor(db: AztecAsyncKVStore);
14
+ getTotalL1ToL2MessageCount(): Promise<bigint>;
15
+ /** Gets the last L1 block synced. */
16
+ getSynchedL1Block(): Promise<L1BlockId | undefined>;
17
+ /** Sets the last L1 block synced */
18
+ setSynchedL1Block(l1Block: L1BlockId): Promise<void>;
19
+ /** Gets the L1 finalized block as of the last successful message sync. */
20
+ getMessagesFinalizedL1Block(): Promise<L1BlockId | undefined>;
21
+ private maybeAdvanceFinalizedL1Block;
22
+ /**
23
+ * Append L1 to L2 messages to the store.
24
+ * Requires new messages to be in order and strictly after the last message added.
25
+ * Throws if out of order messages are added or if the rolling hash is invalid.
26
+ */
27
+ addL1ToL2Messages(messages: InboxMessage[]): Promise<void>;
28
+ /**
29
+ * Gets the L1 to L2 message index in the L1 to L2 message tree.
30
+ * @param l1ToL2Message - The L1 to L2 message.
31
+ * @returns The index of the L1 to L2 message in the L1 to L2 message tree (undefined if not found).
32
+ */
33
+ getL1ToL2MessageIndex(l1ToL2Message: Fr): Promise<bigint | undefined>;
34
+ getLastMessage(): Promise<InboxMessage | undefined>;
35
+ /** Returns the inbox tree-in-progress checkpoint number from L1, or undefined if not yet set. */
36
+ getInboxTreeInProgress(): Promise<bigint | undefined>;
37
+ /**
38
+ * Atomically updates the message sync state: the L1 sync point, the inbox tree-in-progress marker, and
39
+ * (optionally) the L1 finalized block as of this sync. The finalized block is advanced monotonically.
40
+ */
41
+ setMessageSyncState(l1Block: L1BlockId, treeInProgress: bigint | undefined, finalizedL1Block?: L1BlockId): Promise<void>;
42
+ getL1ToL2Messages(checkpointNumber: CheckpointNumber): Promise<Fr[]>;
43
+ iterateL1ToL2Messages(range?: CustomRange<bigint>): AsyncIterableIterator<InboxMessage>;
44
+ removeL1ToL2Messages(startIndex: bigint): Promise<void>;
45
+ rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber: CheckpointNumber): Promise<void>;
46
+ private indexToKey;
47
+ private leafToIndexKey;
48
+ private increaseTotalMessageCount;
49
+ }
50
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWVzc2FnZV9zdG9yZS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL3N0b3JlL21lc3NhZ2Vfc3RvcmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLEVBQUUsU0FBUyxFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFDMUQsT0FBTyxFQUFFLGdCQUFnQixFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFFbkUsT0FBTyxFQUFFLEVBQUUsRUFBRSxNQUFNLGdDQUFnQyxDQUFDO0FBSXBELE9BQU8sRUFDTCxLQUFLLGlCQUFpQixFQUd0QixLQUFLLFdBQVcsRUFFakIsTUFBTSxpQkFBaUIsQ0FBQztBQUl6QixPQUFPLEVBQ0wsS0FBSyxZQUFZLEVBSWxCLE1BQU0sNkJBQTZCLENBQUM7QUFFckMscUJBQWEsaUJBQWtCLFNBQVEsS0FBSzthQUd4QixZQUFZLEVBQUUsWUFBWTtJQUY1QyxZQUNFLE9BQU8sRUFBRSxNQUFNLEVBQ0Ms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