@aztec/txe 0.0.1-commit.fcb71a6 → 0.0.1-commit.fffb133c

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 (52) hide show
  1. package/dest/oracle/interfaces.d.ts +2 -2
  2. package/dest/oracle/interfaces.d.ts.map +1 -1
  3. package/dest/oracle/txe_oracle_public_context.d.ts +2 -2
  4. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  5. package/dest/oracle/txe_oracle_public_context.js +3 -2
  6. package/dest/oracle/txe_oracle_top_level_context.d.ts +3 -2
  7. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  8. package/dest/oracle/txe_oracle_top_level_context.js +22 -16
  9. package/dest/rpc_translator.d.ts +15 -9
  10. package/dest/rpc_translator.d.ts.map +1 -1
  11. package/dest/rpc_translator.js +49 -35
  12. package/dest/state_machine/archiver.d.ts +20 -67
  13. package/dest/state_machine/archiver.d.ts.map +1 -1
  14. package/dest/state_machine/archiver.js +57 -178
  15. package/dest/state_machine/dummy_p2p_client.d.ts +8 -7
  16. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  17. package/dest/state_machine/dummy_p2p_client.js +13 -10
  18. package/dest/state_machine/global_variable_builder.d.ts +2 -2
  19. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  20. package/dest/state_machine/global_variable_builder.js +1 -1
  21. package/dest/state_machine/index.d.ts +1 -1
  22. package/dest/state_machine/index.d.ts.map +1 -1
  23. package/dest/state_machine/index.js +22 -4
  24. package/dest/state_machine/mock_epoch_cache.d.ts +7 -6
  25. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  26. package/dest/state_machine/mock_epoch_cache.js +10 -7
  27. package/dest/state_machine/synchronizer.d.ts +3 -3
  28. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  29. package/dest/txe_session.d.ts +5 -3
  30. package/dest/txe_session.d.ts.map +1 -1
  31. package/dest/txe_session.js +29 -13
  32. package/dest/util/encoding.d.ts +17 -17
  33. package/dest/utils/block_creation.d.ts +4 -4
  34. package/dest/utils/block_creation.d.ts.map +1 -1
  35. package/dest/utils/block_creation.js +16 -5
  36. package/dest/utils/tx_effect_creation.d.ts +2 -3
  37. package/dest/utils/tx_effect_creation.d.ts.map +1 -1
  38. package/dest/utils/tx_effect_creation.js +3 -6
  39. package/package.json +16 -16
  40. package/src/oracle/interfaces.ts +1 -1
  41. package/src/oracle/txe_oracle_public_context.ts +3 -3
  42. package/src/oracle/txe_oracle_top_level_context.ts +26 -14
  43. package/src/rpc_translator.ts +53 -45
  44. package/src/state_machine/archiver.ts +52 -220
  45. package/src/state_machine/dummy_p2p_client.ts +18 -13
  46. package/src/state_machine/global_variable_builder.ts +1 -1
  47. package/src/state_machine/index.ts +26 -4
  48. package/src/state_machine/mock_epoch_cache.ts +10 -11
  49. package/src/state_machine/synchronizer.ts +2 -2
  50. package/src/txe_session.ts +31 -8
  51. package/src/utils/block_creation.ts +17 -16
  52. package/src/utils/tx_effect_creation.ts +3 -11
@@ -22,6 +22,7 @@ import {
22
22
  SenderAddressBookStore,
23
23
  SenderTaggingStore,
24
24
  enrichPublicSimulationError,
25
+ syncState,
25
26
  } from '@aztec/pxe/server';
26
27
  import {
27
28
  ExecutionNoteCache,
@@ -106,6 +107,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
106
107
  private senderAddressBookStore: SenderAddressBookStore,
107
108
  private capsuleStore: CapsuleStore,
108
109
  private privateEventStore: PrivateEventStore,
110
+ private jobId: string,
109
111
  private nextBlockTimestamp: bigint,
110
112
  private version: Fr,
111
113
  private chainId: Fr,
@@ -156,7 +158,8 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
156
158
  }
157
159
 
158
160
  async txeGetLastTxEffects() {
159
- const block = await this.stateMachine.archiver.getL2Block('latest');
161
+ const latestBlockNumber = await this.stateMachine.archiver.getBlockNumber();
162
+ const block = await this.stateMachine.archiver.getBlock(latestBlockNumber);
160
163
 
161
164
  if (block!.body.txEffects.length != 1) {
162
165
  // Note that calls like env.mine() will result in blocks with no transactions, hitting this
@@ -299,7 +302,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
299
302
  await this.executeUtilityCall(call);
300
303
  };
301
304
 
302
- await this.contractStore.syncPrivateState(targetContractAddress, functionSelector, utilityExecutor);
305
+ await syncState(targetContractAddress, this.contractStore, functionSelector, utilityExecutor);
303
306
 
304
307
  const blockNumber = await this.txeGetNextBlockNumber();
305
308
 
@@ -315,6 +318,11 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
315
318
 
316
319
  const protocolNullifier = await computeProtocolNullifier(getSingleTxBlockRequestHash(blockNumber));
317
320
  const noteCache = new ExecutionNoteCache(protocolNullifier);
321
+ // In production, the account contract sets the min revertible counter before calling the app function.
322
+ // Since TXE bypasses the account contract, we simulate this by setting minRevertibleSideEffectCounter to 1,
323
+ // marking all side effects as revertible.
324
+ const minRevertibleSideEffectCounter = 1;
325
+ await noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter);
318
326
  const taggingIndexCache = new ExecutionTaggingIndexCache();
319
327
 
320
328
  const simulator = new WASMSimulator();
@@ -344,8 +352,9 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
344
352
  this.senderAddressBookStore,
345
353
  this.capsuleStore,
346
354
  this.privateEventStore,
347
- 0,
348
- 1,
355
+ this.jobId,
356
+ 0, // totalPublicArgsCount
357
+ minRevertibleSideEffectCounter, // (start) sideEffectCounter
349
358
  undefined, // log
350
359
  undefined, // scopes
351
360
  /**
@@ -381,19 +390,21 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
381
390
  }),
382
391
  );
383
392
 
384
- // TXE's top level context does not track side effect counters, and as such, minRevertibleSideEffectCounter is always 0.
385
- // This has the unfortunate consequence of always producing revertible nullifiers, which means we
386
- // must set the firstNullifierHint to Fr.ZERO so the txRequestHash is always used as nonce generator
387
- result = new PrivateExecutionResult(executionResult, Fr.ZERO, publicFunctionsCalldata);
393
+ noteCache.finish();
394
+ const nonceGenerator = noteCache.getNonceGenerator();
395
+ result = new PrivateExecutionResult(executionResult, nonceGenerator, publicFunctionsCalldata);
388
396
  } catch (err) {
389
397
  throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during private execution'));
390
398
  }
391
399
 
392
- // According to the protocol rules, the nonce generator for the note hashes
393
- // can either be the first nullifier in the tx or the hash of the initial tx request
394
- // if there are none.
395
- const nonceGenerator = result.firstNullifier.equals(Fr.ZERO) ? protocolNullifier : result.firstNullifier;
396
- const { publicInputs } = await generateSimulatedProvingResult(result, nonceGenerator, this.contractStore);
400
+ // According to the protocol rules, there must be at least one nullifier in the tx. The first nullifier is used as
401
+ // the nonce generator for the note hashes.
402
+ // We pass the non-zero minRevertibleSideEffectCounter to make sure the side effects are split correctly.
403
+ const { publicInputs } = await generateSimulatedProvingResult(
404
+ result,
405
+ this.contractStore,
406
+ minRevertibleSideEffectCounter,
407
+ );
397
408
 
398
409
  const globals = makeGlobalVariables();
399
410
  globals.blockNumber = blockNumber;
@@ -635,7 +646,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
635
646
  }
636
647
 
637
648
  // Sync notes before executing utility function to discover notes from previous transactions
638
- await this.contractStore.syncPrivateState(targetContractAddress, functionSelector, async call => {
649
+ await syncState(targetContractAddress, this.contractStore, functionSelector, async call => {
639
650
  await this.executeUtilityCall(call);
640
651
  });
641
652
 
@@ -681,6 +692,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl
681
692
  this.senderAddressBookStore,
682
693
  this.capsuleStore,
683
694
  this.privateEventStore,
695
+ this.jobId,
684
696
  );
685
697
  const acirExecutionResult = await new WASMSimulator()
686
698
  .executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback())
@@ -6,11 +6,11 @@ import {
6
6
  type IMiscOracle,
7
7
  type IPrivateExecutionOracle,
8
8
  type IUtilityExecutionOracle,
9
- packAsRetrievedNote,
9
+ packAsHintedNote,
10
10
  } from '@aztec/pxe/simulator';
11
11
  import { type ContractArtifact, EventSelector, FunctionSelector, NoteSelector } from '@aztec/stdlib/abi';
12
12
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
13
- import { MerkleTreeId } from '@aztec/stdlib/trees';
13
+ import { L2BlockHash } from '@aztec/stdlib/block';
14
14
 
15
15
  import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
16
16
  import type { TXESessionStateHandler } from './txe_session.js';
@@ -346,34 +346,34 @@ export class RPCTranslator {
346
346
  }
347
347
 
348
348
  async utilityStorageRead(
349
+ foreignBlockHash: ForeignCallSingle,
349
350
  foreignContractAddress: ForeignCallSingle,
350
351
  foreignStartStorageSlot: ForeignCallSingle,
351
- foreignBlockNumber: ForeignCallSingle,
352
352
  foreignNumberOfElements: ForeignCallSingle,
353
353
  ) {
354
+ const blockHash = L2BlockHash.fromString(foreignBlockHash);
354
355
  const contractAddress = addressFromSingle(foreignContractAddress);
355
356
  const startStorageSlot = fromSingle(foreignStartStorageSlot);
356
- const blockNumber = BlockNumber(fromSingle(foreignBlockNumber).toNumber());
357
357
  const numberOfElements = fromSingle(foreignNumberOfElements).toNumber();
358
358
 
359
359
  const values = await this.handlerAsUtility().utilityStorageRead(
360
+ blockHash,
360
361
  contractAddress,
361
362
  startStorageSlot,
362
- blockNumber,
363
363
  numberOfElements,
364
364
  );
365
365
 
366
366
  return toForeignCallResult([toArray(values)]);
367
367
  }
368
368
 
369
- async utilityGetPublicDataWitness(foreignBlockNumber: ForeignCallSingle, foreignLeafSlot: ForeignCallSingle) {
370
- const blockNumber = BlockNumber(fromSingle(foreignBlockNumber).toNumber());
369
+ async utilityGetPublicDataWitness(foreignBlockHash: ForeignCallSingle, foreignLeafSlot: ForeignCallSingle) {
370
+ const blockHash = L2BlockHash.fromString(foreignBlockHash);
371
371
  const leafSlot = fromSingle(foreignLeafSlot);
372
372
 
373
- const witness = await this.handlerAsUtility().utilityGetPublicDataWitness(blockNumber, leafSlot);
373
+ const witness = await this.handlerAsUtility().utilityGetPublicDataWitness(blockHash, leafSlot);
374
374
 
375
375
  if (!witness) {
376
- throw new Error(`Public data witness not found for slot ${leafSlot} at block ${blockNumber}.`);
376
+ throw new Error(`Public data witness not found for slot ${leafSlot} at block ${blockHash.toString()}.`);
377
377
  }
378
378
  return toForeignCallResult(witness.toNoirRepresentation());
379
379
  }
@@ -396,7 +396,7 @@ export class RPCTranslator {
396
396
  foreignOffset: ForeignCallSingle,
397
397
  foreignStatus: ForeignCallSingle,
398
398
  foreignMaxNotes: ForeignCallSingle,
399
- foreignPackedRetrievedNoteLength: ForeignCallSingle,
399
+ foreignPackedHintedNoteLength: ForeignCallSingle,
400
400
  ) {
401
401
  // Parse Option<AztecAddress>: ownerIsSome is 0 for None, 1 for Some
402
402
  const owner = fromSingle(foreignOwnerIsSome).toBool()
@@ -417,7 +417,7 @@ export class RPCTranslator {
417
417
  const offset = fromSingle(foreignOffset).toNumber();
418
418
  const status = fromSingle(foreignStatus).toNumber();
419
419
  const maxNotes = fromSingle(foreignMaxNotes).toNumber();
420
- const packedRetrievedNoteLength = fromSingle(foreignPackedRetrievedNoteLength).toNumber();
420
+ const packedHintedNoteLength = fromSingle(foreignPackedHintedNoteLength).toNumber();
421
421
 
422
422
  const noteDatas = await this.handlerAsUtility().utilityGetNotes(
423
423
  owner,
@@ -438,13 +438,13 @@ export class RPCTranslator {
438
438
  );
439
439
 
440
440
  const returnDataAsArrayOfArrays = noteDatas.map(noteData =>
441
- packAsRetrievedNote({
441
+ packAsHintedNote({
442
442
  contractAddress: noteData.contractAddress,
443
443
  owner: noteData.owner,
444
444
  randomness: noteData.randomness,
445
445
  storageSlot: noteData.storageSlot,
446
446
  noteNonce: noteData.noteNonce,
447
- index: noteData.index,
447
+ isPending: noteData.isPending,
448
448
  note: noteData.note,
449
449
  }),
450
450
  );
@@ -456,11 +456,7 @@ export class RPCTranslator {
456
456
 
457
457
  // At last we convert the array of arrays to a bounded vec of arrays
458
458
  return toForeignCallResult(
459
- arrayOfArraysToBoundedVecOfArrays(
460
- returnDataAsArrayOfForeignCallSingleArrays,
461
- maxNotes,
462
- packedRetrievedNoteLength,
463
- ),
459
+ arrayOfArraysToBoundedVecOfArrays(returnDataAsArrayOfForeignCallSingleArrays, maxNotes, packedHintedNoteLength),
464
460
  );
465
461
  }
466
462
 
@@ -516,6 +512,15 @@ export class RPCTranslator {
516
512
  return toForeignCallResult([]);
517
513
  }
518
514
 
515
+ async privateIsNullifierPending(foreignInnerNullifier: ForeignCallSingle, foreignContractAddress: ForeignCallSingle) {
516
+ const innerNullifier = fromSingle(foreignInnerNullifier);
517
+ const contractAddress = addressFromSingle(foreignContractAddress);
518
+
519
+ const isPending = await this.handlerAsPrivate().privateIsNullifierPending(innerNullifier, contractAddress);
520
+
521
+ return toForeignCallResult([toSingle(new Fr(isPending))]);
522
+ }
523
+
519
524
  async utilityCheckNullifierExists(foreignInnerNullifier: ForeignCallSingle) {
520
525
  const innerNullifier = fromSingle(foreignInnerNullifier);
521
526
 
@@ -568,17 +573,14 @@ export class RPCTranslator {
568
573
  );
569
574
  }
570
575
 
571
- async utilityGetNullifierMembershipWitness(
572
- foreignBlockNumber: ForeignCallSingle,
573
- foreignNullifier: ForeignCallSingle,
574
- ) {
575
- const blockNumber = BlockNumber(fromSingle(foreignBlockNumber).toNumber());
576
+ async utilityGetNullifierMembershipWitness(foreignBlockHash: ForeignCallSingle, foreignNullifier: ForeignCallSingle) {
577
+ const blockHash = L2BlockHash.fromString(foreignBlockHash);
576
578
  const nullifier = fromSingle(foreignNullifier);
577
579
 
578
- const witness = await this.handlerAsUtility().utilityGetNullifierMembershipWitness(blockNumber, nullifier);
580
+ const witness = await this.handlerAsUtility().utilityGetNullifierMembershipWitness(blockHash, nullifier);
579
581
 
580
582
  if (!witness) {
581
- throw new Error(`Nullifier membership witness not found at block ${blockNumber}.`);
583
+ throw new Error(`Nullifier membership witness not found at block ${blockHash}.`);
582
584
  }
583
585
  return toForeignCallResult(witness.toNoirRepresentation());
584
586
  }
@@ -639,36 +641,41 @@ export class RPCTranslator {
639
641
  return toForeignCallResult(header.toFields().map(toSingle));
640
642
  }
641
643
 
642
- async utilityGetMembershipWitness(
643
- foreignBlockNumber: ForeignCallSingle,
644
- foreignTreeId: ForeignCallSingle,
645
- foreignLeafValue: ForeignCallSingle,
646
- ) {
647
- const blockNumber = BlockNumber(fromSingle(foreignBlockNumber).toNumber());
648
- const treeId = fromSingle(foreignTreeId).toNumber();
644
+ async utilityGetNoteHashMembershipWitness(foreignBlockHash: ForeignCallSingle, foreignLeafValue: ForeignCallSingle) {
645
+ const blockHash = L2BlockHash.fromString(foreignBlockHash);
646
+ const leafValue = fromSingle(foreignLeafValue);
647
+
648
+ const witness = await this.handlerAsUtility().utilityGetNoteHashMembershipWitness(blockHash, leafValue);
649
+
650
+ if (!witness) {
651
+ throw new Error(`Note hash ${leafValue} not found in the note hash tree at block ${blockHash.toString()}.`);
652
+ }
653
+ return toForeignCallResult(witness.toNoirRepresentation());
654
+ }
655
+
656
+ async utilityGetArchiveMembershipWitness(foreignBlockHash: ForeignCallSingle, foreignLeafValue: ForeignCallSingle) {
657
+ const blockHash = L2BlockHash.fromString(foreignBlockHash);
649
658
  const leafValue = fromSingle(foreignLeafValue);
650
659
 
651
- const witness = await this.handlerAsUtility().utilityGetMembershipWitness(blockNumber, treeId, leafValue);
660
+ const witness = await this.handlerAsUtility().utilityGetArchiveMembershipWitness(blockHash, leafValue);
652
661
 
653
662
  if (!witness) {
654
- throw new Error(
655
- `Membership witness in tree ${MerkleTreeId[treeId]} not found for value ${leafValue} at block ${blockNumber}.`,
656
- );
663
+ throw new Error(`Block hash ${leafValue} not found in the archive tree at block ${blockHash.toString()}.`);
657
664
  }
658
- return toForeignCallResult([toSingle(witness[0]), toArray(witness.slice(1))]);
665
+ return toForeignCallResult(witness.toNoirRepresentation());
659
666
  }
660
667
 
661
668
  async utilityGetLowNullifierMembershipWitness(
662
- foreignBlockNumber: ForeignCallSingle,
669
+ foreignBlockHash: ForeignCallSingle,
663
670
  foreignNullifier: ForeignCallSingle,
664
671
  ) {
665
- const blockNumber = BlockNumber(fromSingle(foreignBlockNumber).toNumber());
672
+ const blockHash = L2BlockHash.fromString(foreignBlockHash);
666
673
  const nullifier = fromSingle(foreignNullifier);
667
674
 
668
- const witness = await this.handlerAsUtility().utilityGetLowNullifierMembershipWitness(blockNumber, nullifier);
675
+ const witness = await this.handlerAsUtility().utilityGetLowNullifierMembershipWitness(blockHash, nullifier);
669
676
 
670
677
  if (!witness) {
671
- throw new Error(`Low nullifier witness not found for nullifier ${nullifier} at block ${blockNumber}.`);
678
+ throw new Error(`Low nullifier witness not found for nullifier ${nullifier} at block ${blockHash}.`);
672
679
  }
673
680
  return toForeignCallResult(witness.toNoirRepresentation());
674
681
  }
@@ -681,7 +688,7 @@ export class RPCTranslator {
681
688
  return toForeignCallResult([]);
682
689
  }
683
690
 
684
- public async utilityValidateEnqueuedNotesAndEvents(
691
+ public async utilityValidateAndStoreEnqueuedNotesAndEvents(
685
692
  foreignContractAddress: ForeignCallSingle,
686
693
  foreignNoteValidationRequestsArrayBaseSlot: ForeignCallSingle,
687
694
  foreignEventValidationRequestsArrayBaseSlot: ForeignCallSingle,
@@ -690,7 +697,7 @@ export class RPCTranslator {
690
697
  const noteValidationRequestsArrayBaseSlot = fromSingle(foreignNoteValidationRequestsArrayBaseSlot);
691
698
  const eventValidationRequestsArrayBaseSlot = fromSingle(foreignEventValidationRequestsArrayBaseSlot);
692
699
 
693
- await this.handlerAsUtility().utilityValidateEnqueuedNotesAndEvents(
700
+ await this.handlerAsUtility().utilityValidateAndStoreEnqueuedNotesAndEvents(
694
701
  contractAddress,
695
702
  noteValidationRequestsArrayBaseSlot,
696
703
  eventValidationRequestsArrayBaseSlot,
@@ -828,10 +835,11 @@ export class RPCTranslator {
828
835
  return toForeignCallResult([]);
829
836
  }
830
837
 
831
- async avmOpcodeStorageRead(foreignSlot: ForeignCallSingle) {
838
+ async avmOpcodeStorageRead(foreignSlot: ForeignCallSingle, foreignContractAddress: ForeignCallSingle) {
832
839
  const slot = fromSingle(foreignSlot);
840
+ const contractAddress = AztecAddress.fromField(fromSingle(foreignContractAddress));
833
841
 
834
- const value = (await this.handlerAsAvm().avmOpcodeStorageRead(slot)).value;
842
+ const value = (await this.handlerAsAvm().avmOpcodeStorageRead(slot, contractAddress)).value;
835
843
 
836
844
  return toForeignCallResult([toSingle(new Fr(value))]);
837
845
  }
@@ -1,204 +1,48 @@
1
- import { ArchiverStoreHelper, KVArchiverDataStore } from '@aztec/archiver';
1
+ import { ArchiverDataSourceBase, ArchiverDataStoreUpdater, KVArchiverDataStore } from '@aztec/archiver';
2
2
  import { GENESIS_ARCHIVE_ROOT } from '@aztec/constants';
3
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
3
+ import { CheckpointNumber, type EpochNumber, type SlotNumber } from '@aztec/foundation/branded-types';
4
4
  import { Fr } from '@aztec/foundation/curves/bn254';
5
5
  import type { EthAddress } from '@aztec/foundation/eth-address';
6
- import { isDefined } from '@aztec/foundation/types';
7
6
  import type { AztecAsyncKVStore } from '@aztec/kv-store';
8
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
9
- import {
10
- CommitteeAttestation,
11
- L2Block,
12
- type L2BlockId,
13
- type L2BlockNew,
14
- type L2BlockSource,
15
- type L2Tips,
16
- PublishedL2Block,
17
- type ValidateBlockResult,
18
- } from '@aztec/stdlib/block';
19
- import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
20
- import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
7
+ import type { CheckpointId, L2BlockId, L2TipId, L2Tips, ValidateCheckpointResult } from '@aztec/stdlib/block';
8
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
21
9
  import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
22
- import type { BlockHeader } from '@aztec/stdlib/tx';
23
- import type { UInt64 } from '@aztec/stdlib/types';
24
10
 
25
- // We are extending the ArchiverDataStoreHelper here because it provides most of the endpoints needed by the
26
- // node for reading from and writing to state, without needing any of the extra overhead that the Archiver itself
27
- // requires (i.e. an L1 client)
28
- export class TXEArchiver extends ArchiverStoreHelper implements L2BlockSource {
29
- constructor(db: AztecAsyncKVStore) {
30
- super(new KVArchiverDataStore(db, 9999));
31
- }
32
-
33
- public async getBlock(number: BlockNumber): Promise<L2Block | undefined> {
34
- if (number === 0) {
35
- return undefined;
36
- }
37
- const publishedBlocks = await this.getPublishedBlocks(number, 1);
38
- if (publishedBlocks.length === 0) {
39
- return undefined;
40
- }
41
- return publishedBlocks[0].block;
42
- }
43
-
44
- public async getBlocks(from: BlockNumber, limit: number, proven?: boolean): Promise<L2Block[]> {
45
- const publishedBlocks = await this.getPublishedBlocks(from, limit, proven);
46
- return publishedBlocks.map(x => x.block);
47
- }
48
-
49
- public override async addCheckpoints(
50
- checkpoints: PublishedCheckpoint[],
51
- _result?: ValidateBlockResult,
52
- ): Promise<boolean> {
53
- const allBlocks = checkpoints.flatMap(ch => ch.checkpoint.blocks);
54
- const opResults = await Promise.all([this.store.addLogs(allBlocks), this.store.addCheckpoints(checkpoints)]);
55
-
56
- return opResults.every(Boolean);
57
- }
58
-
59
- /**
60
- * Gets the number of the latest L2 block processed by the block source implementation.
61
- * @returns The number of the latest L2 block processed by the block source implementation.
62
- */
63
- public getBlockNumber(): Promise<BlockNumber> {
64
- return this.store.getLatestBlockNumber();
65
- }
66
-
67
- /**
68
- * Gets the number of the latest L2 block proven seen by the block source implementation.
69
- * @returns The number of the latest L2 block proven seen by the block source implementation.
70
- */
71
- public override getProvenBlockNumber(): Promise<BlockNumber> {
72
- return this.store.getProvenBlockNumber();
73
- }
74
-
75
- /**
76
- * Gets a published l2 block. If a negative number is passed, the block returned is the most recent.
77
- * @param number - The block number to return (inclusive).
78
- * @returns The requested L2 block.
79
- */
80
- public async getPublishedBlock(number: number): Promise<PublishedL2Block | undefined> {
81
- // If the number provided is -ve, then return the latest block.
82
- if (number < 0) {
83
- number = await this.store.getLatestBlockNumber();
84
- }
85
- if (number == 0) {
86
- return undefined;
87
- }
88
- const publishedBlocks = await this.retrievePublishedBlocks(BlockNumber(number), 1);
89
- return publishedBlocks.length === 0 ? undefined : publishedBlocks[0];
90
- }
91
-
92
- getPublishedBlocks(from: BlockNumber, limit: number, proven?: boolean): Promise<PublishedL2Block[]> {
93
- return this.retrievePublishedBlocks(from, limit, proven);
94
- }
95
-
96
- private async retrievePublishedBlocks(
97
- from: BlockNumber,
98
- limit: number,
99
- proven?: boolean,
100
- ): Promise<PublishedL2Block[]> {
101
- const checkpoints = await this.store.getRangeOfCheckpoints(CheckpointNumber(from), limit);
102
- const provenCheckpointNumber = await this.store.getProvenCheckpointNumber();
103
- const blocks = (
104
- await Promise.all(checkpoints.map(ch => this.store.getBlocksForCheckpoint(ch.checkpointNumber)))
105
- ).filter(isDefined);
11
+ /**
12
+ * TXE Archiver implementation.
13
+ * Provides most of the endpoints needed by the node for reading from and writing to state,
14
+ * without needing any of the extra overhead that the Archiver itself requires (i.e. an L1 client).
15
+ */
16
+ export class TXEArchiver extends ArchiverDataSourceBase {
17
+ private readonly updater = new ArchiverDataStoreUpdater(this.store);
106
18
 
107
- const olbBlocks: PublishedL2Block[] = [];
108
- for (let i = 0; i < checkpoints.length; i++) {
109
- const blockForCheckpoint = blocks[i][0];
110
- const checkpoint = checkpoints[i];
111
- if (proven === true && checkpoint.checkpointNumber > provenCheckpointNumber) {
112
- continue;
113
- }
114
- const oldCheckpoint = new Checkpoint(
115
- blockForCheckpoint.archive,
116
- checkpoint.header,
117
- [blockForCheckpoint],
118
- checkpoint.checkpointNumber,
119
- );
120
- const oldBlock = L2Block.fromCheckpoint(oldCheckpoint);
121
- const publishedBlock = new PublishedL2Block(
122
- oldBlock,
123
- checkpoint.l1,
124
- checkpoint.attestations.map(x => CommitteeAttestation.fromBuffer(x)),
125
- );
126
- olbBlocks.push(publishedBlock);
127
- }
128
- return olbBlocks;
129
- }
130
-
131
- /**
132
- * Gets an l2 block. If a negative number is passed, the block returned is the most recent.
133
- * @param number - The block number to return (inclusive).
134
- * @returns The requested L2 block.
135
- */
136
- public getL2Block(number: BlockNumber | 'latest'): Promise<L2Block | undefined> {
137
- return this.getPublishedBlock(number != 'latest' ? number : -1).then(b => b?.block);
138
- }
139
-
140
- /**
141
- * Gets an L2 block (new format).
142
- * @param number - The block number to return.
143
- * @returns The requested L2 block.
144
- */
145
- public getL2BlockNew(number: BlockNumber): Promise<L2BlockNew | undefined> {
146
- if (number === 0) {
147
- return Promise.resolve(undefined);
148
- }
149
- return this.store.getBlock(number);
150
- }
151
-
152
- /**
153
- * Gets an l2 block header.
154
- * @param number - The block number to return or 'latest' for the most recent one.
155
- * @returns The requested L2 block header.
156
- */
157
- public async getBlockHeader(number: number | 'latest'): Promise<BlockHeader | undefined> {
158
- if (number === 'latest') {
159
- number = await this.store.getLatestBlockNumber();
160
- }
161
- if (number === 0) {
162
- return undefined;
163
- }
164
- const headers = await this.store.getBlockHeaders(BlockNumber(number), 1);
165
- return headers.length === 0 ? undefined : headers[0];
166
- }
167
-
168
- public getBlockRange(from: number, limit: number, _proven?: boolean): Promise<L2Block[]> {
169
- return this.getPublishedBlocks(BlockNumber(from), limit).then(blocks => blocks.map(b => b.block));
170
- }
171
-
172
- public getPublishedCheckpoints(_from: CheckpointNumber, _limit: number): Promise<PublishedCheckpoint[]> {
173
- throw new Error('TXE Archiver does not implement "getPublishedCheckpoints"');
174
- }
175
-
176
- public getCheckpointByArchive(_archive: Fr): Promise<Checkpoint | undefined> {
177
- throw new Error('TXE Archiver does not implement "getCheckpointByArchive"');
19
+ constructor(db: AztecAsyncKVStore) {
20
+ const store = new KVArchiverDataStore(db, 9999, { epochDuration: 32 });
21
+ super(store);
178
22
  }
179
23
 
180
- public getL2SlotNumber(): Promise<SlotNumber | undefined> {
181
- throw new Error('TXE Archiver does not implement "getL2SlotNumber"');
24
+ public async addCheckpoints(checkpoints: PublishedCheckpoint[], result?: ValidateCheckpointResult): Promise<void> {
25
+ await this.updater.addCheckpoints(checkpoints, result);
182
26
  }
183
27
 
184
- public getL2EpochNumber(): Promise<EpochNumber> {
185
- throw new Error('TXE Archiver does not implement "getL2EpochNumber"');
28
+ public getRollupAddress(): Promise<EthAddress> {
29
+ throw new Error('TXE Archiver does not implement "getRollupAddress"');
186
30
  }
187
31
 
188
- public getCheckpointsForEpoch(_epochNumber: EpochNumber): Promise<Checkpoint[]> {
189
- throw new Error('TXE Archiver does not implement "getCheckpointsForEpoch"');
32
+ public getRegistryAddress(): Promise<EthAddress> {
33
+ throw new Error('TXE Archiver does not implement "getRegistryAddress"');
190
34
  }
191
35
 
192
- public getBlocksForEpoch(_epochNumber: EpochNumber): Promise<L2Block[]> {
193
- throw new Error('TXE Archiver does not implement "getBlocksForEpoch"');
36
+ public getL1Constants(): Promise<L1RollupConstants> {
37
+ throw new Error('TXE Archiver does not implement "getL1Constants"');
194
38
  }
195
39
 
196
- public getBlockHeadersForEpoch(_epochNumber: EpochNumber): Promise<BlockHeader[]> {
197
- throw new Error('TXE Archiver does not implement "getBlockHeadersForEpoch"');
40
+ public getGenesisValues(): Promise<{ genesisArchiveRoot: Fr }> {
41
+ return Promise.resolve({ genesisArchiveRoot: new Fr(GENESIS_ARCHIVE_ROOT) });
198
42
  }
199
43
 
200
- public isEpochComplete(_epochNumber: EpochNumber): Promise<boolean> {
201
- throw new Error('TXE Archiver does not implement "isEpochComplete"');
44
+ public getL1Timestamp(): Promise<bigint | undefined> {
45
+ throw new Error('TXE Archiver does not implement "getL1Timestamp"');
202
46
  }
203
47
 
204
48
  public async getL2Tips(): Promise<L2Tips> {
@@ -211,53 +55,41 @@ export class TXEArchiver extends ArchiverStoreHelper implements L2BlockSource {
211
55
 
212
56
  const number = blockHeader.globalVariables.blockNumber;
213
57
  const hash = (await blockHeader.hash()).toString();
58
+ const checkpointedBlock = await this.getCheckpointedBlock(number);
59
+ if (!checkpointedBlock) {
60
+ throw new Error(`L2Tips requested from TXE Archiver but no checkpointed block found for block number ${number}`);
61
+ }
62
+ const checkpoint = await this.store.getRangeOfCheckpoints(CheckpointNumber.fromBlockNumber(number), 1);
63
+ if (checkpoint.length === 0) {
64
+ throw new Error(`L2Tips requested from TXE Archiver but no checkpoint found for block number ${number}`);
65
+ }
66
+ const blockId: L2BlockId = { number, hash };
67
+ const checkpointId: CheckpointId = {
68
+ number: checkpoint[0].checkpointNumber,
69
+ hash: checkpoint[0].header.hash().toString(),
70
+ };
71
+ const tipId: L2TipId = { block: blockId, checkpoint: checkpointId };
214
72
  return {
215
- latest: { number, hash } as L2BlockId,
216
- proven: { number, hash } as L2BlockId,
217
- finalized: { number, hash } as L2BlockId,
73
+ proposed: blockId,
74
+ proven: tipId,
75
+ finalized: tipId,
76
+ checkpointed: tipId,
218
77
  };
219
78
  }
220
79
 
221
- public getL1Constants(): Promise<L1RollupConstants> {
222
- throw new Error('TXE Archiver does not implement "getL2Constants"');
223
- }
224
-
225
- public getGenesisValues(): Promise<{ genesisArchiveRoot: Fr }> {
226
- return Promise.resolve({ genesisArchiveRoot: new Fr(GENESIS_ARCHIVE_ROOT) });
227
- }
228
-
229
- public syncImmediate(): Promise<void> {
230
- throw new Error('TXE Archiver does not implement "syncImmediate"');
231
- }
232
-
233
- public getContract(_address: AztecAddress, _timestamp?: UInt64): Promise<ContractInstanceWithAddress | undefined> {
234
- throw new Error('TXE Archiver does not implement "getContract"');
235
- }
236
-
237
- public getRollupAddress(): Promise<EthAddress> {
238
- throw new Error('TXE Archiver does not implement "getRollupAddress"');
239
- }
240
-
241
- public getRegistryAddress(): Promise<EthAddress> {
242
- throw new Error('TXE Archiver does not implement "getRegistryAddress"');
243
- }
244
-
245
- public getL1Timestamp(): Promise<bigint> {
246
- throw new Error('TXE Archiver does not implement "getL1Timestamp"');
80
+ public getL2SlotNumber(): Promise<SlotNumber | undefined> {
81
+ throw new Error('TXE Archiver does not implement "getL2SlotNumber"');
247
82
  }
248
83
 
249
- public isPendingChainInvalid(): Promise<boolean> {
250
- return Promise.resolve(false);
84
+ public getL2EpochNumber(): Promise<EpochNumber | undefined> {
85
+ throw new Error('TXE Archiver does not implement "getL2EpochNumber"');
251
86
  }
252
87
 
253
- public override getPendingChainValidationStatus(): Promise<ValidateBlockResult> {
254
- return Promise.resolve({ valid: true });
88
+ public isEpochComplete(_epochNumber: EpochNumber): Promise<boolean> {
89
+ throw new Error('TXE Archiver does not implement "isEpochComplete"');
255
90
  }
256
91
 
257
- getPublishedBlockByHash(_blockHash: Fr): Promise<PublishedL2Block | undefined> {
258
- throw new Error('Method not implemented.');
259
- }
260
- getPublishedBlockByArchive(_archive: Fr): Promise<PublishedL2Block | undefined> {
261
- throw new Error('Method not implemented.');
92
+ public syncImmediate(): Promise<void> {
93
+ throw new Error('TXE Archiver does not implement "syncImmediate"');
262
94
  }
263
95
  }