@aztec/archiver 4.0.0-nightly.20250907 → 4.0.0-nightly.20260108

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 (133) hide show
  1. package/README.md +27 -6
  2. package/dest/archiver/archiver.d.ts +127 -84
  3. package/dest/archiver/archiver.d.ts.map +1 -1
  4. package/dest/archiver/archiver.js +1150 -382
  5. package/dest/archiver/archiver_store.d.ts +122 -45
  6. package/dest/archiver/archiver_store.d.ts.map +1 -1
  7. package/dest/archiver/archiver_store_test_suite.d.ts +1 -1
  8. package/dest/archiver/archiver_store_test_suite.d.ts.map +1 -1
  9. package/dest/archiver/archiver_store_test_suite.js +2013 -343
  10. package/dest/archiver/config.d.ts +7 -20
  11. package/dest/archiver/config.d.ts.map +1 -1
  12. package/dest/archiver/config.js +21 -5
  13. package/dest/archiver/errors.d.ts +25 -1
  14. package/dest/archiver/errors.d.ts.map +1 -1
  15. package/dest/archiver/errors.js +37 -0
  16. package/dest/archiver/index.d.ts +2 -2
  17. package/dest/archiver/index.d.ts.map +1 -1
  18. package/dest/archiver/instrumentation.d.ts +5 -3
  19. package/dest/archiver/instrumentation.d.ts.map +1 -1
  20. package/dest/archiver/instrumentation.js +14 -0
  21. package/dest/archiver/kv_archiver_store/block_store.d.ts +83 -15
  22. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  23. package/dest/archiver/kv_archiver_store/block_store.js +396 -73
  24. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +2 -2
  25. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +1 -1
  26. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  27. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +2 -2
  28. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +1 -1
  29. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +51 -55
  30. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  31. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +82 -46
  32. package/dest/archiver/kv_archiver_store/log_store.d.ts +12 -16
  33. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +1 -1
  34. package/dest/archiver/kv_archiver_store/log_store.js +149 -84
  35. package/dest/archiver/kv_archiver_store/message_store.d.ts +6 -5
  36. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +1 -1
  37. package/dest/archiver/kv_archiver_store/message_store.js +15 -14
  38. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  39. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  40. package/dest/archiver/l1/bin/retrieve-calldata.js +149 -0
  41. package/dest/archiver/l1/calldata_retriever.d.ts +112 -0
  42. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  43. package/dest/archiver/l1/calldata_retriever.js +471 -0
  44. package/dest/archiver/l1/data_retrieval.d.ts +90 -0
  45. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  46. package/dest/archiver/l1/data_retrieval.js +331 -0
  47. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  48. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  49. package/dest/archiver/l1/debug_tx.js +73 -0
  50. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  51. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  52. package/dest/archiver/l1/spire_proposer.js +157 -0
  53. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  54. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  55. package/dest/archiver/l1/trace_tx.js +91 -0
  56. package/dest/archiver/l1/types.d.ts +12 -0
  57. package/dest/archiver/l1/types.d.ts.map +1 -0
  58. package/dest/archiver/l1/types.js +3 -0
  59. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  60. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  61. package/dest/archiver/l1/validate_trace.js +150 -0
  62. package/dest/archiver/structs/data_retrieval.d.ts +1 -1
  63. package/dest/archiver/structs/inbox_message.d.ts +4 -4
  64. package/dest/archiver/structs/inbox_message.d.ts.map +1 -1
  65. package/dest/archiver/structs/inbox_message.js +6 -5
  66. package/dest/archiver/structs/published.d.ts +2 -2
  67. package/dest/archiver/structs/published.d.ts.map +1 -1
  68. package/dest/archiver/validation.d.ts +10 -4
  69. package/dest/archiver/validation.d.ts.map +1 -1
  70. package/dest/archiver/validation.js +66 -44
  71. package/dest/factory.d.ts +4 -6
  72. package/dest/factory.d.ts.map +1 -1
  73. package/dest/factory.js +5 -4
  74. package/dest/index.d.ts +2 -2
  75. package/dest/index.d.ts.map +1 -1
  76. package/dest/index.js +1 -1
  77. package/dest/rpc/index.d.ts +2 -2
  78. package/dest/test/index.d.ts +1 -1
  79. package/dest/test/mock_archiver.d.ts +16 -8
  80. package/dest/test/mock_archiver.d.ts.map +1 -1
  81. package/dest/test/mock_archiver.js +19 -14
  82. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  83. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  84. package/dest/test/mock_l1_to_l2_message_source.js +10 -9
  85. package/dest/test/mock_l2_block_source.d.ts +31 -20
  86. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  87. package/dest/test/mock_l2_block_source.js +85 -18
  88. package/dest/test/mock_structs.d.ts +3 -2
  89. package/dest/test/mock_structs.d.ts.map +1 -1
  90. package/dest/test/mock_structs.js +9 -8
  91. package/package.json +18 -17
  92. package/src/archiver/archiver.ts +990 -481
  93. package/src/archiver/archiver_store.ts +141 -44
  94. package/src/archiver/archiver_store_test_suite.ts +2114 -331
  95. package/src/archiver/config.ts +30 -35
  96. package/src/archiver/errors.ts +64 -0
  97. package/src/archiver/index.ts +1 -1
  98. package/src/archiver/instrumentation.ts +19 -2
  99. package/src/archiver/kv_archiver_store/block_store.ts +541 -83
  100. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  101. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  102. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +107 -67
  103. package/src/archiver/kv_archiver_store/log_store.ts +209 -99
  104. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  105. package/src/archiver/l1/README.md +98 -0
  106. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  107. package/src/archiver/l1/calldata_retriever.ts +641 -0
  108. package/src/archiver/l1/data_retrieval.ts +512 -0
  109. package/src/archiver/l1/debug_tx.ts +99 -0
  110. package/src/archiver/l1/spire_proposer.ts +160 -0
  111. package/src/archiver/l1/trace_tx.ts +128 -0
  112. package/src/archiver/l1/types.ts +13 -0
  113. package/src/archiver/l1/validate_trace.ts +211 -0
  114. package/src/archiver/structs/inbox_message.ts +8 -8
  115. package/src/archiver/structs/published.ts +1 -1
  116. package/src/archiver/validation.ts +86 -32
  117. package/src/factory.ts +6 -7
  118. package/src/index.ts +1 -1
  119. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  120. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  121. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  122. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  123. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  124. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  125. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  126. package/src/test/mock_archiver.ts +22 -16
  127. package/src/test/mock_l1_to_l2_message_source.ts +10 -9
  128. package/src/test/mock_l2_block_source.ts +114 -27
  129. package/src/test/mock_structs.ts +10 -9
  130. package/dest/archiver/data_retrieval.d.ts +0 -78
  131. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  132. package/dest/archiver/data_retrieval.js +0 -354
  133. package/src/archiver/data_retrieval.ts +0 -535
@@ -0,0 +1,90 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { type CheckpointBlobData } from '@aztec/blob-lib';
3
+ import type { ViemClient, ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
4
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import { EthAddress } from '@aztec/foundation/eth-address';
7
+ import { type Logger } from '@aztec/foundation/log';
8
+ import { type InboxAbi, RollupAbi } from '@aztec/l1-artifacts';
9
+ import { CommitteeAttestation } from '@aztec/stdlib/block';
10
+ import { L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
11
+ import { Proof } from '@aztec/stdlib/proofs';
12
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
13
+ import { type GetContractReturnType, type Hex } from 'viem';
14
+ import type { ArchiverInstrumentation } from '../instrumentation.js';
15
+ import type { DataRetrieval } from '../structs/data_retrieval.js';
16
+ import type { InboxMessage } from '../structs/inbox_message.js';
17
+ export type RetrievedCheckpoint = {
18
+ checkpointNumber: CheckpointNumber;
19
+ archiveRoot: Fr;
20
+ header: CheckpointHeader;
21
+ checkpointBlobData: CheckpointBlobData;
22
+ l1: L1PublishedData;
23
+ chainId: Fr;
24
+ version: Fr;
25
+ attestations: CommitteeAttestation[];
26
+ };
27
+ export declare function retrievedToPublishedCheckpoint({ checkpointNumber, archiveRoot, header: checkpointHeader, checkpointBlobData, l1, chainId, version, attestations }: RetrievedCheckpoint): Promise<PublishedCheckpoint>;
28
+ /**
29
+ * Fetches new checkpoints.
30
+ * @param rollup - The rollup contract instance.
31
+ * @param publicClient - The viem public client to use for transaction retrieval.
32
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
33
+ * @param blobClient - The blob client client for fetching blob data.
34
+ * @param searchStartBlock - The block number to use for starting the search.
35
+ * @param searchEndBlock - The highest block number that we should search up to.
36
+ * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
37
+ * @param instrumentation - The archiver instrumentation instance.
38
+ * @param logger - The logger instance.
39
+ * @param isHistoricalSync - Whether this is a historical sync.
40
+ * @returns An array of retrieved checkpoints.
41
+ */
42
+ export declare function retrieveCheckpointsFromRollup(rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>, publicClient: ViemPublicClient, debugClient: ViemPublicDebugClient, blobClient: BlobClientInterface, searchStartBlock: bigint, searchEndBlock: bigint, contractAddresses: {
43
+ governanceProposerAddress: EthAddress;
44
+ slashFactoryAddress?: EthAddress;
45
+ slashingProposerAddress: EthAddress;
46
+ }, instrumentation: ArchiverInstrumentation, logger?: Logger, isHistoricalSync?: boolean): Promise<RetrievedCheckpoint[]>;
47
+ export declare function getL1BlockTime(publicClient: ViemPublicClient, blockNumber: bigint): Promise<bigint>;
48
+ export declare function getCheckpointBlobDataFromBlobs(blobClient: BlobClientInterface, blockHash: string, blobHashes: Buffer<ArrayBufferLike>[], checkpointNumber: CheckpointNumber, logger: Logger, isHistoricalSync: boolean): Promise<CheckpointBlobData>;
49
+ /** Given an L1 to L2 message, retrieves its corresponding event from the Inbox within a specific block range. */
50
+ export declare function retrieveL1ToL2Message(inbox: GetContractReturnType<typeof InboxAbi, ViemClient>, leaf: Fr, fromBlock: bigint, toBlock: bigint): Promise<InboxMessage | undefined>;
51
+ /**
52
+ * Fetch L1 to L2 messages.
53
+ * @param publicClient - The viem public client to use for transaction retrieval.
54
+ * @param inboxAddress - The address of the inbox contract to fetch messages from.
55
+ * @param blockUntilSynced - If true, blocks until the archiver has fully synced.
56
+ * @param searchStartBlock - The block number to use for starting the search.
57
+ * @param searchEndBlock - The highest block number that we should search up to.
58
+ * @returns An array of InboxLeaf and next eth block to search from.
59
+ */
60
+ export declare function retrieveL1ToL2Messages(inbox: GetContractReturnType<typeof InboxAbi, ViemClient>, searchStartBlock: bigint, searchEndBlock: bigint): Promise<InboxMessage[]>;
61
+ /** Retrieves L2ProofVerified events from the rollup contract. */
62
+ export declare function retrieveL2ProofVerifiedEvents(publicClient: ViemPublicClient, rollupAddress: EthAddress, searchStartBlock: bigint, searchEndBlock?: bigint): Promise<{
63
+ l1BlockNumber: bigint;
64
+ checkpointNumber: CheckpointNumber;
65
+ proverId: Fr;
66
+ txHash: Hex;
67
+ }[]>;
68
+ /** Retrieve submitted proofs from the rollup contract */
69
+ export declare function retrieveL2ProofsFromRollup(publicClient: ViemPublicClient, rollupAddress: EthAddress, searchStartBlock: bigint, searchEndBlock?: bigint): Promise<DataRetrieval<{
70
+ proof: Proof;
71
+ proverId: Fr;
72
+ checkpointNumber: number;
73
+ txHash: `0x${string}`;
74
+ }>>;
75
+ export type SubmitEpochProof = {
76
+ archiveRoot: Fr;
77
+ proverId: Fr;
78
+ proof: Proof;
79
+ };
80
+ /**
81
+ * Gets epoch proof metadata (archive root and proof) from the calldata of an L1 transaction.
82
+ * Assumes that the block was published from an EOA.
83
+ * TODO: Add retries and error management.
84
+ * @param publicClient - The viem public client to use for transaction retrieval.
85
+ * @param txHash - Hash of the tx that published it.
86
+ * @param expectedProverId - Expected prover ID.
87
+ * @returns Epoch proof metadata from the calldata, deserialized.
88
+ */
89
+ export declare function getProofFromSubmitProofTx(publicClient: ViemPublicClient, txHash: `0x${string}`, expectedProverId: Fr): Promise<SubmitEpochProof>;
90
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGF0YV9yZXRyaWV2YWwuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcmNoaXZlci9sMS9kYXRhX3JldHJpZXZhbC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxtQkFBbUIsRUFBRSxNQUFNLDJCQUEyQixDQUFDO0FBQ3JFLE9BQU8sRUFFTCxLQUFLLGtCQUFrQixFQUl4QixNQUFNLGlCQUFpQixDQUFDO0FBRXpCLE9BQU8sS0FBSyxFQUFFLFVBQVUsRUFBRSxnQkFBZ0IsRUFBRSxxQkFBcUIsRUFBRSxNQUFNLHVCQUF1QixDQUFDO0FBRWpHLE9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
+ import { asyncPool } from '@aztec/foundation/async-pool';
3
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
4
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import { EthAddress } from '@aztec/foundation/eth-address';
7
+ import { createLogger } from '@aztec/foundation/log';
8
+ import { RollupAbi } from '@aztec/l1-artifacts';
9
+ import { Body, L2BlockNew } from '@aztec/stdlib/block';
10
+ import { Checkpoint, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
11
+ import { Proof } from '@aztec/stdlib/proofs';
12
+ import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
13
+ import { BlockHeader, GlobalVariables, PartialStateReference, StateReference } from '@aztec/stdlib/tx';
14
+ import { decodeFunctionData, getAbiItem, hexToBytes } from 'viem';
15
+ import { NoBlobBodiesFoundError } from '../errors.js';
16
+ import { CalldataRetriever } from './calldata_retriever.js';
17
+ export async function retrievedToPublishedCheckpoint({ checkpointNumber, archiveRoot, header: checkpointHeader, checkpointBlobData, l1, chainId, version, attestations }) {
18
+ const { blocks: blocksBlobData } = checkpointBlobData;
19
+ // The lastArchiveRoot of a block is the new archive for the previous block.
20
+ const newArchiveRoots = blocksBlobData.map((b)=>b.lastArchiveRoot).slice(1).concat([
21
+ archiveRoot
22
+ ]);
23
+ // An error will be thrown from `decodeCheckpointBlobDataFromBlobs` if it can't read a field for the
24
+ // `l1ToL2MessageRoot` of the first block. So below we can safely assume it exists:
25
+ const l1toL2MessageTreeRoot = blocksBlobData[0].l1ToL2MessageRoot;
26
+ const spongeBlob = SpongeBlob.init();
27
+ const l2Blocks = [];
28
+ for(let i = 0; i < blocksBlobData.length; i++){
29
+ const blockBlobData = blocksBlobData[i];
30
+ const { blockEndMarker, blockEndStateField, lastArchiveRoot, noteHashRoot, nullifierRoot, publicDataRoot } = blockBlobData;
31
+ const l2BlockNumber = blockEndMarker.blockNumber;
32
+ const globalVariables = GlobalVariables.from({
33
+ chainId,
34
+ version,
35
+ blockNumber: l2BlockNumber,
36
+ slotNumber: checkpointHeader.slotNumber,
37
+ timestamp: blockEndMarker.timestamp,
38
+ coinbase: checkpointHeader.coinbase,
39
+ feeRecipient: checkpointHeader.feeRecipient,
40
+ gasFees: checkpointHeader.gasFees
41
+ });
42
+ const state = StateReference.from({
43
+ l1ToL2MessageTree: new AppendOnlyTreeSnapshot(l1toL2MessageTreeRoot, blockEndStateField.l1ToL2MessageNextAvailableLeafIndex),
44
+ partial: PartialStateReference.from({
45
+ noteHashTree: new AppendOnlyTreeSnapshot(noteHashRoot, blockEndStateField.noteHashNextAvailableLeafIndex),
46
+ nullifierTree: new AppendOnlyTreeSnapshot(nullifierRoot, blockEndStateField.nullifierNextAvailableLeafIndex),
47
+ publicDataTree: new AppendOnlyTreeSnapshot(publicDataRoot, blockEndStateField.publicDataNextAvailableLeafIndex)
48
+ })
49
+ });
50
+ const body = Body.fromTxBlobData(checkpointBlobData.blocks[0].txs);
51
+ const blobFields = encodeBlockBlobData(blockBlobData);
52
+ await spongeBlob.absorb(blobFields);
53
+ const clonedSpongeBlob = spongeBlob.clone();
54
+ const spongeBlobHash = await clonedSpongeBlob.squeeze();
55
+ const header = BlockHeader.from({
56
+ lastArchive: new AppendOnlyTreeSnapshot(lastArchiveRoot, l2BlockNumber),
57
+ state,
58
+ spongeBlobHash,
59
+ globalVariables,
60
+ totalFees: body.txEffects.reduce((accum, txEffect)=>accum.add(txEffect.transactionFee), Fr.ZERO),
61
+ totalManaUsed: new Fr(blockEndStateField.totalManaUsed)
62
+ });
63
+ const newArchive = new AppendOnlyTreeSnapshot(newArchiveRoots[i], l2BlockNumber + 1);
64
+ l2Blocks.push(new L2BlockNew(newArchive, header, body, checkpointNumber, i));
65
+ }
66
+ const lastBlock = l2Blocks.at(-1);
67
+ const checkpoint = Checkpoint.from({
68
+ archive: new AppendOnlyTreeSnapshot(archiveRoot, lastBlock.number + 1),
69
+ header: checkpointHeader,
70
+ blocks: l2Blocks,
71
+ number: checkpointNumber
72
+ });
73
+ return PublishedCheckpoint.from({
74
+ checkpoint,
75
+ l1,
76
+ attestations
77
+ });
78
+ }
79
+ /**
80
+ * Fetches new checkpoints.
81
+ * @param rollup - The rollup contract instance.
82
+ * @param publicClient - The viem public client to use for transaction retrieval.
83
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
84
+ * @param blobClient - The blob client client for fetching blob data.
85
+ * @param searchStartBlock - The block number to use for starting the search.
86
+ * @param searchEndBlock - The highest block number that we should search up to.
87
+ * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
88
+ * @param instrumentation - The archiver instrumentation instance.
89
+ * @param logger - The logger instance.
90
+ * @param isHistoricalSync - Whether this is a historical sync.
91
+ * @returns An array of retrieved checkpoints.
92
+ */ export async function retrieveCheckpointsFromRollup(rollup, publicClient, debugClient, blobClient, searchStartBlock, searchEndBlock, contractAddresses, instrumentation, logger = createLogger('archiver'), isHistoricalSync = false) {
93
+ const retrievedCheckpoints = [];
94
+ let rollupConstants;
95
+ do {
96
+ if (searchStartBlock > searchEndBlock) {
97
+ break;
98
+ }
99
+ const checkpointProposedLogs = (await rollup.getEvents.CheckpointProposed({}, {
100
+ fromBlock: searchStartBlock,
101
+ toBlock: searchEndBlock
102
+ })).filter((log)=>log.blockNumber >= searchStartBlock && log.blockNumber <= searchEndBlock);
103
+ if (checkpointProposedLogs.length === 0) {
104
+ break;
105
+ }
106
+ const lastLog = checkpointProposedLogs.at(-1);
107
+ logger.debug(`Got ${checkpointProposedLogs.length} processed logs for checkpoints ${checkpointProposedLogs[0].args.checkpointNumber}-${lastLog.args.checkpointNumber} between L1 blocks ${searchStartBlock}-${searchEndBlock}`);
108
+ if (rollupConstants === undefined) {
109
+ const [chainId, version, targetCommitteeSize] = await Promise.all([
110
+ publicClient.getChainId(),
111
+ rollup.read.getVersion(),
112
+ rollup.read.getTargetCommitteeSize()
113
+ ]);
114
+ rollupConstants = {
115
+ chainId: new Fr(chainId),
116
+ version: new Fr(version),
117
+ targetCommitteeSize: Number(targetCommitteeSize)
118
+ };
119
+ }
120
+ const newCheckpoints = await processCheckpointProposedLogs(rollup, publicClient, debugClient, blobClient, checkpointProposedLogs, rollupConstants, contractAddresses, instrumentation, logger, isHistoricalSync);
121
+ retrievedCheckpoints.push(...newCheckpoints);
122
+ searchStartBlock = lastLog.blockNumber + 1n;
123
+ }while (searchStartBlock <= searchEndBlock)
124
+ // The asyncPool from processCheckpointProposedLogs will not necessarily return the checkpoints in order, so we sort them before returning.
125
+ return retrievedCheckpoints.sort((a, b)=>Number(a.l1.blockNumber - b.l1.blockNumber));
126
+ }
127
+ /**
128
+ * Processes newly received CheckpointProposed logs.
129
+ * @param rollup - The rollup contract instance.
130
+ * @param publicClient - The viem public client to use for transaction retrieval.
131
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
132
+ * @param blobClient - The blob client client for fetching blob data.
133
+ * @param logs - CheckpointProposed logs.
134
+ * @param rollupConstants - The rollup constants (chainId, version, targetCommitteeSize).
135
+ * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
136
+ * @param instrumentation - The archiver instrumentation instance.
137
+ * @param logger - The logger instance.
138
+ * @param isHistoricalSync - Whether this is a historical sync.
139
+ * @returns An array of retrieved checkpoints.
140
+ */ async function processCheckpointProposedLogs(rollup, publicClient, debugClient, blobClient, logs, { chainId, version, targetCommitteeSize }, contractAddresses, instrumentation, logger, isHistoricalSync) {
141
+ const retrievedCheckpoints = [];
142
+ const calldataRetriever = new CalldataRetriever(publicClient, debugClient, targetCommitteeSize, instrumentation, logger, {
143
+ ...contractAddresses,
144
+ rollupAddress: EthAddress.fromString(rollup.address)
145
+ });
146
+ await asyncPool(10, logs, async (log)=>{
147
+ const checkpointNumber = CheckpointNumber.fromBigInt(log.args.checkpointNumber);
148
+ const archive = log.args.archive;
149
+ const archiveFromChain = await rollup.read.archiveAt([
150
+ BigInt(checkpointNumber)
151
+ ]);
152
+ const blobHashes = log.args.versionedBlobHashes.map((blobHash)=>Buffer.from(blobHash.slice(2), 'hex'));
153
+ // The value from the event and contract will match only if the checkpoint is in the chain.
154
+ if (archive === archiveFromChain) {
155
+ // Build expected hashes object (fields may be undefined for backwards compatibility with older events)
156
+ const expectedHashes = {
157
+ attestationsHash: log.args.attestationsHash,
158
+ payloadDigest: log.args.payloadDigest
159
+ };
160
+ const checkpoint = await calldataRetriever.getCheckpointFromRollupTx(log.transactionHash, blobHashes, checkpointNumber, expectedHashes);
161
+ const checkpointBlobData = await getCheckpointBlobDataFromBlobs(blobClient, checkpoint.blockHash, blobHashes, checkpointNumber, logger, isHistoricalSync);
162
+ const l1 = new L1PublishedData(log.blockNumber, await getL1BlockTime(publicClient, log.blockNumber), log.blockHash);
163
+ retrievedCheckpoints.push({
164
+ ...checkpoint,
165
+ checkpointBlobData,
166
+ l1,
167
+ chainId,
168
+ version
169
+ });
170
+ logger.trace(`Retrieved checkpoint ${checkpointNumber} from L1 tx ${log.transactionHash}`, {
171
+ l1BlockNumber: log.blockNumber,
172
+ checkpointNumber,
173
+ archive: archive.toString(),
174
+ attestations: checkpoint.attestations
175
+ });
176
+ } else {
177
+ logger.warn(`Ignoring checkpoint ${checkpointNumber} due to archive root mismatch`, {
178
+ actual: archive,
179
+ expected: archiveFromChain
180
+ });
181
+ }
182
+ });
183
+ return retrievedCheckpoints;
184
+ }
185
+ export async function getL1BlockTime(publicClient, blockNumber) {
186
+ const block = await publicClient.getBlock({
187
+ blockNumber,
188
+ includeTransactions: false
189
+ });
190
+ return block.timestamp;
191
+ }
192
+ export async function getCheckpointBlobDataFromBlobs(blobClient, blockHash, blobHashes, checkpointNumber, logger, isHistoricalSync) {
193
+ const blobBodies = await blobClient.getBlobSidecar(blockHash, blobHashes, {
194
+ isHistoricalSync
195
+ });
196
+ if (blobBodies.length === 0) {
197
+ throw new NoBlobBodiesFoundError(checkpointNumber);
198
+ }
199
+ let checkpointBlobData;
200
+ try {
201
+ // Attempt to decode the checkpoint blob data.
202
+ checkpointBlobData = decodeCheckpointBlobDataFromBlobs(blobBodies);
203
+ } catch (err) {
204
+ if (err instanceof BlobDeserializationError) {
205
+ logger.fatal(err.message);
206
+ } else {
207
+ logger.fatal('Unable to sync: failed to decode fetched blob, this blob was likely not created by us');
208
+ }
209
+ // Throwing an error since this is most likely caused by a bug.
210
+ throw err;
211
+ }
212
+ return checkpointBlobData;
213
+ }
214
+ /** Given an L1 to L2 message, retrieves its corresponding event from the Inbox within a specific block range. */ export async function retrieveL1ToL2Message(inbox, leaf, fromBlock, toBlock) {
215
+ const logs = await inbox.getEvents.MessageSent({
216
+ hash: leaf.toString()
217
+ }, {
218
+ fromBlock,
219
+ toBlock
220
+ });
221
+ const messages = mapLogsInboxMessage(logs);
222
+ return messages.length > 0 ? messages[0] : undefined;
223
+ }
224
+ /**
225
+ * Fetch L1 to L2 messages.
226
+ * @param publicClient - The viem public client to use for transaction retrieval.
227
+ * @param inboxAddress - The address of the inbox contract to fetch messages from.
228
+ * @param blockUntilSynced - If true, blocks until the archiver has fully synced.
229
+ * @param searchStartBlock - The block number to use for starting the search.
230
+ * @param searchEndBlock - The highest block number that we should search up to.
231
+ * @returns An array of InboxLeaf and next eth block to search from.
232
+ */ export async function retrieveL1ToL2Messages(inbox, searchStartBlock, searchEndBlock) {
233
+ const retrievedL1ToL2Messages = [];
234
+ while(searchStartBlock <= searchEndBlock){
235
+ const messageSentLogs = (await inbox.getEvents.MessageSent({}, {
236
+ fromBlock: searchStartBlock,
237
+ toBlock: searchEndBlock
238
+ })).filter((log)=>log.blockNumber >= searchStartBlock && log.blockNumber <= searchEndBlock);
239
+ if (messageSentLogs.length === 0) {
240
+ break;
241
+ }
242
+ retrievedL1ToL2Messages.push(...mapLogsInboxMessage(messageSentLogs));
243
+ searchStartBlock = messageSentLogs.at(-1).blockNumber + 1n;
244
+ }
245
+ return retrievedL1ToL2Messages;
246
+ }
247
+ function mapLogsInboxMessage(logs) {
248
+ return logs.map((log)=>{
249
+ const { index, hash, checkpointNumber, rollingHash } = log.args;
250
+ return {
251
+ index: index,
252
+ leaf: Fr.fromHexString(hash),
253
+ l1BlockNumber: log.blockNumber,
254
+ l1BlockHash: Buffer32.fromString(log.blockHash),
255
+ checkpointNumber: CheckpointNumber.fromBigInt(checkpointNumber),
256
+ rollingHash: Buffer16.fromString(rollingHash)
257
+ };
258
+ });
259
+ }
260
+ /** Retrieves L2ProofVerified events from the rollup contract. */ export async function retrieveL2ProofVerifiedEvents(publicClient, rollupAddress, searchStartBlock, searchEndBlock) {
261
+ const logs = await publicClient.getLogs({
262
+ address: rollupAddress.toString(),
263
+ fromBlock: searchStartBlock,
264
+ toBlock: searchEndBlock ? searchEndBlock : undefined,
265
+ strict: true,
266
+ event: getAbiItem({
267
+ abi: RollupAbi,
268
+ name: 'L2ProofVerified'
269
+ })
270
+ });
271
+ return logs.map((log)=>({
272
+ l1BlockNumber: log.blockNumber,
273
+ checkpointNumber: CheckpointNumber.fromBigInt(log.args.checkpointNumber),
274
+ proverId: Fr.fromHexString(log.args.proverId),
275
+ txHash: log.transactionHash
276
+ }));
277
+ }
278
+ /** Retrieve submitted proofs from the rollup contract */ export async function retrieveL2ProofsFromRollup(publicClient, rollupAddress, searchStartBlock, searchEndBlock) {
279
+ const logs = await retrieveL2ProofVerifiedEvents(publicClient, rollupAddress, searchStartBlock, searchEndBlock);
280
+ const retrievedData = [];
281
+ const lastProcessedL1BlockNumber = logs.length > 0 ? logs.at(-1).l1BlockNumber : searchStartBlock - 1n;
282
+ for (const { txHash, proverId, checkpointNumber } of logs){
283
+ const proofData = await getProofFromSubmitProofTx(publicClient, txHash, proverId);
284
+ retrievedData.push({
285
+ proof: proofData.proof,
286
+ proverId: proofData.proverId,
287
+ checkpointNumber,
288
+ txHash
289
+ });
290
+ }
291
+ return {
292
+ retrievedData,
293
+ lastProcessedL1BlockNumber
294
+ };
295
+ }
296
+ /**
297
+ * Gets epoch proof metadata (archive root and proof) from the calldata of an L1 transaction.
298
+ * Assumes that the block was published from an EOA.
299
+ * TODO: Add retries and error management.
300
+ * @param publicClient - The viem public client to use for transaction retrieval.
301
+ * @param txHash - Hash of the tx that published it.
302
+ * @param expectedProverId - Expected prover ID.
303
+ * @returns Epoch proof metadata from the calldata, deserialized.
304
+ */ export async function getProofFromSubmitProofTx(publicClient, txHash, expectedProverId) {
305
+ const { input: data } = await publicClient.getTransaction({
306
+ hash: txHash
307
+ });
308
+ const { functionName, args } = decodeFunctionData({
309
+ abi: RollupAbi,
310
+ data
311
+ });
312
+ let proverId;
313
+ let archiveRoot;
314
+ let proof;
315
+ if (functionName === 'submitEpochRootProof') {
316
+ const [decodedArgs] = args;
317
+ proverId = Fr.fromHexString(decodedArgs.args.proverId);
318
+ archiveRoot = Fr.fromHexString(decodedArgs.args.endArchive);
319
+ proof = Proof.fromBuffer(Buffer.from(hexToBytes(decodedArgs.proof)));
320
+ } else {
321
+ throw new Error(`Unexpected proof method called ${functionName}`);
322
+ }
323
+ if (!proverId.equals(expectedProverId)) {
324
+ throw new Error(`Prover ID mismatch: expected ${expectedProverId} but got ${proverId}`);
325
+ }
326
+ return {
327
+ proverId,
328
+ archiveRoot,
329
+ proof
330
+ };
331
+ }
@@ -0,0 +1,19 @@
1
+ import type { DebugCallTrace, ViemPublicDebugClient } from '@aztec/ethereum/types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import { type ZodFor } from '@aztec/foundation/schemas';
5
+ import type { Hex } from 'viem';
6
+ import type { CallInfo } from './types.js';
7
+ /** Zod schema for validating call trace from debug_traceTransaction */
8
+ export declare const callTraceSchema: ZodFor<DebugCallTrace>;
9
+ /**
10
+ * Traces a transaction and extracts all CALL operations to a specific contract and function selector.
11
+ *
12
+ * @param client - The Viem public client
13
+ * @param txHash - The transaction hash to trace
14
+ * @param targetAddress - The contract address to filter for
15
+ * @param functionSelector - The 4-byte function selector to filter for (with or without 0x prefix)
16
+ * @returns Array of CallInfo objects containing from, gasUsed, input, and value for matching calls
17
+ */
18
+ export declare function getSuccessfulCallsFromDebug(client: ViemPublicDebugClient, txHash: Hex, targetAddress: EthAddress, functionSelector: string, logger?: Logger): Promise<CallInfo[]>;
19
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVidWdfdHguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcmNoaXZlci9sMS9kZWJ1Z190eC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxjQUFjLEVBQUUscUJBQXFCLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUNuRixPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sK0JBQStCLENBQUM7QUFDM0QsT0FBTyxLQUFLLEVBQUUsTUFBTSxFQUFFLE1BQU0sdUJBQXVCLENBQUM7QUFDcEQsT0FBTyxFQUFFLEtBQUssTUFBTSxFQUFXLE1BQU0sMkJBQTJCLENBQUM7QUFHakUsT0FBTyxLQUFLLEVBQUUsR0FBRyxFQUFFLE1BQU0sTUFBTSxDQUFDO0FBR2hDLE9BQU8sS0FBSyxFQUFFLFFBQVEsRUFBRSxNQUFNLFlBQVksQ0FBQztBQUUzQyx1RUFBdUU7QUFDdkUsZUFBTyxNQUFNLGVBQWUsRUFBRSxNQUFNLENBQUMsY0FBYyxDQWFsRCxDQUFDO0FBRUY7Ozs7Ozs7O0dBUUc7QUFDSCx3QkFBc0IsMkJBQTJCLENBQy9DLE1BQU0sRUFBRSxxQkFBcUIsRUFDN0IsTUFBTSxFQUFFLEdBQUcsRUFDWCxhQUFhLEVBQUUsVUFBVSxFQUN6QixnQkFBZ0IsRUFBRSxNQUFNLEVBQ3hCLE1BQU0sQ0FBQyxFQUFFLE1BQU0sR0FDZCxPQUFPLENBQUMsUUFBUSxFQUFFLENBQUMsQ0F3RHJCIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug_tx.d.ts","sourceRoot":"","sources":["../../../src/archiver/l1/debug_tx.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,KAAK,MAAM,EAAW,MAAM,2BAA2B,CAAC;AAGjE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAGhC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,uEAAuE;AACvE,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,cAAc,CAalD,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,qBAAqB,EAC7B,MAAM,EAAE,GAAG,EACX,aAAa,EAAE,UAAU,EACzB,gBAAgB,EAAE,MAAM,EACxB,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,QAAQ,EAAE,CAAC,CAwDrB"}
@@ -0,0 +1,73 @@
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
+ import { schemas } from '@aztec/foundation/schemas';
3
+ import { withHexPrefix } from '@aztec/foundation/string';
4
+ import { z } from 'zod';
5
+ /** Zod schema for validating call trace from debug_traceTransaction */ export const callTraceSchema = z.lazy(()=>z.object({
6
+ from: schemas.HexStringWith0x,
7
+ to: schemas.HexStringWith0x.optional(),
8
+ type: z.string(),
9
+ input: schemas.HexStringWith0x.optional(),
10
+ output: schemas.HexStringWith0x.optional(),
11
+ gas: schemas.HexStringWith0x.optional(),
12
+ gasUsed: schemas.HexStringWith0x.optional(),
13
+ value: schemas.HexStringWith0x.optional(),
14
+ error: z.string().optional(),
15
+ calls: z.array(callTraceSchema).optional()
16
+ }));
17
+ /**
18
+ * Traces a transaction and extracts all CALL operations to a specific contract and function selector.
19
+ *
20
+ * @param client - The Viem public client
21
+ * @param txHash - The transaction hash to trace
22
+ * @param targetAddress - The contract address to filter for
23
+ * @param functionSelector - The 4-byte function selector to filter for (with or without 0x prefix)
24
+ * @returns Array of CallInfo objects containing from, gasUsed, input, and value for matching calls
25
+ */ export async function getSuccessfulCallsFromDebug(client, txHash, targetAddress, functionSelector, logger) {
26
+ // Normalize inputs for comparison
27
+ const normalizedTarget = targetAddress.toString().toLowerCase();
28
+ const normalizedSelector = withHexPrefix(functionSelector.toLowerCase());
29
+ // Call debug_traceTransaction with callTracer
30
+ // Using 'any' here because debug_traceTransaction is not in viem's standard RPC types
31
+ const rawTrace = await client.request({
32
+ method: 'debug_traceTransaction',
33
+ params: [
34
+ txHash,
35
+ {
36
+ tracer: 'callTracer'
37
+ }
38
+ ]
39
+ });
40
+ if (rawTrace === null || rawTrace === undefined) {
41
+ throw new Error(`Failed to retrieve debug_traceTransaction for ${txHash}`);
42
+ }
43
+ logger?.trace(`Retrieved debug_traceTransaction for ${txHash}`, {
44
+ trace: rawTrace
45
+ });
46
+ // Validate the response with zod
47
+ const trace = callTraceSchema.parse(rawTrace);
48
+ const results = [];
49
+ /**
50
+ * Recursively traverse the call trace tree
51
+ */ function traverseCalls(callTrace) {
52
+ // Skip calls that have errors, and all its descendants
53
+ if (callTrace.error) {
54
+ return;
55
+ }
56
+ // Check if this is a CALL (not DELEGATECALL or STATICCALL) to the target address with matching selector
57
+ if (callTrace.type.toUpperCase() === 'CALL' && callTrace.to?.toLowerCase() === normalizedTarget && callTrace.input?.toLowerCase().startsWith(normalizedSelector)) {
58
+ results.push({
59
+ from: EthAddress.fromString(callTrace.from),
60
+ gasUsed: callTrace.gasUsed === undefined ? undefined : BigInt(callTrace.gasUsed),
61
+ input: callTrace.input,
62
+ value: callTrace.value ? BigInt(callTrace.value) : 0n
63
+ });
64
+ }
65
+ // Recursively process nested calls
66
+ for (const nestedCall of callTrace.calls ?? []){
67
+ traverseCalls(nestedCall);
68
+ }
69
+ }
70
+ // Start traversal from the root trace
71
+ traverseCalls(trace);
72
+ return results;
73
+ }
@@ -0,0 +1,70 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+ import { type Hex, type Transaction } from 'viem';
3
+ export declare const SPIRE_PROPOSER_ADDRESS = "0x9ccc2f3ecde026230e11a5c8799ac7524f2bb294";
4
+ export declare const SPIRE_PROPOSER_EXPECTED_IMPLEMENTATION = "0x7d38d47e7c82195e6e607d3b0f1c20c615c7bf42";
5
+ export declare const EIP1967_IMPLEMENTATION_SLOT: "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";
6
+ export declare const SpireProposerAbi: readonly [{
7
+ readonly inputs: readonly [{
8
+ readonly components: readonly [{
9
+ readonly internalType: "address";
10
+ readonly name: "proposer";
11
+ readonly type: "address";
12
+ }, {
13
+ readonly internalType: "address";
14
+ readonly name: "target";
15
+ readonly type: "address";
16
+ }, {
17
+ readonly internalType: "bytes";
18
+ readonly name: "data";
19
+ readonly type: "bytes";
20
+ }, {
21
+ readonly internalType: "uint256";
22
+ readonly name: "value";
23
+ readonly type: "uint256";
24
+ }, {
25
+ readonly internalType: "uint256";
26
+ readonly name: "gasLimit";
27
+ readonly type: "uint256";
28
+ }];
29
+ readonly internalType: "struct IProposerMulticall.Call[]";
30
+ readonly name: "_calls";
31
+ readonly type: "tuple[]";
32
+ }];
33
+ readonly name: "multicall";
34
+ readonly outputs: readonly [];
35
+ readonly stateMutability: "nonpayable";
36
+ readonly type: "function";
37
+ }];
38
+ /**
39
+ * Verifies that a proxy contract points to the expected implementation using EIP-1967.
40
+ * @param publicClient - The viem public client
41
+ * @param proxyAddress - The proxy contract address
42
+ * @param expectedImplementation - The expected implementation address
43
+ * @param logger - Logger instance
44
+ * @returns True if the proxy points to the expected implementation
45
+ */
46
+ export declare function verifyProxyImplementation(publicClient: {
47
+ getStorageAt: (params: {
48
+ address: Hex;
49
+ slot: Hex;
50
+ }) => Promise<Hex | undefined>;
51
+ }, proxyAddress: Hex, expectedImplementation: Hex, logger: Logger): Promise<boolean>;
52
+ /**
53
+ * Attempts to decode transaction as a Spire Proposer Multicall.
54
+ * Spire Proposer is a proxy contract that wraps multiple calls.
55
+ * Returns the target address and calldata of the wrapped call if validation succeeds and there is a single call.
56
+ * @param tx - The transaction to decode
57
+ * @param publicClient - The viem public client for proxy verification
58
+ * @param logger - Logger instance
59
+ * @returns Object with 'to' and 'data' of the wrapped call, or undefined if validation fails
60
+ */
61
+ export declare function getCallFromSpireProposer(tx: Transaction, publicClient: {
62
+ getStorageAt: (params: {
63
+ address: Hex;
64
+ slot: Hex;
65
+ }) => Promise<Hex | undefined>;
66
+ }, logger: Logger): Promise<{
67
+ to: Hex;
68
+ data: Hex;
69
+ } | undefined>;
70
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3BpcmVfcHJvcG9zZXIuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcmNoaXZlci9sMS9zcGlyZV9wcm9wb3Nlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEtBQUssRUFBRSxNQUFNLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUVwRCxPQUFPLEVBQUUsS0FBSyxHQUFHLEVBQUUsS0FBSyxXQUFXLEVBQXdDLE1BQU0sTUFBTSxDQUFDO0FBR3hGLGVBQU8sTUFBTSxzQkFBc0IsK0NBQStDLENBQUM7QUFDbkYsZUFBTyxNQUFNLHNDQUFzQywrQ0FBK0MsQ0FBQztBQUluRyxlQUFPLE1BQU0sMkJBQTJCLHNFQUN1QyxDQUFDO0FBR2hGLGVBQU8sTUFBTSxnQkFBZ0I7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7RUFxQm5CLENBQUM7QUFFWDs7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