@aztec/archiver 0.0.1-commit.d431d1c → 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 (138) hide show
  1. package/README.md +28 -11
  2. package/dest/archiver.d.ts +80 -21
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +347 -167
  5. package/dest/config.d.ts +7 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +38 -14
  8. package/dest/errors.d.ts +60 -9
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -13
  11. package/dest/factory.d.ts +13 -6
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +59 -39
  14. package/dest/index.d.ts +12 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +11 -2
  17. package/dest/l1/bin/retrieve-calldata.js +35 -32
  18. package/dest/l1/calldata_retriever.d.ts +81 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +202 -260
  21. package/dest/l1/data_retrieval.d.ts +32 -18
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +45 -50
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/trace_tx.d.ts +12 -66
  28. package/dest/l1/trace_tx.d.ts.map +1 -1
  29. package/dest/l1/validate_historical_logs.d.ts +23 -0
  30. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  31. package/dest/l1/validate_historical_logs.js +108 -0
  32. package/dest/l1/validate_trace.d.ts +6 -3
  33. package/dest/l1/validate_trace.d.ts.map +1 -1
  34. package/dest/l1/validate_trace.js +13 -9
  35. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  36. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  37. package/dest/modules/contract_data_source_adapter.js +32 -0
  38. package/dest/modules/data_source_base.d.ts +75 -48
  39. package/dest/modules/data_source_base.d.ts.map +1 -1
  40. package/dest/modules/data_source_base.js +251 -220
  41. package/dest/modules/data_store_updater.d.ts +65 -29
  42. package/dest/modules/data_store_updater.d.ts.map +1 -1
  43. package/dest/modules/data_store_updater.js +242 -153
  44. package/dest/modules/instrumentation.d.ts +30 -4
  45. package/dest/modules/instrumentation.d.ts.map +1 -1
  46. package/dest/modules/instrumentation.js +83 -20
  47. package/dest/modules/l1_synchronizer.d.ts +16 -14
  48. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  49. package/dest/modules/l1_synchronizer.js +493 -225
  50. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  51. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  52. package/dest/modules/outbox_trees_resolver.js +162 -0
  53. package/dest/modules/validation.d.ts +30 -7
  54. package/dest/modules/validation.d.ts.map +1 -1
  55. package/dest/modules/validation.js +35 -17
  56. package/dest/store/block_store.d.ts +200 -75
  57. package/dest/store/block_store.d.ts.map +1 -1
  58. package/dest/store/block_store.js +802 -276
  59. package/dest/store/contract_class_store.d.ts +17 -4
  60. package/dest/store/contract_class_store.d.ts.map +1 -1
  61. package/dest/store/contract_class_store.js +51 -73
  62. package/dest/store/contract_instance_store.d.ts +28 -1
  63. package/dest/store/contract_instance_store.d.ts.map +1 -1
  64. package/dest/store/contract_instance_store.js +54 -2
  65. package/dest/store/data_stores.d.ts +68 -0
  66. package/dest/store/data_stores.d.ts.map +1 -0
  67. package/dest/store/data_stores.js +54 -0
  68. package/dest/store/function_names_cache.d.ts +17 -0
  69. package/dest/store/function_names_cache.d.ts.map +1 -0
  70. package/dest/store/function_names_cache.js +30 -0
  71. package/dest/store/l2_tips_cache.d.ts +25 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +26 -0
  74. package/dest/store/log_store.d.ts +42 -37
  75. package/dest/store/log_store.d.ts.map +1 -1
  76. package/dest/store/log_store.js +262 -388
  77. package/dest/store/log_store_codec.d.ts +78 -0
  78. package/dest/store/log_store_codec.d.ts.map +1 -0
  79. package/dest/store/log_store_codec.js +110 -0
  80. package/dest/store/message_store.d.ts +11 -1
  81. package/dest/store/message_store.d.ts.map +1 -1
  82. package/dest/store/message_store.js +51 -9
  83. package/dest/test/fake_l1_state.d.ts +28 -4
  84. package/dest/test/fake_l1_state.d.ts.map +1 -1
  85. package/dest/test/fake_l1_state.js +166 -32
  86. package/dest/test/index.js +3 -1
  87. package/dest/test/mock_archiver.d.ts +1 -1
  88. package/dest/test/mock_archiver.d.ts.map +1 -1
  89. package/dest/test/mock_archiver.js +3 -2
  90. package/dest/test/mock_l2_block_source.d.ts +65 -51
  91. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  92. package/dest/test/mock_l2_block_source.js +309 -215
  93. package/dest/test/mock_structs.d.ts +6 -2
  94. package/dest/test/mock_structs.d.ts.map +1 -1
  95. package/dest/test/mock_structs.js +26 -12
  96. package/dest/test/noop_l1_archiver.d.ts +34 -0
  97. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  98. package/dest/test/noop_l1_archiver.js +88 -0
  99. package/package.json +15 -14
  100. package/src/archiver.ts +458 -198
  101. package/src/config.ts +43 -13
  102. package/src/errors.ts +134 -21
  103. package/src/factory.ts +87 -36
  104. package/src/index.ts +19 -2
  105. package/src/l1/README.md +25 -68
  106. package/src/l1/bin/retrieve-calldata.ts +45 -33
  107. package/src/l1/calldata_retriever.ts +267 -379
  108. package/src/l1/data_retrieval.ts +70 -74
  109. package/src/l1/spire_proposer.ts +7 -15
  110. package/src/l1/validate_historical_logs.ts +140 -0
  111. package/src/l1/validate_trace.ts +24 -6
  112. package/src/modules/contract_data_source_adapter.ts +46 -0
  113. package/src/modules/data_source_base.ts +336 -288
  114. package/src/modules/data_store_updater.ts +287 -187
  115. package/src/modules/instrumentation.ts +86 -21
  116. package/src/modules/l1_synchronizer.ts +667 -278
  117. package/src/modules/outbox_trees_resolver.ts +199 -0
  118. package/src/modules/validation.ts +80 -23
  119. package/src/store/block_store.ts +984 -352
  120. package/src/store/contract_class_store.ts +57 -107
  121. package/src/store/contract_instance_store.ts +68 -5
  122. package/src/store/data_stores.ts +104 -0
  123. package/src/store/function_names_cache.ts +37 -0
  124. package/src/store/l2_tips_cache.ts +35 -0
  125. package/src/store/log_store.ts +305 -500
  126. package/src/store/log_store_codec.ts +143 -0
  127. package/src/store/message_store.ts +60 -10
  128. package/src/structs/inbox_message.ts +1 -1
  129. package/src/test/fake_l1_state.ts +215 -44
  130. package/src/test/index.ts +3 -0
  131. package/src/test/mock_archiver.ts +3 -2
  132. package/src/test/mock_l2_block_source.ts +381 -246
  133. package/src/test/mock_structs.ts +50 -17
  134. package/src/test/noop_l1_archiver.ts +158 -0
  135. package/dest/store/kv_archiver_store.d.ts +0 -336
  136. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  137. package/dest/store/kv_archiver_store.js +0 -443
  138. package/src/store/kv_archiver_store.ts +0 -631
@@ -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
+ }
@@ -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
  };