From 0226102c8161b02c60405b51439e0712f044c921 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bene=C5=A1?= Date: Fri, 22 Mar 2024 14:13:07 +0100 Subject: [PATCH] refactor: messaging naming fixes (#5383) Some naming fixes we discussed in our team chat and which Lasse [disliked](https://github.com/AztecProtocol/aztec-packages/pull/5206#discussion_r1528245150) in my purge PR a few days ago. \+ nuked some stale stuff from contracts. --- .../references/portals/data_structures.md | 12 -- .../developers/debugging/sandbox-errors.md | 4 +- l1-contracts/GUIDE_LINES.md | 17 ++- l1-contracts/slither_output.md | 50 ++------ .../core/interfaces/messagebridge/IInbox.sol | 10 +- .../src/core/libraries/DataStructures.sol | 16 --- l1-contracts/src/core/libraries/Errors.sol | 4 +- .../src/core/libraries/MessageBox.sol | 113 ------------------ l1-contracts/src/core/messagebridge/Inbox.sol | 6 +- l1-contracts/test/Inbox.t.sol | 2 +- l1-contracts/test/Registry.t.sol | 1 - l1-contracts/test/portals/TokenPortal.t.sol | 6 +- l1-contracts/test/portals/UniswapPortal.sol | 4 +- l1-contracts/test/portals/UniswapPortal.t.sol | 89 +++++++------- noir-projects/aztec-nr/aztec/src/messaging.nr | 6 +- .../oracle/get_l1_to_l2_membership_witness.nr | 8 +- .../archiver/src/archiver/archiver.test.ts | 26 ++-- .../archiver/src/archiver/archiver.ts | 17 +-- .../archiver/src/archiver/archiver_store.ts | 10 +- .../src/archiver/archiver_store_test_suite.ts | 20 ++-- .../archiver/src/archiver/data_retrieval.ts | 12 +- .../archiver/src/archiver/eth_log_handlers.ts | 24 ++-- .../kv_archiver_store/kv_archiver_store.ts | 8 +- .../l1_to_l2_message_store.ts | 3 +- .../memory_archiver_store.ts | 6 +- .../aztec-node/src/aztec-node/server.ts | 12 +- .../src/interfaces/aztec-node.ts | 9 +- .../circuit-types/src/messaging/inbox_leaf.ts | 2 +- .../src/messaging/l1_to_l2_message.ts | 8 +- .../src/e2e_cross_chain_messaging.test.ts | 16 +-- .../end-to-end/src/e2e_outbox.test.ts | 16 +-- .../e2e_public_cross_chain_messaging.test.ts | 26 ++-- .../e2e_public_to_private_messaging.test.ts | 4 +- .../src/integration_l1_publisher.test.ts | 2 +- .../src/shared/cross_chain_test_harness.ts | 18 +-- .../src/shared/gas_portal_test_harness.ts | 8 +- .../end-to-end/src/shared/uniswap_l1_l2.ts | 36 +++--- .../pxe/src/simulator_oracle/index.ts | 15 +-- .../src/simulator/public_executor.ts | 6 +- .../simulator/src/acvm/oracle/oracle.ts | 4 +- .../simulator/src/acvm/oracle/typed_oracle.ts | 2 +- .../simulator/src/client/view_data_oracle.ts | 8 +- yarn-project/simulator/src/public/db.ts | 8 +- .../src/public/public_execution_context.ts | 6 +- 44 files changed, 258 insertions(+), 422 deletions(-) delete mode 100644 l1-contracts/src/core/libraries/MessageBox.sol diff --git a/docs/docs/developers/contracts/references/portals/data_structures.md b/docs/docs/developers/contracts/references/portals/data_structures.md index babbe4211d0..ba97bfd5272 100644 --- a/docs/docs/developers/contracts/references/portals/data_structures.md +++ b/docs/docs/developers/contracts/references/portals/data_structures.md @@ -6,18 +6,6 @@ The `DataStructures` are structs that we are using throughout the message infras **Links**: [Implementation](https://github.com/AztecProtocol/aztec-packages/blob/master/l1-contracts/src/core/libraries/DataStructures.sol). -## `Entry` - -An entry for the messageboxes multi-sets. - -#include_code data_structure_entry l1-contracts/src/core/libraries/DataStructures.sol solidity - -| Name | Type | Description | -| -------------- | ------- | ----------- | -| `count` | `uint32` | The occurrence of the entry in the dataset | -| `version` | `uint32` | The version of the entry | - - ## `L1Actor` An entity on L1, specifying the address and the chainId for the entity. Used when specifying sender/recipient with an entity that is on L1. diff --git a/docs/docs/developers/debugging/sandbox-errors.md b/docs/docs/developers/debugging/sandbox-errors.md index 0dfb7675713..911654026b6 100644 --- a/docs/docs/developers/debugging/sandbox-errors.md +++ b/docs/docs/developers/debugging/sandbox-errors.md @@ -177,9 +177,7 @@ Users may create a proof against a historical state in Aztec. The rollup circuit ## Archiver Errors -- "L1 to L2 Message with key ${entryKey.toString()} not found in the confirmed messages store" - happens when the L1 to L2 message doesn't exist or is "pending", when the user has sent a message on L1 via the Inbox contract but it has yet to be included in an L2 block by the sequencer - user has to wait for sequencer to pick it up and the archiver to sync the respective L2 block. You can get the sequencer to pick it up by doing an arbitrary transaction on L2 (eg send DAI to yourself). This would give the sequencer a transaction to process and as a side effect it would look for any pending messages it should include. - -- "Unable to remove message: L1 to L2 Message with key ${entryKeyBigInt} not found in store" - happens when trying to confirm a non-existent pending message or cancelling such a message. Perhaps the sequencer has already confirmed the message? +- "No L1 to L2 message found for message hash ${messageHash.toString()}" - happens when the L1 to L2 message doesn't exist or is "pending", when the user has sent a message on L1 via the Inbox contract but it has yet to be included in an L2 block by the sequencer - user has to wait for enough blocks to progress and for the archiver to sync the respective L2 block. You can get the sequencer to pick it up by doing 2 arbitrary transaction on L2 (eg. send DAI to yourself 2 times). This would give the sequencer a transaction to process and as a side effect it would consume 2 subtrees of new messages from the Inbox contract. 2 subtrees needs to be consumed and not just 1 because there is a 1 block lag to prevent the subtree from changing when the sequencer is proving. - "Block number mismatch: expected ${l2BlockNum} but got ${block.number}" - The archiver keeps track of the next expected L2 block number. It throws this error if it got a different one when trying to sync with the rollup contract's events on L1. diff --git a/l1-contracts/GUIDE_LINES.md b/l1-contracts/GUIDE_LINES.md index e62096e2bab..4e4ea93a552 100644 --- a/l1-contracts/GUIDE_LINES.md +++ b/l1-contracts/GUIDE_LINES.md @@ -120,13 +120,18 @@ Natspec should be written for all functions (`internal` mainly for clarity). Use ```solidity /** - * @notice Consumes an entry from the Outbox - * @dev Only meaningfully callable by portals, otherwise should never hit an entry - * @dev Emits the `MessageConsumed` event when consuming messages - * @param _message - The L2 to L1 message - * @return entryKey - The key of the entry removed + * @notice Inserts a new message into the Inbox + * @dev Emits `MessageSent` with data for easy access by the sequencer + * @param _recipient - The recipient of the message + * @param _content - The content of the message (application specific) + * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on L2) + * @return Hash of the sent message. */ - function consume(DataStructures.L2ToL1Msg memory _message) + function sendL2Message( + DataStructures.L2Actor memory _recipient, + bytes32 _content, + bytes32 _secretHash + ) external override(IInbox) returns (bytes32) { ``` ### Solhint configuration diff --git a/l1-contracts/slither_output.md b/l1-contracts/slither_output.md index 9b23244910e..17f01315b45 100644 --- a/l1-contracts/slither_output.md +++ b/l1-contracts/slither_output.md @@ -7,7 +7,7 @@ Summary - [timestamp](#timestamp) (1 results) (Low) - [pess-public-vs-external](#pess-public-vs-external) (5 results) (Low) - [assembly](#assembly) (1 results) (Informational) - - [dead-code](#dead-code) (5 results) (Informational) + - [dead-code](#dead-code) (1 results) (Informational) - [solc-version](#solc-version) (1 results) (Informational) - [similar-names](#similar-names) (3 results) (Informational) - [constable-states](#constable-states) (1 results) (Optimization) @@ -123,7 +123,7 @@ Reentrancy in [Inbox.sendL2Message(DataStructures.L2Actor,bytes32,bytes32)](src/ External calls: - [index = currentTree.insertLeaf(leaf)](src/core/messagebridge/Inbox.sol#L91) Event emitted after the call(s): - - [LeafInserted(inProgress,index,leaf)](src/core/messagebridge/Inbox.sol#L92) + - [MessageSent(inProgress,index,leaf)](src/core/messagebridge/Inbox.sol#L92) src/core/messagebridge/Inbox.sol#L61-L95 @@ -191,30 +191,6 @@ src/core/libraries/decoders/TxsDecoder.sol#L258-L277 Impact: Informational Confidence: Medium - [ ] ID-18 -[MessageBox.consume(mapping(bytes32 => DataStructures.Entry),bytes32,function(bytes32))](src/core/libraries/MessageBox.sol#L71-L79) is never used and should be removed - -src/core/libraries/MessageBox.sol#L71-L79 - - - - [ ] ID-19 -[MessageBox.contains(mapping(bytes32 => DataStructures.Entry),bytes32)](src/core/libraries/MessageBox.sol#L87-L92) is never used and should be removed - -src/core/libraries/MessageBox.sol#L87-L92 - - - - [ ] ID-20 -[MessageBox.get(mapping(bytes32 => DataStructures.Entry),bytes32,function(bytes32))](src/core/libraries/MessageBox.sol#L104-L112) is never used and should be removed - -src/core/libraries/MessageBox.sol#L104-L112 - - - - [ ] ID-21 -[MessageBox.insert(mapping(bytes32 => DataStructures.Entry),bytes32,uint64,uint32,uint32,function(bytes32,uint64,uint64,uint32,uint32,uint32,uint32))](src/core/libraries/MessageBox.sol#L30-L60) is never used and should be removed - -src/core/libraries/MessageBox.sol#L30-L60 - - - - [ ] ID-22 [Hash.sha256ToField(bytes32)](src/core/libraries/Hash.sol#L52-L54) is never used and should be removed src/core/libraries/Hash.sol#L52-L54 @@ -223,25 +199,25 @@ src/core/libraries/Hash.sol#L52-L54 ## solc-version Impact: Informational Confidence: High - - [ ] ID-23 + - [ ] ID-19 solc-0.8.23 is not recommended for deployment ## similar-names Impact: Informational Confidence: Medium - - [ ] ID-24 + - [ ] ID-20 Variable [Constants.LOGS_HASHES_NUM_BYTES_PER_BASE_ROLLUP](src/core/libraries/ConstantsGen.sol#L130) is too similar to [Constants.NOTE_HASHES_NUM_BYTES_PER_BASE_ROLLUP](src/core/libraries/ConstantsGen.sol#L123) src/core/libraries/ConstantsGen.sol#L130 - - [ ] ID-25 + - [ ] ID-21 Variable [Constants.L1_TO_L2_MESSAGE_LENGTH](src/core/libraries/ConstantsGen.sol#L110) is too similar to [Constants.L2_TO_L1_MESSAGE_LENGTH](src/core/libraries/ConstantsGen.sol#L111) src/core/libraries/ConstantsGen.sol#L110 - - [ ] ID-26 + - [ ] ID-22 Variable [Rollup.AVAILABILITY_ORACLE](src/core/Rollup.sol#L32) is too similar to [Rollup.constructor(IRegistry,IAvailabilityOracle)._availabilityOracle](src/core/Rollup.sol#L43) src/core/Rollup.sol#L32 @@ -250,7 +226,7 @@ src/core/Rollup.sol#L32 ## constable-states Impact: Optimization Confidence: High - - [ ] ID-27 + - [ ] ID-23 [Rollup.lastWarpedBlockTs](src/core/Rollup.sol#L41) should be constant src/core/Rollup.sol#L41 @@ -259,37 +235,37 @@ src/core/Rollup.sol#L41 ## pess-multiple-storage-read Impact: Optimization Confidence: High - - [ ] ID-28 + - [ ] ID-24 In a function [Outbox.insert(uint256,bytes32,uint256)](src/core/messagebridge/Outbox.sol#L44-L64) variable [Outbox.roots](src/core/messagebridge/Outbox.sol#L29) is read multiple times src/core/messagebridge/Outbox.sol#L44-L64 - - [ ] ID-29 + - [ ] ID-25 In a function [Inbox.consume()](src/core/messagebridge/Inbox.sol#L104-L123) variable [Inbox.toConsume](src/core/messagebridge/Inbox.sol#L34) is read multiple times src/core/messagebridge/Inbox.sol#L104-L123 - - [ ] ID-30 + - [ ] ID-26 In a function [Inbox.consume()](src/core/messagebridge/Inbox.sol#L104-L123) variable [Inbox.inProgress](src/core/messagebridge/Inbox.sol#L36) is read multiple times src/core/messagebridge/Inbox.sol#L104-L123 - - [ ] ID-31 + - [ ] ID-27 In a function [FrontierMerkle.root()](src/core/messagebridge/frontier_tree/Frontier.sol#L48-L81) variable [FrontierMerkle.HEIGHT](src/core/messagebridge/frontier_tree/Frontier.sol#L13) is read multiple times src/core/messagebridge/frontier_tree/Frontier.sol#L48-L81 - - [ ] ID-32 + - [ ] ID-28 In a function [Inbox.sendL2Message(DataStructures.L2Actor,bytes32,bytes32)](src/core/messagebridge/Inbox.sol#L61-L95) variable [Inbox.inProgress](src/core/messagebridge/Inbox.sol#L36) is read multiple times src/core/messagebridge/Inbox.sol#L61-L95 - - [ ] ID-33 + - [ ] ID-29 In a function [FrontierMerkle.root()](src/core/messagebridge/frontier_tree/Frontier.sol#L48-L81) variable [FrontierMerkle.frontier](src/core/messagebridge/frontier_tree/Frontier.sol#L18) is read multiple times src/core/messagebridge/frontier_tree/Frontier.sol#L48-L81 diff --git a/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol b/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol index b5a261d0ef3..2139bd78483 100644 --- a/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol +++ b/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol @@ -10,12 +10,18 @@ import {DataStructures} from "../../libraries/DataStructures.sol"; * @notice Lives on L1 and is used to pass messages into the rollup from L1. */ interface IInbox { - event LeafInserted(uint256 indexed blockNumber, uint256 index, bytes32 value); + /** + * @notice Emitted when a message is sent + * @param l2BlockNumber - The L2 block number in which the message is included + * @param index - The index of the message in the block + * @param hash - The hash of the message + */ + event MessageSent(uint256 indexed l2BlockNumber, uint256 index, bytes32 hash); // docs:start:send_l1_to_l2_message /** * @notice Inserts a new message into the Inbox - * @dev Emits `LeafInserted` with data for easy access by the sequencer + * @dev Emits `MessageSent` with data for easy access by the sequencer * @param _recipient - The recipient of the message * @param _content - The content of the message (application specific) * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on L2) diff --git a/l1-contracts/src/core/libraries/DataStructures.sol b/l1-contracts/src/core/libraries/DataStructures.sol index 8a8e8d3a0e5..00367bf0319 100644 --- a/l1-contracts/src/core/libraries/DataStructures.sol +++ b/l1-contracts/src/core/libraries/DataStructures.sol @@ -8,22 +8,6 @@ pragma solidity >=0.8.18; * @notice Library that contains data structures used throughout the Aztec protocol */ library DataStructures { - // docs:start:data_structure_entry - /** - * @notice Entry struct - Done as struct to easily support extensions if needed - * @param fee - The fee provided to sequencer for including in the inbox. 0 if Outbox (as not applicable). - * @param count - The occurrence of the entry in the dataset - * @param version - The version of the entry - * @param deadline - The deadline to consume a message. Only after it, can a message be cancelled. - */ - struct Entry { - uint64 fee; - uint32 count; - uint32 version; - uint32 deadline; - } - // docs:end:data_structure_entry - // docs:start:l1_actor /** * @notice Actor on L1. diff --git a/l1-contracts/src/core/libraries/Errors.sol b/l1-contracts/src/core/libraries/Errors.sol index 92e3006eb8b..7b47ffde25a 100644 --- a/l1-contracts/src/core/libraries/Errors.sol +++ b/l1-contracts/src/core/libraries/Errors.sol @@ -20,9 +20,9 @@ library Errors { error Outbox__Unauthorized(); // 0x2c9490c2 error Outbox__InvalidChainId(); // 0x577ec7c4 error Outbox__InvalidVersion(uint256 entry, uint256 message); // 0x7915cac3 - error Outbox__NothingToConsume(bytes32 entryKey); // 0xfb4fb506 + error Outbox__NothingToConsume(bytes32 messageHash); // 0xfb4fb506 error Outbox__IncompatibleEntryArguments( - bytes32 entryKey, + bytes32 messageHash, uint64 storedFee, uint64 feePassed, uint32 storedVersion, diff --git a/l1-contracts/src/core/libraries/MessageBox.sol b/l1-contracts/src/core/libraries/MessageBox.sol deleted file mode 100644 index dd20785c171..00000000000 --- a/l1-contracts/src/core/libraries/MessageBox.sol +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Copyright 2023 Aztec Labs. -pragma solidity >=0.8.18; - -// Libraries -import {DataStructures} from "./DataStructures.sol"; -import {Errors} from "./Errors.sol"; - -/** - * @title MessageBox - * @author Aztec Labs - * @notice Library that implements multi-set logic for a mapping of entries (DataStructures.Entry) - * Allows for inserting, consuming, checking existence and fetching entries - * @dev This library is used by `Inbox` and `Outbox` to store messages - * @dev Allow passing of `_err` functions to allow for custom error messages dependent on the context of use - */ -library MessageBox { - /** - * @notice Inserts an entry into the MessageBox (multi-set) - * @dev Will increment the count of the entry if it already exists - * Will revert if the entry already exists with different fee or deadline - * @param _self - The storage mapping containing all entries - * @param _entryKey - The key to insert - * @param _fee - The fee to insert - * @param _deadline - The deadline to insert - * @param _err - A function taking _entryKey, _fee, _deadline as params that MUST revert with a error reason - * @dev The _err function is passed as a param to allow for custom error messages dependent on the context of use - * We use it to allow `Inbox` and `Outbox` to throw distinct errors - */ - function insert( - mapping(bytes32 entryKey => DataStructures.Entry entry) storage _self, - bytes32 _entryKey, - uint64 _fee, - uint32 _version, - uint32 _deadline, - function( - bytes32, - uint64, - uint64, - uint32, - uint32, - uint32, - uint32 - ) pure _err - ) internal { - DataStructures.Entry memory entry = _self[_entryKey]; - if ( - (entry.fee != 0 && entry.fee != _fee) || (entry.deadline != 0 && entry.deadline != _deadline) - || (entry.version != 0 && entry.version != _version) - ) { - // this should never happen as it is trying to overwrite `fee`, `version` and `deadline` with different values - // even though the entryKey (a hash) is the same! Pass all arguments to the error message for debugging. - _err(_entryKey, entry.fee, _fee, entry.version, _version, entry.deadline, _deadline); - } - entry.count += 1; - entry.fee = _fee; - entry.version = _version; - entry.deadline = _deadline; - _self[_entryKey] = entry; - } - - /** - * @notice Consume an entry if possible, reverts if nothing to consume - * @dev For multiplicity > 1, will consume one element - * @param _self - The storage mapping containing all entries - * @param _entryKey - The key to consume - * @param _err - A function taking _entryKey as param that MUST revert with a error reason - * @dev The _err function is passed as a param to allow for custom error messages dependent on the context of use - * We use it to allow `Inbox` and `Outbox` to throw distinct errors - */ - function consume( - mapping(bytes32 entryKey => DataStructures.Entry entry) storage _self, - bytes32 _entryKey, - function(bytes32) view _err - ) internal { - DataStructures.Entry storage entry = _self[_entryKey]; - if (entry.count == 0) _err(_entryKey); - entry.count--; - } - - /** - * @notice Check if an entry exists - * @param _self - The storage mapping containing all entries - * @param _entryKey - The key to lookup - * @return True if the entry exists, false otherwise - */ - function contains( - mapping(bytes32 entryKey => DataStructures.Entry entry) storage _self, - bytes32 _entryKey - ) internal view returns (bool) { - return _self[_entryKey].count > 0; - } - - /** - * @notice Fetch an entry - * @dev Will revert if the entry does not exist - * @param _self - The storage mapping containing all entries - * @param _entryKey - The key to lookup - * @param _err - A function taking _entryKey as param that MUST revert with a error reason - * @dev The _err function is passed as a param to allow for custom error messages dependent on the context of use - * We use it to allow `Inbox` and `Outbox` to throw distinct errors - * @return The entry matching the provided key - */ - function get( - mapping(bytes32 entryKey => DataStructures.Entry entry) storage _self, - bytes32 _entryKey, - function(bytes32) view _err - ) internal view returns (DataStructures.Entry memory) { - DataStructures.Entry memory entry = _self[_entryKey]; - if (entry.count == 0) _err(_entryKey); - return entry; - } -} diff --git a/l1-contracts/src/core/messagebridge/Inbox.sol b/l1-contracts/src/core/messagebridge/Inbox.sol index aa1a2959fe5..aaf5476a163 100644 --- a/l1-contracts/src/core/messagebridge/Inbox.sol +++ b/l1-contracts/src/core/messagebridge/Inbox.sol @@ -52,11 +52,11 @@ contract Inbox is IInbox { /** * @notice Inserts a new message into the Inbox - * @dev Emits `LeafInserted` with data for easy access by the sequencer + * @dev Emits `MessageSent` with data for easy access by the sequencer * @param _recipient - The recipient of the message * @param _content - The content of the message (application specific) * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on L2) - * @return The key of the message in the set + * @return Hash of the sent message. */ function sendL2Message( DataStructures.L2Actor memory _recipient, @@ -89,7 +89,7 @@ contract Inbox is IInbox { bytes32 leaf = message.sha256ToField(); uint256 index = currentTree.insertLeaf(leaf); - emit LeafInserted(inProgress, index, leaf); + emit MessageSent(inProgress, index, leaf); return leaf; } diff --git a/l1-contracts/test/Inbox.t.sol b/l1-contracts/test/Inbox.t.sol index a9f02c7f6a5..e7a0ca5af33 100644 --- a/l1-contracts/test/Inbox.t.sol +++ b/l1-contracts/test/Inbox.t.sol @@ -81,7 +81,7 @@ contract InboxTest is Test { bytes32 leaf = message.sha256ToField(); vm.expectEmit(true, true, true, true); // event we expect - emit IInbox.LeafInserted(FIRST_REAL_TREE_NUM, 0, leaf); + emit IInbox.MessageSent(FIRST_REAL_TREE_NUM, 0, leaf); // event we will get bytes32 insertedLeaf = inbox.sendL2Message(message.recipient, message.content, message.secretHash); diff --git a/l1-contracts/test/Registry.t.sol b/l1-contracts/test/Registry.t.sol index 49a6921f376..4bb4f44ddaf 100644 --- a/l1-contracts/test/Registry.t.sol +++ b/l1-contracts/test/Registry.t.sol @@ -9,7 +9,6 @@ import {Registry} from "../src/core/messagebridge/Registry.sol"; import {Errors} from "../src/core/libraries/Errors.sol"; import {DataStructures} from "../src/core/libraries/DataStructures.sol"; -import {MessageBox} from "../src/core/libraries/MessageBox.sol"; contract RegistryTest is Test { address internal constant DEAD = address(0xdead); diff --git a/l1-contracts/test/portals/TokenPortal.t.sol b/l1-contracts/test/portals/TokenPortal.t.sol index 8ec35f3db7d..550afbe5bc8 100644 --- a/l1-contracts/test/portals/TokenPortal.t.sol +++ b/l1-contracts/test/portals/TokenPortal.t.sol @@ -26,7 +26,7 @@ contract TokenPortalTest is Test { uint256 internal constant FIRST_REAL_TREE_NUM = Constants.INITIAL_L2_BLOCK_NUM + 1; - event MessageConsumed(bytes32 indexed entryKey, address indexed recipient); + event MessageConsumed(bytes32 indexed messageHash, address indexed recipient); Registry internal registry; @@ -114,7 +114,7 @@ contract TokenPortalTest is Test { // Check the event was emitted vm.expectEmit(true, true, true, true); // event we expect - emit IInbox.LeafInserted(FIRST_REAL_TREE_NUM, 0, expectedLeaf); + emit IInbox.MessageSent(FIRST_REAL_TREE_NUM, 0, expectedLeaf); // event we will get // Perform op @@ -139,7 +139,7 @@ contract TokenPortalTest is Test { // Check the event was emitted vm.expectEmit(true, true, true, true); // event we expect - emit IInbox.LeafInserted(FIRST_REAL_TREE_NUM, 0, expectedLeaf); + emit IInbox.MessageSent(FIRST_REAL_TREE_NUM, 0, expectedLeaf); // Perform op bytes32 leaf = tokenPortal.depositToAztecPublic(to, amount, secretHashForL2MessageConsumption); diff --git a/l1-contracts/test/portals/UniswapPortal.sol b/l1-contracts/test/portals/UniswapPortal.sol index 8eb22e31163..2fad905b7e9 100644 --- a/l1-contracts/test/portals/UniswapPortal.sol +++ b/l1-contracts/test/portals/UniswapPortal.sol @@ -53,7 +53,7 @@ contract UniswapPortal { * @param _aztecRecipient - The aztec address to receive the output assets * @param _secretHashForL1ToL2Message - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a Field element) * @param _withCaller - When true, using `msg.sender` as the caller, otherwise address(0) - * @return The entryKey of the deposit transaction in the Inbox + * @return A hash of the L1 to L2 message inserted in the Inbox */ function swapPublic( address _inputTokenPortal, @@ -160,7 +160,7 @@ contract UniswapPortal { * @param _secretHashForRedeemingMintedNotes - The hash of the secret to redeem minted notes privately on Aztec. The hash should be 254 bits (so it can fit in a Field element) * @param _secretHashForL1ToL2Message - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a Field element) * @param _withCaller - When true, using `msg.sender` as the caller, otherwise address(0) - * @return The entryKey of the deposit transaction in the Inbox + * @return A hash of the L1 to L2 message inserted in the Inbox */ function swapPrivate( address _inputTokenPortal, diff --git a/l1-contracts/test/portals/UniswapPortal.t.sol b/l1-contracts/test/portals/UniswapPortal.t.sol index d1abc1de5e6..b525e78a494 100644 --- a/l1-contracts/test/portals/UniswapPortal.t.sol +++ b/l1-contracts/test/portals/UniswapPortal.t.sol @@ -23,8 +23,6 @@ import {UniswapPortal} from "./UniswapPortal.sol"; contract UniswapPortalTest is Test { using Hash for DataStructures.L2ToL1Msg; - event L1ToL2MessageCancelled(bytes32 indexed entryKey); - IERC20 public constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 public constant WETH9 = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); @@ -152,14 +150,14 @@ contract UniswapPortalTest is Test { } function _addMessagesToOutbox( - bytes32 daiWithdrawEntryKey, - bytes32 swapEntryKey, + bytes32 daiWithdrawMessageHash, + bytes32 swapMessageHash, uint256 _l2BlockNumber ) internal returns (bytes32, bytes32[] memory, bytes32[] memory) { uint256 treeHeight = 1; NaiveMerkle tree = new NaiveMerkle(treeHeight); - tree.insertLeaf(daiWithdrawEntryKey); - tree.insertLeaf(swapEntryKey); + tree.insertLeaf(daiWithdrawMessageHash); + tree.insertLeaf(swapMessageHash); bytes32 treeRoot = tree.computeRoot(); (bytes32[] memory withdrawSiblingPath,) = tree.computeSiblingPath(0); @@ -286,14 +284,14 @@ contract UniswapPortalTest is Test { function testRevertIfSwapParamsDifferentToOutboxMessage() public { uint256 l2BlockNumber = 69; - bytes32 daiWithdrawEntryKey = + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); - bytes32 swapEntryKey = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); + bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = - _addMessagesToOutbox(daiWithdrawEntryKey, swapEntryKey, l2BlockNumber); + _addMessagesToOutbox(daiWithdrawMessageHash, swapMessageHash, l2BlockNumber); bytes32 newAztecRecipient = bytes32(uint256(0x4)); - bytes32 entryKeyPortalChecksAgainst = + bytes32 messageHashPortalChecksAgainst = _createUniswapSwapMessagePublic(newAztecRecipient, address(this)); bytes32 actualRoot; @@ -302,13 +300,13 @@ contract UniswapPortalTest is Test { { uint256 treeHeight = 1; NaiveMerkle tree1 = new NaiveMerkle(treeHeight); - tree1.insertLeaf(daiWithdrawEntryKey); - tree1.insertLeaf(swapEntryKey); + tree1.insertLeaf(daiWithdrawMessageHash); + tree1.insertLeaf(swapMessageHash); actualRoot = tree1.computeRoot(); NaiveMerkle tree2 = new NaiveMerkle(treeHeight); - tree2.insertLeaf(daiWithdrawEntryKey); - tree2.insertLeaf(entryKeyPortalChecksAgainst); + tree2.insertLeaf(daiWithdrawMessageHash); + tree2.insertLeaf(messageHashPortalChecksAgainst); consumedRoot = tree2.computeRoot(); } @@ -317,7 +315,7 @@ contract UniswapPortalTest is Test { Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, - entryKeyPortalChecksAgainst, + messageHashPortalChecksAgainst, 1 ) ); @@ -351,12 +349,12 @@ contract UniswapPortalTest is Test { function testSwapWithDesignatedCaller() public { uint256 l2BlockNumber = 69; - bytes32 daiWithdrawEntryKey = + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); - bytes32 swapEntryKey = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); + bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = - _addMessagesToOutbox(daiWithdrawEntryKey, swapEntryKey, l2BlockNumber); + _addMessagesToOutbox(daiWithdrawMessageHash, swapMessageHash, l2BlockNumber); PortalDataStructures.OutboxMessageMetadata[2] memory outboxMessageMetadata = [ PortalDataStructures.OutboxMessageMetadata({ @@ -397,13 +395,13 @@ contract UniswapPortalTest is Test { vm.assume(_caller != address(uniswapPortal)); uint256 l2BlockNumber = 69; - bytes32 daiWithdrawEntryKey = + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); // don't set caller on swapPublic() -> so anyone can call this method. - bytes32 swapEntryKey = _createUniswapSwapMessagePublic(aztecRecipient, address(0)); + bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(0)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = - _addMessagesToOutbox(daiWithdrawEntryKey, swapEntryKey, l2BlockNumber); + _addMessagesToOutbox(daiWithdrawMessageHash, swapMessageHash, l2BlockNumber); PortalDataStructures.OutboxMessageMetadata[2] memory outboxMessageMetadata = [ PortalDataStructures.OutboxMessageMetadata({ @@ -445,12 +443,12 @@ contract UniswapPortalTest is Test { vm.assume(_caller != address(this)); uint256 l2BlockNumber = 69; - bytes32 daiWithdrawEntryKey = + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); - bytes32 swapEntryKey = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); + bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = - _addMessagesToOutbox(daiWithdrawEntryKey, swapEntryKey, l2BlockNumber); + _addMessagesToOutbox(daiWithdrawMessageHash, swapMessageHash, l2BlockNumber); PortalDataStructures.OutboxMessageMetadata[2] memory outboxMessageMetadata = [ PortalDataStructures.OutboxMessageMetadata({ @@ -466,7 +464,8 @@ contract UniswapPortalTest is Test { ]; vm.startPrank(_caller); - bytes32 entryKeyPortalChecksAgainst = _createUniswapSwapMessagePublic(aztecRecipient, _caller); + bytes32 messageHashPortalChecksAgainst = + _createUniswapSwapMessagePublic(aztecRecipient, _caller); bytes32 actualRoot; bytes32 consumedRoot; @@ -474,13 +473,13 @@ contract UniswapPortalTest is Test { { uint256 treeHeight = 1; NaiveMerkle tree1 = new NaiveMerkle(treeHeight); - tree1.insertLeaf(daiWithdrawEntryKey); - tree1.insertLeaf(swapEntryKey); + tree1.insertLeaf(daiWithdrawMessageHash); + tree1.insertLeaf(swapMessageHash); actualRoot = tree1.computeRoot(); NaiveMerkle tree2 = new NaiveMerkle(treeHeight); - tree2.insertLeaf(daiWithdrawEntryKey); - tree2.insertLeaf(entryKeyPortalChecksAgainst); + tree2.insertLeaf(daiWithdrawMessageHash); + tree2.insertLeaf(messageHashPortalChecksAgainst); consumedRoot = tree2.computeRoot(); } @@ -489,7 +488,7 @@ contract UniswapPortalTest is Test { Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, - entryKeyPortalChecksAgainst, + messageHashPortalChecksAgainst, 1 ) ); @@ -506,18 +505,18 @@ contract UniswapPortalTest is Test { outboxMessageMetadata ); - entryKeyPortalChecksAgainst = _createUniswapSwapMessagePublic(aztecRecipient, address(0)); + messageHashPortalChecksAgainst = _createUniswapSwapMessagePublic(aztecRecipient, address(0)); { uint256 treeHeight = 1; NaiveMerkle tree1 = new NaiveMerkle(treeHeight); - tree1.insertLeaf(daiWithdrawEntryKey); - tree1.insertLeaf(swapEntryKey); + tree1.insertLeaf(daiWithdrawMessageHash); + tree1.insertLeaf(swapMessageHash); actualRoot = tree1.computeRoot(); NaiveMerkle tree2 = new NaiveMerkle(treeHeight); - tree2.insertLeaf(daiWithdrawEntryKey); - tree2.insertLeaf(entryKeyPortalChecksAgainst); + tree2.insertLeaf(daiWithdrawMessageHash); + tree2.insertLeaf(messageHashPortalChecksAgainst); consumedRoot = tree2.computeRoot(); } vm.expectRevert( @@ -525,7 +524,7 @@ contract UniswapPortalTest is Test { Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, - entryKeyPortalChecksAgainst, + messageHashPortalChecksAgainst, 1 ) ); @@ -546,13 +545,13 @@ contract UniswapPortalTest is Test { function testRevertIfSwapMessageWasForDifferentPublicOrPrivateFlow() public { uint256 l2BlockNumber = 69; - bytes32 daiWithdrawEntryKey = + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); // Create message for `_isPrivateFlow`: - bytes32 swapEntryKey = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); + bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = - _addMessagesToOutbox(daiWithdrawEntryKey, swapEntryKey, l2BlockNumber); + _addMessagesToOutbox(daiWithdrawMessageHash, swapMessageHash, l2BlockNumber); PortalDataStructures.OutboxMessageMetadata[2] memory outboxMessageMetadata = [ PortalDataStructures.OutboxMessageMetadata({ @@ -567,7 +566,7 @@ contract UniswapPortalTest is Test { }) ]; - bytes32 entryKeyPortalChecksAgainst = + bytes32 messageHashPortalChecksAgainst = _createUniswapSwapMessagePrivate(secretHashForRedeemingMintedNotes, address(this)); bytes32 actualRoot; @@ -576,13 +575,13 @@ contract UniswapPortalTest is Test { { uint256 treeHeight = 1; NaiveMerkle tree1 = new NaiveMerkle(treeHeight); - tree1.insertLeaf(daiWithdrawEntryKey); - tree1.insertLeaf(swapEntryKey); + tree1.insertLeaf(daiWithdrawMessageHash); + tree1.insertLeaf(swapMessageHash); actualRoot = tree1.computeRoot(); NaiveMerkle tree2 = new NaiveMerkle(treeHeight); - tree2.insertLeaf(daiWithdrawEntryKey); - tree2.insertLeaf(entryKeyPortalChecksAgainst); + tree2.insertLeaf(daiWithdrawMessageHash); + tree2.insertLeaf(messageHashPortalChecksAgainst); consumedRoot = tree2.computeRoot(); } @@ -591,7 +590,7 @@ contract UniswapPortalTest is Test { Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, - entryKeyPortalChecksAgainst, + messageHashPortalChecksAgainst, 1 ) ); diff --git a/noir-projects/aztec-nr/aztec/src/messaging.nr b/noir-projects/aztec-nr/aztec/src/messaging.nr index 958a5e863f4..4cfe82baa0c 100644 --- a/noir-projects/aztec-nr/aztec/src/messaging.nr +++ b/noir-projects/aztec-nr/aztec/src/messaging.nr @@ -23,15 +23,15 @@ pub fn process_l1_to_l2_message( content, secret ); - let entry_key = msg.hash(); + let message_hash = msg.hash(); - let returned_message = get_l1_to_l2_membership_witness(entry_key); + let returned_message = get_l1_to_l2_membership_witness(message_hash); let leaf_index = returned_message[0]; let sibling_path = arr_copy_slice(returned_message, [0; L1_TO_L2_MSG_TREE_HEIGHT], 1); // Check that the message is in the tree // This is implicitly checking that the values of the message are correct - let root = compute_merkle_root(entry_key, leaf_index, sibling_path); + let root = compute_merkle_root(message_hash, leaf_index, sibling_path); assert(root == l1_to_l2_root, "Message not in state"); msg.compute_nullifier() diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr index de73fca0c49..0f9e98eeaa9 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr @@ -1,9 +1,9 @@ use dep::protocol_types::constants::L1_TO_L2_MESSAGE_ORACLE_CALL_LENGTH; -// Checks if a msg is within the l1ToL2Msg tree +// Obtains membership witness (index and sibling path) for a message in the L1 to L2 message tree. #[oracle(getL1ToL2MembershipWitness)] -fn get_l1_to_l2_membership_witness_oracle(_entry_key: Field) -> [Field; L1_TO_L2_MESSAGE_ORACLE_CALL_LENGTH] {} +fn get_l1_to_l2_membership_witness_oracle(_message_hash: Field) -> [Field; L1_TO_L2_MESSAGE_ORACLE_CALL_LENGTH] {} -unconstrained pub fn get_l1_to_l2_membership_witness(entry_key: Field) -> [Field; L1_TO_L2_MESSAGE_ORACLE_CALL_LENGTH] { - get_l1_to_l2_membership_witness_oracle(entry_key) +unconstrained pub fn get_l1_to_l2_membership_witness(message_hash: Field) -> [Field; L1_TO_L2_MESSAGE_ORACLE_CALL_LENGTH] { + get_l1_to_l2_membership_witness_oracle(message_hash) } diff --git a/yarn-project/archiver/src/archiver/archiver.test.ts b/yarn-project/archiver/src/archiver/archiver.test.ts index 7754448a3f0..48471c74aa3 100644 --- a/yarn-project/archiver/src/archiver/archiver.test.ts +++ b/yarn-project/archiver/src/archiver/archiver.test.ts @@ -46,14 +46,14 @@ describe('Archiver', () => { publicClient.getBlockNumber.mockResolvedValueOnce(2500n).mockResolvedValueOnce(2600n).mockResolvedValueOnce(2700n); // logs should be created in order of how archiver syncs. publicClient.getLogs - .mockResolvedValueOnce([makeLeafInsertedEvent(98n, 1n, 0n), makeLeafInsertedEvent(99n, 1n, 1n)]) + .mockResolvedValueOnce([makeMessageSentEvent(98n, 1n, 0n), makeMessageSentEvent(99n, 1n, 1n)]) .mockResolvedValueOnce([makeTxsPublishedEvent(101n, blocks[0].body.getTxsEffectsHash())]) .mockResolvedValueOnce([makeL2BlockProcessedEvent(101n, 1n)]) .mockResolvedValueOnce([ - makeLeafInsertedEvent(2504n, 2n, 0n), - makeLeafInsertedEvent(2505n, 2n, 1n), - makeLeafInsertedEvent(2505n, 2n, 2n), - makeLeafInsertedEvent(2506n, 3n, 1n), + makeMessageSentEvent(2504n, 2n, 0n), + makeMessageSentEvent(2505n, 2n, 1n), + makeMessageSentEvent(2505n, 2n, 2n), + makeMessageSentEvent(2506n, 3n, 1n), ]) .mockResolvedValueOnce([ makeTxsPublishedEvent(2510n, blocks[1].body.getTxsEffectsHash()), @@ -142,7 +142,7 @@ describe('Archiver', () => { publicClient.getBlockNumber.mockResolvedValue(102n); // add all of the L1 to L2 messages to the mock publicClient.getLogs - .mockResolvedValueOnce([makeLeafInsertedEvent(66n, 1n, 0n), makeLeafInsertedEvent(68n, 1n, 1n)]) + .mockResolvedValueOnce([makeMessageSentEvent(66n, 1n, 0n), makeMessageSentEvent(68n, 1n, 1n)]) .mockResolvedValueOnce([ makeTxsPublishedEvent(70n, blocks[0].body.getTxsEffectsHash()), makeTxsPublishedEvent(80n, blocks[1].body.getTxsEffectsHash()), @@ -196,21 +196,21 @@ function makeTxsPublishedEvent(l1BlockNum: bigint, txsEffectsHash: Buffer) { } /** - * Makes fake L1ToL2 LeafInserted events for testing purposes. + * Makes fake L1ToL2 MessageSent events for testing purposes. * @param l1BlockNum - L1 block number. - * @param l2BlockNumber - The L2 block number of the leaf inserted. - * @returns LeafInserted event logs. + * @param l2BlockNumber - The L2 block number of in which the message was included. + * @returns MessageSent event logs. */ -function makeLeafInsertedEvent(l1BlockNum: bigint, l2BlockNumber: bigint, index: bigint) { +function makeMessageSentEvent(l1BlockNum: bigint, l2BlockNumber: bigint, index: bigint) { return { blockNumber: l1BlockNum, args: { - blockNumber: l2BlockNumber, + l2BlockNumber, index, - value: Fr.random().toString(), + hash: Fr.random().toString(), }, transactionHash: `0x${l1BlockNum}`, - } as Log; + } as Log; } /** diff --git a/yarn-project/archiver/src/archiver/archiver.ts b/yarn-project/archiver/src/archiver/archiver.ts index 19760bfee3b..72eb746663b 100644 --- a/yarn-project/archiver/src/archiver/archiver.ts +++ b/yarn-project/archiver/src/archiver/archiver.ts @@ -148,10 +148,13 @@ export class Archiver implements ArchiveSource { * * This code does not handle reorgs. */ - const lastL1Blocks = await this.store.getSynchedL1BlockNumbers(); + const l1SynchPoint = await this.store.getSynchPoint(); const currentL1BlockNumber = await this.publicClient.getBlockNumber(); - if (currentL1BlockNumber <= lastL1Blocks.blocks && currentL1BlockNumber <= lastL1Blocks.messages) { + if ( + currentL1BlockNumber <= l1SynchPoint.blocksSynchedTo && + currentL1BlockNumber <= l1SynchPoint.messagesSynchedTo + ) { // chain hasn't moved forward // or it's been rolled back return; @@ -184,14 +187,14 @@ export class Archiver implements ArchiveSource { this.publicClient, this.inboxAddress, blockUntilSynced, - lastL1Blocks.messages + 1n, + l1SynchPoint.messagesSynchedTo + 1n, currentL1BlockNumber, ); if (retrievedL1ToL2Messages.retrievedData.length !== 0) { this.log( `Retrieved ${retrievedL1ToL2Messages.retrievedData.length} new L1 -> L2 messages between L1 blocks ${ - lastL1Blocks.messages + 1n + l1SynchPoint.messagesSynchedTo + 1n } and ${currentL1BlockNumber}.`, ); } @@ -205,7 +208,7 @@ export class Archiver implements ArchiveSource { this.publicClient, this.availabilityOracleAddress, blockUntilSynced, - lastL1Blocks.blocks + 1n, + l1SynchPoint.blocksSynchedTo + 1n, currentL1BlockNumber, ); @@ -220,7 +223,7 @@ export class Archiver implements ArchiveSource { this.publicClient, this.rollupAddress, blockUntilSynced, - lastL1Blocks.blocks + 1n, + l1SynchPoint.blocksSynchedTo + 1n, currentL1BlockNumber, nextExpectedL2BlockNum, ); @@ -244,7 +247,7 @@ export class Archiver implements ArchiveSource { } else { this.log( `Retrieved ${blocks.length} new L2 blocks between L1 blocks ${ - lastL1Blocks.blocks + 1n + l1SynchPoint.blocksSynchedTo + 1n } and ${currentL1BlockNumber}.`, ); } diff --git a/yarn-project/archiver/src/archiver/archiver_store.ts b/yarn-project/archiver/src/archiver/archiver_store.ts index 20793bb76bc..2adacfa03ee 100644 --- a/yarn-project/archiver/src/archiver/archiver_store.ts +++ b/yarn-project/archiver/src/archiver/archiver_store.ts @@ -20,10 +20,10 @@ import { DataRetrieval } from './data_retrieval.js'; * Represents the latest L1 block processed by the archiver for various objects in L2. */ export type ArchiverL1SynchPoint = { - /** The last L1 block that added a new L2 block. */ - blocks: bigint; - /** The last L1 block that added L1 -> L2 messages from the Inbox. */ - messages: bigint; + /** Number of the last L1 block that added a new L2 block. */ + blocksSynchedTo: bigint; + /** Number of the last L1 block that added L1 -> L2 messages from the Inbox. */ + messagesSynchedTo: bigint; }; /** @@ -134,7 +134,7 @@ export interface ArchiverDataStore { /** * Gets the synch point of the archiver */ - getSynchedL1BlockNumbers(): Promise; + getSynchPoint(): Promise; /** * Add new contract classes from an L2 block to the store's list. diff --git a/yarn-project/archiver/src/archiver/archiver_store_test_suite.ts b/yarn-project/archiver/src/archiver/archiver_store_test_suite.ts index 606acf74aa9..ad454ab0d6f 100644 --- a/yarn-project/archiver/src/archiver/archiver_store_test_suite.ts +++ b/yarn-project/archiver/src/archiver/archiver_store_test_suite.ts @@ -81,19 +81,19 @@ export function describeArchiverDataStore(testName: string, getStore: () => Arch }); }); - describe('getSynchedL1BlockNumbers', () => { + describe('getSynchPoint', () => { it('returns 0n if no blocks have been added', async () => { - await expect(store.getSynchedL1BlockNumbers()).resolves.toEqual({ - blocks: 0n, - messages: 0n, + await expect(store.getSynchPoint()).resolves.toEqual({ + blocksSynchedTo: 0n, + messagesSynchedTo: 0n, }); }); it('returns the L1 block number in which the most recent L2 block was published', async () => { await store.addBlocks(blocks); - await expect(store.getSynchedL1BlockNumbers()).resolves.toEqual({ - blocks: blocks.lastProcessedL1BlockNumber, - messages: 0n, + await expect(store.getSynchPoint()).resolves.toEqual({ + blocksSynchedTo: blocks.lastProcessedL1BlockNumber, + messagesSynchedTo: 0n, }); }); @@ -102,9 +102,9 @@ export function describeArchiverDataStore(testName: string, getStore: () => Arch lastProcessedL1BlockNumber: 1n, retrievedData: [new InboxLeaf(0n, 0n, Fr.ZERO)], }); - await expect(store.getSynchedL1BlockNumbers()).resolves.toEqual({ - blocks: 0n, - messages: 1n, + await expect(store.getSynchPoint()).resolves.toEqual({ + blocksSynchedTo: 0n, + messagesSynchedTo: 1n, }); }); }); diff --git a/yarn-project/archiver/src/archiver/data_retrieval.ts b/yarn-project/archiver/src/archiver/data_retrieval.ts index ec4a8820b33..86f1fc6e8bf 100644 --- a/yarn-project/archiver/src/archiver/data_retrieval.ts +++ b/yarn-project/archiver/src/archiver/data_retrieval.ts @@ -6,10 +6,10 @@ import { PublicClient } from 'viem'; import { getL2BlockProcessedLogs, - getLeafInsertedLogs, + getMessageSentLogs, getTxsPublishedLogs, processL2BlockProcessedLogs, - processLeafInsertedLogs, + processMessageSentLogs, processTxsPublishedLogs, } from './eth_log_handlers.js'; @@ -132,14 +132,14 @@ export async function retrieveL1ToL2Messages( if (searchStartBlock > searchEndBlock) { break; } - const leafInsertedLogs = await getLeafInsertedLogs(publicClient, inboxAddress, searchStartBlock, searchEndBlock); - if (leafInsertedLogs.length === 0) { + const messageSentLogs = await getMessageSentLogs(publicClient, inboxAddress, searchStartBlock, searchEndBlock); + if (messageSentLogs.length === 0) { break; } - const l1ToL2Messages = processLeafInsertedLogs(leafInsertedLogs); + const l1ToL2Messages = processMessageSentLogs(messageSentLogs); retrievedL1ToL2Messages.push(...l1ToL2Messages); // handles the case when there are no new messages: - searchStartBlock = (leafInsertedLogs.findLast(msgLog => !!msgLog)?.blockNumber || searchStartBlock) + 1n; + searchStartBlock = (messageSentLogs.findLast(msgLog => !!msgLog)?.blockNumber || searchStartBlock) + 1n; } while (blockUntilSynced && searchStartBlock <= searchEndBlock); return { lastProcessedL1BlockNumber: searchStartBlock - 1n, retrievedData: retrievedL1ToL2Messages }; } diff --git a/yarn-project/archiver/src/archiver/eth_log_handlers.ts b/yarn-project/archiver/src/archiver/eth_log_handlers.ts index c3380efd8a5..4c04f3f4410 100644 --- a/yarn-project/archiver/src/archiver/eth_log_handlers.ts +++ b/yarn-project/archiver/src/archiver/eth_log_handlers.ts @@ -8,17 +8,17 @@ import { AvailabilityOracleAbi, InboxAbi, RollupAbi } from '@aztec/l1-artifacts' import { Hex, Log, PublicClient, decodeFunctionData, getAbiItem, getAddress, hexToBytes } from 'viem'; /** - * Processes newly received LeafInserted (L1 to L2) logs. - * @param logs - LeafInserted logs. - * @returns Array of all processed LeafInserted logs + * Processes newly received MessageSent (L1 to L2) logs. + * @param logs - MessageSent logs. + * @returns Array of all processed MessageSent logs */ -export function processLeafInsertedLogs( - logs: Log[], +export function processMessageSentLogs( + logs: Log[], ): InboxLeaf[] { const leaves: InboxLeaf[] = []; for (const log of logs) { - const { blockNumber, index, value } = log.args; - leaves.push(new InboxLeaf(blockNumber, index, Fr.fromString(value))); + const { l2BlockNumber, index, hash } = log.args; + leaves.push(new InboxLeaf(l2BlockNumber, index, Fr.fromString(hash))); } return leaves; } @@ -191,24 +191,24 @@ export function getTxsPublishedLogs( } /** - * Get relevant `LeafInserted` logs emitted by Inbox on chain. + * Get relevant `MessageSent` logs emitted by Inbox on chain. * @param publicClient - The viem public client to use for transaction retrieval. * @param inboxAddress - The address of the inbox contract. * @param fromBlock - First block to get logs from (inclusive). * @param toBlock - Last block to get logs from (inclusive). - * @returns An array of `LeafInserted` logs. + * @returns An array of `MessageSent` logs. */ -export function getLeafInsertedLogs( +export function getMessageSentLogs( publicClient: PublicClient, inboxAddress: EthAddress, fromBlock: bigint, toBlock: bigint, -): Promise[]> { +): Promise[]> { return publicClient.getLogs({ address: getAddress(inboxAddress.toString()), event: getAbiItem({ abi: InboxAbi, - name: 'LeafInserted', + name: 'MessageSent', }), fromBlock, toBlock: toBlock + 1n, // the toBlock argument in getLogs is exclusive diff --git a/yarn-project/archiver/src/archiver/kv_archiver_store/kv_archiver_store.ts b/yarn-project/archiver/src/archiver/kv_archiver_store/kv_archiver_store.ts index b5d9fa6fc36..e183b68076b 100644 --- a/yarn-project/archiver/src/archiver/kv_archiver_store/kv_archiver_store.ts +++ b/yarn-project/archiver/src/archiver/kv_archiver_store/kv_archiver_store.ts @@ -214,12 +214,10 @@ export class KVArchiverDataStore implements ArchiverDataStore { /** * Gets the last L1 block number processed by the archiver */ - getSynchedL1BlockNumbers(): Promise { - const blocks = this.#blockStore.getSynchedL1BlockNumber(); - const messages = this.#messageStore.getSynchedL1BlockNumber(); + getSynchPoint(): Promise { return Promise.resolve({ - blocks, - messages, + blocksSynchedTo: this.#blockStore.getSynchedL1BlockNumber(), + messagesSynchedTo: this.#messageStore.getSynchedL1BlockNumber(), }); } } diff --git a/yarn-project/archiver/src/archiver/memory_archiver_store/l1_to_l2_message_store.ts b/yarn-project/archiver/src/archiver/memory_archiver_store/l1_to_l2_message_store.ts index 3cae18ea47b..cec550cec18 100644 --- a/yarn-project/archiver/src/archiver/memory_archiver_store/l1_to_l2_message_store.ts +++ b/yarn-project/archiver/src/archiver/memory_archiver_store/l1_to_l2_message_store.ts @@ -11,8 +11,7 @@ import { Fr } from '@aztec/foundation/fields'; */ export class L1ToL2MessageStore { /** - * A map containing the entry key to the corresponding L1 to L2 - * messages (and the number of times the message has been seen). + * A map pointing from a key in a "blockNum-messageIndex" format to the corresponding L1 to L2 message hash. */ protected store: Map = new Map(); diff --git a/yarn-project/archiver/src/archiver/memory_archiver_store/memory_archiver_store.ts b/yarn-project/archiver/src/archiver/memory_archiver_store/memory_archiver_store.ts index ae701859282..12c8922e0b2 100644 --- a/yarn-project/archiver/src/archiver/memory_archiver_store/memory_archiver_store.ts +++ b/yarn-project/archiver/src/archiver/memory_archiver_store/memory_archiver_store.ts @@ -357,10 +357,10 @@ export class MemoryArchiverStore implements ArchiverDataStore { return Promise.resolve(this.l2BlockContexts[this.l2BlockContexts.length - 1].block.number); } - public getSynchedL1BlockNumbers(): Promise { + public getSynchPoint(): Promise { return Promise.resolve({ - blocks: this.lastL1BlockNewBlocks, - messages: this.lastL1BlockNewMessages, + blocksSynchedTo: this.lastL1BlockNewBlocks, + messagesSynchedTo: this.lastL1BlockNewMessages, }); } } diff --git a/yarn-project/aztec-node/src/aztec-node/server.ts b/yarn-project/aztec-node/src/aztec-node/server.ts index 43a1aefd8bc..657668e07e4 100644 --- a/yarn-project/aztec-node/src/aztec-node/server.ts +++ b/yarn-project/aztec-node/src/aztec-node/server.ts @@ -424,10 +424,10 @@ export class AztecNodeService implements AztecNode { * @param l2ToL1Message - The l2ToL1Message get the index / sibling path for. * @returns A tuple of the index and the sibling path of the L2ToL1Message. */ - public async getL2ToL1MessageIndexAndSiblingPath( + public async getL2ToL1MessageMembershipWitness( blockNumber: L2BlockNumber, l2ToL1Message: Fr, - ): Promise<[number, SiblingPath]> { + ): Promise<[bigint, SiblingPath]> { const block = await this.blockSource.getBlock(blockNumber === 'latest' ? await this.getBlockNumber() : blockNumber); if (block === undefined) { @@ -440,11 +440,11 @@ export class AztecNodeService implements AztecNode { throw new Error('L2 to L1 Messages are not padded'); } - const indexOfL2ToL1Message = l2ToL1Messages.findIndex(l2ToL1MessageInBlock => - l2ToL1MessageInBlock.equals(l2ToL1Message), + const indexOfL2ToL1Message = BigInt( + l2ToL1Messages.findIndex(l2ToL1MessageInBlock => l2ToL1MessageInBlock.equals(l2ToL1Message)), ); - if (indexOfL2ToL1Message === -1) { + if (indexOfL2ToL1Message === -1n) { throw new Error('The L2ToL1Message you are trying to prove inclusion of does not exist'); } @@ -453,7 +453,7 @@ export class AztecNodeService implements AztecNode { const tree = new StandardTree(openTmpStore(true), new SHA256Trunc(), 'temp_outhash_sibling_path', treeHeight); await tree.appendLeaves(l2ToL1Messages.map(l2ToL1Msg => l2ToL1Msg.toBuffer())); - return [indexOfL2ToL1Message, await tree.getSiblingPath(BigInt(indexOfL2ToL1Message), true)]; + return [indexOfL2ToL1Message, await tree.getSiblingPath(indexOfL2ToL1Message, true)]; } /** diff --git a/yarn-project/circuit-types/src/interfaces/aztec-node.ts b/yarn-project/circuit-types/src/interfaces/aztec-node.ts index 619208b8400..738692cf30a 100644 --- a/yarn-project/circuit-types/src/interfaces/aztec-node.ts +++ b/yarn-project/circuit-types/src/interfaces/aztec-node.ts @@ -77,18 +77,19 @@ export interface AztecNode { isL1ToL2MessageSynced(l1ToL2Message: Fr): Promise; /** - * Returns the index of a l2ToL1Message in a ephemeral l2 to l1 data tree as well as its sibling path. + * Returns a membership witness of an l2ToL1Message in an ephemeral l2 to l1 message tree. + * @dev Membership witness is a consists of the index and the sibling path of the l2ToL1Message. * @remarks This tree is considered ephemeral because it is created on-demand by: taking all the l2ToL1 messages * in a single block, and then using them to make a variable depth append-only tree with these messages as leaves. * The tree is discarded immediately after calculating what we need from it. * @param blockNumber - The block number at which to get the data. - * @param l2ToL1Message - The l2ToL1Message get the index / sibling path for. + * @param l2ToL1Message - The l2ToL1Message to get the membership witness for. * @returns A tuple of the index and the sibling path of the L2ToL1Message. */ - getL2ToL1MessageIndexAndSiblingPath( + getL2ToL1MessageMembershipWitness( blockNumber: L2BlockNumber, l2ToL1Message: Fr, - ): Promise<[number, SiblingPath]>; + ): Promise<[bigint, SiblingPath]>; /** * Returns a sibling path for a leaf in the committed historic blocks tree. diff --git a/yarn-project/circuit-types/src/messaging/inbox_leaf.ts b/yarn-project/circuit-types/src/messaging/inbox_leaf.ts index eff95b07d0a..f0b507cfb92 100644 --- a/yarn-project/circuit-types/src/messaging/inbox_leaf.ts +++ b/yarn-project/circuit-types/src/messaging/inbox_leaf.ts @@ -8,7 +8,7 @@ export class InboxLeaf { public readonly blockNumber: bigint, /** Index of the leaf in L2 block message subtree. */ public readonly index: bigint, - /** Leaf in the subtree. */ + /** Leaf in the subtree/message hash. */ public readonly leaf: Fr, ) {} diff --git a/yarn-project/circuit-types/src/messaging/l1_to_l2_message.ts b/yarn-project/circuit-types/src/messaging/l1_to_l2_message.ts index 248162c52ce..491ba12e26e 100644 --- a/yarn-project/circuit-types/src/messaging/l1_to_l2_message.ts +++ b/yarn-project/circuit-types/src/messaging/l1_to_l2_message.ts @@ -26,10 +26,6 @@ export class L1ToL2Message { * The hash of the spending secret. */ public readonly secretHash: Fr, - /** - * The entry key for the message - optional. - */ - public readonly entryKey?: Fr, ) {} /** @@ -70,7 +66,7 @@ export class L1ToL2Message { return new L1ToL2Message(L1Actor.empty(), L2Actor.empty(), Fr.ZERO, Fr.ZERO); } - static random(entryKey?: Fr): L1ToL2Message { - return new L1ToL2Message(L1Actor.random(), L2Actor.random(), Fr.random(), Fr.random(), entryKey); + static random(): L1ToL2Message { + return new L1ToL2Message(L1Actor.random(), L2Actor.random(), Fr.random(), Fr.random()); } } diff --git a/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts b/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts index d337897f3bd..c87579abff7 100644 --- a/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts @@ -82,14 +82,14 @@ describe('e2e_cross_chain_messaging', () => { await crossChainTestHarness.mintTokensOnL1(l1TokenBalance); // 2. Deposit tokens to the TokenPortal - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPrivate( + const msgHash = await crossChainTestHarness.sendTokensToPortalPrivate( secretHashForRedeemingMintedNotes, bridgeAmount, secretHashForL2MessageConsumption, ); expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(l1TokenBalance - bridgeAmount); - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); // 3. Consume L1 -> L2 message and mint private tokens on L2 await crossChainTestHarness.consumeMessageOnAztecAndMintPrivately( @@ -119,7 +119,7 @@ describe('e2e_cross_chain_messaging', () => { const l2TxReceipt = await crossChainTestHarness.withdrawPrivateFromAztecToL1(withdrawAmount, nonce); await crossChainTestHarness.expectPrivateBalanceOnL2(ownerAddress, bridgeAmount - withdrawAmount); - const [l2ToL1MessageIndex, siblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [l2ToL1MessageIndex, siblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( l2TxReceipt.blockNumber!, l2ToL1Message, ); @@ -146,7 +146,7 @@ describe('e2e_cross_chain_messaging', () => { crossChainTestHarness.generateClaimSecret(); await crossChainTestHarness.mintTokensOnL1(l1TokenBalance); - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPrivate( + const msgHash = await crossChainTestHarness.sendTokensToPortalPrivate( secretHashForRedeemingMintedNotes, bridgeAmount, secretHashForL2MessageConsumption, @@ -154,7 +154,7 @@ describe('e2e_cross_chain_messaging', () => { expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(l1TokenBalance - bridgeAmount); // Wait for the message to be available for consumption - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); // 3. Consume L1 -> L2 message and mint private tokens on L2 const content = toTruncField( @@ -178,7 +178,7 @@ describe('e2e_cross_chain_messaging', () => { .withWallet(user2Wallet) .methods.claim_private(secretHashForL2MessageConsumption, bridgeAmount, secretForL2MessageConsumption) .simulate(), - ).rejects.toThrow(`No L1 to L2 message found for entry key ${wrongMessage.hash().toString()}`); + ).rejects.toThrow(`No L1 to L2 message found for message hash ${wrongMessage.hash().toString()}`); // send the right one - const consumptionReceipt = await l2Bridge @@ -227,7 +227,7 @@ describe('e2e_cross_chain_messaging', () => { const [secretForL2MessageConsumption, secretHashForL2MessageConsumption] = crossChainTestHarness.generateClaimSecret(); - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPrivate( + const msgHash = await crossChainTestHarness.sendTokensToPortalPrivate( Fr.random(), bridgeAmount, secretHashForL2MessageConsumption, @@ -235,7 +235,7 @@ describe('e2e_cross_chain_messaging', () => { expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(0n); // Wait for the message to be available for consumption - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); const content = toTruncField( sha256( diff --git a/yarn-project/end-to-end/src/e2e_outbox.test.ts b/yarn-project/end-to-end/src/e2e_outbox.test.ts index 98f1f3e655e..ca3dd3af8b3 100644 --- a/yarn-project/end-to-end/src/e2e_outbox.test.ts +++ b/yarn-project/end-to-end/src/e2e_outbox.test.ts @@ -67,36 +67,36 @@ describe('E2E Outbox Tests', () => { // the index to match the order of the block we obtained earlier. We also then use this sibling path to hash up to the root, // verifying that the expected root obtained through the message and the sibling path match the actual root // that was returned by the circuits in the header as out_hash. - const [index, siblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [index, siblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( txReceipt.blockNumber!, l2ToL1Messages![0], ); expect(siblingPath.pathSize).toBe(2); - expect(index).toBe(0); + expect(index).toBe(0n); const expectedRoot = calculateExpectedRoot(l2ToL1Messages![0], siblingPath as SiblingPath<2>, index); expect(expectedRoot.toString('hex')).toEqual(block?.header.contentCommitment.outHash.toString('hex')); - const [index2, siblingPath2] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [index2, siblingPath2] = await aztecNode.getL2ToL1MessageMembershipWitness( txReceipt.blockNumber!, l2ToL1Messages![1], ); expect(siblingPath2.pathSize).toBe(2); - expect(index2).toBe(1); + expect(index2).toBe(1n); const expectedRoot2 = calculateExpectedRoot(l2ToL1Messages![1], siblingPath2 as SiblingPath<2>, index2); expect(expectedRoot2.toString('hex')).toEqual(block?.header.contentCommitment.outHash.toString('hex')); }, 360_000); - function calculateExpectedRoot(l2ToL1Message: Fr, siblingPath: SiblingPath<2>, index: number): Buffer { + function calculateExpectedRoot(l2ToL1Message: Fr, siblingPath: SiblingPath<2>, index: bigint): Buffer { const firstLayerInput: [Buffer, Buffer] = - index & 0x1 + index & 0x1n ? [siblingPath.toBufferArray()[0], l2ToL1Message.toBuffer()] : [l2ToL1Message.toBuffer(), siblingPath.toBufferArray()[0]]; const firstLayer = merkleSha256.hash(...firstLayerInput); - index /= 2; + index /= 2n; // In the circuit, the 'firstLayer' is the kernel out hash, which is truncated to 31 bytes // To match the result, the below preimages and the output are truncated to 31 then padded const secondLayerInput: [Buffer, Buffer] = - index & 0x1 + index & 0x1n ? [siblingPath.toBufferArray()[1], truncateAndPad(firstLayer)] : [truncateAndPad(firstLayer), siblingPath.toBufferArray()[1]]; return truncateAndPad(merkleSha256.hash(...secondLayerInput)); diff --git a/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts b/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts index 581e2e603c4..2dbfa75bc6d 100644 --- a/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts @@ -89,11 +89,11 @@ describe('e2e_public_cross_chain_messaging', () => { await crossChainTestHarness.mintTokensOnL1(l1TokenBalance); // 2. Deposit tokens to the TokenPortal - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); + const msgHash = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(l1TokenBalance - bridgeAmount); // Wait for the message to be available for consumption - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); // 3. Consume L1 -> L2 message and mint public tokens on L2 await crossChainTestHarness.consumeMessageOnAztecAndMintPublicly(bridgeAmount, secret); @@ -122,7 +122,7 @@ describe('e2e_public_cross_chain_messaging', () => { // Check balance before and after exit. expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(l1TokenBalance - bridgeAmount); - const [l2ToL1MessageIndex, siblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [l2ToL1MessageIndex, siblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( l2TxReceipt.blockNumber!, l2ToL1Message, ); @@ -147,10 +147,10 @@ describe('e2e_public_cross_chain_messaging', () => { const [secret, secretHash] = crossChainTestHarness.generateClaimSecret(); await crossChainTestHarness.mintTokensOnL1(l1TokenBalance); - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); + const msgHash = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(l1TokenBalance - bridgeAmount); - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); const content = toTruncField( sha256( @@ -200,10 +200,10 @@ describe('e2e_public_cross_chain_messaging', () => { const [secret, secretHash] = crossChainTestHarness.generateClaimSecret(); await crossChainTestHarness.mintTokensOnL1(bridgeAmount); - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); + const msgHash = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); expect(await crossChainTestHarness.getL1BalanceOf(ethAccount)).toBe(0n); - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); // Wrong message hash const content = toTruncField( @@ -223,7 +223,7 @@ describe('e2e_public_cross_chain_messaging', () => { await expect( l2Bridge.withWallet(user2Wallet).methods.claim_private(secretHash, bridgeAmount, secret).simulate(), - ).rejects.toThrow(`No L1 to L2 message found for entry key ${wrongMessage.hash().toString()}`); + ).rejects.toThrow(`No L1 to L2 message found for message hash ${wrongMessage.hash().toString()}`); }, 60_000); // Note: We register one portal address when deploying contract but that address is no-longer the only address @@ -272,7 +272,7 @@ describe('e2e_public_cross_chain_messaging', () => { ), )[0]; - const [l2MessageIndex, siblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [l2MessageIndex, siblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( l2TxReceipt.blockNumber!, leaf, ); @@ -343,7 +343,7 @@ describe('e2e_public_cross_chain_messaging', () => { ); // We check that the message was correctly injected by checking the emitted event - const msgLeaf = message.hash(); + const msgHash = message.hash(); { const txReceipt = await crossChainTestHarness.publicClient.waitForTransactionReceipt({ hash: txHash, @@ -359,13 +359,13 @@ describe('e2e_public_cross_chain_messaging', () => { data: txLog.data, topics: txLog.topics, }); - const receivedMsgLeaf = topics.args.value; + const receivedMsgHash = topics.args.hash; // We check that the leaf inserted into the subtree matches the expected message hash - expect(receivedMsgLeaf).toBe(msgLeaf.toString()); + expect(receivedMsgHash).toBe(msgHash.toString()); } - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); // Finally, e consume the L1 -> L2 message using the test contract either from private or public if (isPrivate) { diff --git a/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts b/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts index 78473915a3e..0b67d07c67d 100644 --- a/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts @@ -48,10 +48,10 @@ describe('e2e_public_to_private_messaging', () => { const [secret, secretHash] = crossChainTestHarness.generateClaimSecret(); await crossChainTestHarness.mintTokensOnL1(l1TokenBalance); - const msgLeaf = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); + const msgHash = await crossChainTestHarness.sendTokensToPortalPublic(bridgeAmount, secretHash); expect(await underlyingERC20.read.balanceOf([ethAccount.toString()])).toBe(l1TokenBalance - bridgeAmount); - await crossChainTestHarness.makeMessageConsumable(msgLeaf); + await crossChainTestHarness.makeMessageConsumable(msgHash); await crossChainTestHarness.consumeMessageOnAztecAndMintPublicly(bridgeAmount, secret); await crossChainTestHarness.expectPublicBalanceOnL2(ownerAddress, bridgeAmount); diff --git a/yarn-project/end-to-end/src/integration_l1_publisher.test.ts b/yarn-project/end-to-end/src/integration_l1_publisher.test.ts index d6a568def0b..7dea048cdcb 100644 --- a/yarn-project/end-to-end/src/integration_l1_publisher.test.ts +++ b/yarn-project/end-to-end/src/integration_l1_publisher.test.ts @@ -215,7 +215,7 @@ describe('L1Publisher integration', () => { topics: txLog.topics, }); - return Fr.fromString(topics.args.value); + return Fr.fromString(topics.args.hash); }; /** diff --git a/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts b/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts index 0453e64f68b..5d2fbc75ada 100644 --- a/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts +++ b/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts @@ -255,13 +255,13 @@ export class CrossChainTestHarness { // Deposit tokens to the TokenPortal this.logger('Sending messages to L1 portal to be consumed publicly'); const args = [this.ownerAddress.toString(), bridgeAmount, secretHash.toString()] as const; - const { result: entryKeyHex } = await this.tokenPortal.simulate.depositToAztecPublic(args, { + const { result: messageHash } = await this.tokenPortal.simulate.depositToAztecPublic(args, { account: this.ethAccount.toString(), } as any); const txHash2 = await this.tokenPortal.write.depositToAztecPublic(args, {} as any); await this.publicClient.waitForTransactionReceipt({ hash: txHash2 }); - return Fr.fromString(entryKeyHex); + return Fr.fromString(messageHash); } async sendTokensToPortalPrivate( @@ -281,13 +281,13 @@ export class CrossChainTestHarness { bridgeAmount, secretHashForL2MessageConsumption.toString(), ] as const; - const { result: entryKeyHex } = await this.tokenPortal.simulate.depositToAztecPrivate(args, { + const { result: messageHash } = await this.tokenPortal.simulate.depositToAztecPrivate(args, { account: this.ethAccount.toString(), } as any); const txHash2 = await this.tokenPortal.write.depositToAztecPrivate(args, {} as any); await this.publicClient.waitForTransactionReceipt({ hash: txHash2 }); - return Fr.fromString(entryKeyHex); + return Fr.fromString(messageHash); } async mintTokensPublicOnL2(amount: bigint) { @@ -392,17 +392,17 @@ export class CrossChainTestHarness { async withdrawFundsFromBridgeOnL1( withdrawAmount: bigint, blockNumber: number, - messageIndex: number, + messageIndex: bigint, siblingPath: SiblingPath, ) { - this.logger('Send L1 tx to consume entry and withdraw funds'); + this.logger('Send L1 tx to consume message and withdraw funds'); // Call function on L1 contract to consume the message const { request: withdrawRequest } = await this.tokenPortal.simulate.withdraw([ this.ethAccount.toString(), withdrawAmount, false, BigInt(blockNumber), - BigInt(messageIndex), + messageIndex, siblingPath.toBufferArray().map((buf: Buffer) => `0x${buf.toString('hex')}`) as readonly `0x${string}`[], ]); @@ -463,9 +463,9 @@ export class CrossChainTestHarness { * the message is sent to Inbox and when the subtree containing the message is included in the block and then when * it's included it becomes available for consumption in the next block because the l1 to l2 message tree. */ - async makeMessageConsumable(msgLeaf: Fr) { + async makeMessageConsumable(msgHash: Fr) { // We poll isL1ToL2MessageSynced endpoint until the message is available - await retryUntil(async () => await this.aztecNode.isL1ToL2MessageSynced(msgLeaf), 'message sync', 10); + await retryUntil(async () => await this.aztecNode.isL1ToL2MessageSynced(msgHash), 'message sync', 10); await this.mintTokensPublicOnL2(0n); await this.mintTokensPublicOnL2(0n); diff --git a/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts b/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts index 585c5626856..ef5140df02f 100644 --- a/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts +++ b/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts @@ -151,12 +151,12 @@ class GasBridgingTestHarness implements IGasBridgingTestHarness { // Deposit tokens to the TokenPortal this.logger('Sending messages to L1 portal to be consumed publicly'); const args = [l2Address.toString(), bridgeAmount, secretHash.toString()] as const; - const { result: entryKeyHex } = await this.tokenPortal.simulate.depositToAztecPublic(args, { + const { result: messageHash } = await this.tokenPortal.simulate.depositToAztecPublic(args, { account: this.ethAccount.toString(), } as any); await this.tokenPortal.write.depositToAztecPublic(args, {} as any); - return Fr.fromString(entryKeyHex); + return Fr.fromString(messageHash); } async sendTokensToPortalPrivate( @@ -177,12 +177,12 @@ class GasBridgingTestHarness implements IGasBridgingTestHarness { deadline, secretHashForL2MessageConsumption.toString(), ] as const; - const { result: entryKeyHex } = await this.tokenPortal.simulate.depositToAztecPrivate(args, { + const { result: messageHash } = await this.tokenPortal.simulate.depositToAztecPrivate(args, { account: this.ethAccount.toString(), } as any); await this.tokenPortal.write.depositToAztecPrivate(args, {} as any); - return Fr.fromString(entryKeyHex); + return Fr.fromString(messageHash); } async consumeMessageOnAztecAndMintPublicly(bridgeAmount: bigint, owner: AztecAddress, secret: Fr) { diff --git a/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts b/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts index 7f4aed845eb..61c270341f1 100644 --- a/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts +++ b/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts @@ -179,7 +179,7 @@ export const uniswapL1L2TestSuite = ( const [secretForMintingWeth, secretHashForMintingWeth] = wethCrossChainHarness.generateClaimSecret(); const [secretForRedeemingWeth, secretHashForRedeemingWeth] = wethCrossChainHarness.generateClaimSecret(); - const tokenDepositMsgLeaf = await wethCrossChainHarness.sendTokensToPortalPrivate( + const tokenDepositMsgHash = await wethCrossChainHarness.sendTokensToPortalPrivate( secretHashForRedeemingWeth, wethAmountToBridge, secretHashForMintingWeth, @@ -192,7 +192,7 @@ export const uniswapL1L2TestSuite = ( wethAmountToBridge, ); - await wethCrossChainHarness.makeMessageConsumable(tokenDepositMsgLeaf); + await wethCrossChainHarness.makeMessageConsumable(tokenDepositMsgHash); // 2. Claim WETH on L2 logger('Minting weth on L2'); @@ -317,11 +317,11 @@ export const uniswapL1L2TestSuite = ( daiCrossChainHarness.tokenPortalAddress, ); - const [swapPrivateL2MessageIndex, swapPrivateSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [swapPrivateL2MessageIndex, swapPrivateSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( l2UniswapInteractionReceipt.blockNumber!, swapPrivateLeaf, ); - const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( l2UniswapInteractionReceipt.blockNumber!, withdrawLeaf, ); @@ -358,7 +358,7 @@ export const uniswapL1L2TestSuite = ( const txHash = await uniswapPortal.write.swapPrivate(swapArgs, {} as any); // We get the msg leaf from event so that we can later wait for it to be available for consumption - let tokenOutMsgLeaf: Fr; + let tokenOutMsgHash: Fr; { const txReceipt = await daiCrossChainHarness.publicClient.waitForTransactionReceipt({ hash: txHash, @@ -370,7 +370,7 @@ export const uniswapL1L2TestSuite = ( data: txLog.data, topics: txLog.topics, }); - tokenOutMsgLeaf = Fr.fromString(topics.args.value); + tokenOutMsgHash = Fr.fromString(topics.args.hash); } // weth was swapped to dai and send to portal @@ -381,7 +381,7 @@ export const uniswapL1L2TestSuite = ( const daiAmountToBridge = BigInt(daiL1BalanceOfPortalAfter - daiL1BalanceOfPortalBeforeSwap); // Wait for the message to be available for consumption - await daiCrossChainHarness.makeMessageConsumable(tokenOutMsgLeaf); + await daiCrossChainHarness.makeMessageConsumable(tokenOutMsgHash); // 6. claim dai on L2 logger('Consuming messages to mint dai on L2'); @@ -411,7 +411,7 @@ export const uniswapL1L2TestSuite = ( // 1. Approve and deposit weth to the portal and move to L2 const [secretForMintingWeth, secretHashForMintingWeth] = wethCrossChainHarness.generateClaimSecret(); - const wethDepositMsgLeaf = await wethCrossChainHarness.sendTokensToPortalPublic( + const wethDepositMsgHash = await wethCrossChainHarness.sendTokensToPortalPublic( wethAmountToBridge, secretHashForMintingWeth, ); @@ -424,7 +424,7 @@ export const uniswapL1L2TestSuite = ( ); // Wait for the message to be available for consumption - await wethCrossChainHarness.makeMessageConsumable(wethDepositMsgLeaf); + await wethCrossChainHarness.makeMessageConsumable(wethDepositMsgHash); // 2. Claim WETH on L2 logger('Minting weth on L2'); @@ -552,11 +552,11 @@ export const uniswapL1L2TestSuite = ( daiCrossChainHarness.tokenPortalAddress, ); - const [swapPrivateL2MessageIndex, swapPrivateSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [swapPrivateL2MessageIndex, swapPrivateSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( uniswapL2Interaction.blockNumber!, swapPublicLeaf, ); - const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( uniswapL2Interaction.blockNumber!, withdrawLeaf, ); @@ -593,7 +593,7 @@ export const uniswapL1L2TestSuite = ( const txHash = await uniswapPortal.write.swapPublic(swapArgs, {} as any); // We get the msg leaf from event so that we can later wait for it to be available for consumption - let outTokenDepositMsgLeaf: Fr; + let outTokenDepositMsgHash: Fr; { const txReceipt = await daiCrossChainHarness.publicClient.waitForTransactionReceipt({ hash: txHash, @@ -605,7 +605,7 @@ export const uniswapL1L2TestSuite = ( data: txLog.data, topics: txLog.topics, }); - outTokenDepositMsgLeaf = Fr.fromString(topics.args.value); + outTokenDepositMsgHash = Fr.fromString(topics.args.hash); } // weth was swapped to dai and send to portal @@ -616,7 +616,7 @@ export const uniswapL1L2TestSuite = ( const daiAmountToBridge = BigInt(daiL1BalanceOfPortalAfter - daiL1BalanceOfPortalBeforeSwap); // Wait for the message to be available for consumption - await daiCrossChainHarness.makeMessageConsumable(outTokenDepositMsgLeaf); + await daiCrossChainHarness.makeMessageConsumable(outTokenDepositMsgHash); // 6. claim dai on L2 logger('Consuming messages to mint dai on L2'); @@ -919,11 +919,11 @@ export const uniswapL1L2TestSuite = ( ), )[0]; - const [swapPrivateL2MessageIndex, swapPrivateSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [swapPrivateL2MessageIndex, swapPrivateSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( withdrawReceipt.blockNumber!, swapPrivateLeaf, ); - const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( withdrawReceipt.blockNumber!, withdrawLeaf, ); @@ -1058,11 +1058,11 @@ export const uniswapL1L2TestSuite = ( ), )[0]; - const [swapPublicL2MessageIndex, swapPublicSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [swapPublicL2MessageIndex, swapPublicSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( withdrawReceipt.blockNumber!, swapPublicLeaf, ); - const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageIndexAndSiblingPath( + const [withdrawL2MessageIndex, withdrawSiblingPath] = await aztecNode.getL2ToL1MessageMembershipWitness( withdrawReceipt.blockNumber!, withdrawLeaf, ); diff --git a/yarn-project/pxe/src/simulator_oracle/index.ts b/yarn-project/pxe/src/simulator_oracle/index.ts index ff524c63f99..d0b5ac16837 100644 --- a/yarn-project/pxe/src/simulator_oracle/index.ts +++ b/yarn-project/pxe/src/simulator_oracle/index.ts @@ -121,17 +121,14 @@ export class SimulatorOracle implements DBOracle { } /** - * Retrieves the L1ToL2Message associated with a specific entry key - * - * @throws If the entry key is not found - * @param entryKey - The key of the message to be retrieved - * @returns A promise that resolves to the message data, a sibling path and the - * index of the message in the l1ToL2MessageTree + * Fetches the a message from the db, given its key. + * @param messageHash - Hash of the message. + * @returns The l1 to l2 membership witness (index of message in the tree and sibling path). */ - async getL1ToL2MembershipWitness(entryKey: Fr): Promise> { - const response = await this.aztecNode.getL1ToL2MessageMembershipWitness('latest', entryKey); + async getL1ToL2MembershipWitness(messageHash: Fr): Promise> { + const response = await this.aztecNode.getL1ToL2MessageMembershipWitness('latest', messageHash); if (!response) { - throw new Error(`No L1 to L2 message found for entry key ${entryKey.toString()}`); + throw new Error(`No L1 to L2 message found for message hash ${messageHash.toString()}`); } const [index, siblingPath] = response; return new MessageLoadOracleInputs(index, siblingPath); diff --git a/yarn-project/sequencer-client/src/simulator/public_executor.ts b/yarn-project/sequencer-client/src/simulator/public_executor.ts index c93c6d7e6c8..6008f8b2aa5 100644 --- a/yarn-project/sequencer-client/src/simulator/public_executor.ts +++ b/yarn-project/sequencer-client/src/simulator/public_executor.ts @@ -224,11 +224,11 @@ export class WorldStateDB implements CommitmentsDB { } public async getL1ToL2MembershipWitness( - entryKey: Fr, + messageHash: Fr, ): Promise> { - const index = (await this.db.findLeafIndex(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, entryKey.toBuffer()))!; + const index = (await this.db.findLeafIndex(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, messageHash.toBuffer()))!; if (index === undefined) { - throw new Error(`Message ${entryKey.toString()} not found`); + throw new Error(`Message ${messageHash.toString()} not found`); } const siblingPath = await this.db.getSiblingPath( MerkleTreeId.L1_TO_L2_MESSAGE_TREE, diff --git a/yarn-project/simulator/src/acvm/oracle/oracle.ts b/yarn-project/simulator/src/acvm/oracle/oracle.ts index 17510858cfc..78f7f2abbc2 100644 --- a/yarn-project/simulator/src/acvm/oracle/oracle.ts +++ b/yarn-project/simulator/src/acvm/oracle/oracle.ts @@ -244,8 +244,8 @@ export class Oracle { return toACVMField(exists); } - async getL1ToL2MembershipWitness([entryKey]: ACVMField[]): Promise { - const message = await this.typedOracle.getL1ToL2MembershipWitness(fromACVMField(entryKey)); + async getL1ToL2MembershipWitness([messageHash]: ACVMField[]): Promise { + const message = await this.typedOracle.getL1ToL2MembershipWitness(fromACVMField(messageHash)); return message.toFields().map(toACVMField); } diff --git a/yarn-project/simulator/src/acvm/oracle/typed_oracle.ts b/yarn-project/simulator/src/acvm/oracle/typed_oracle.ts index 83a75f7d339..e2fc9040bd1 100644 --- a/yarn-project/simulator/src/acvm/oracle/typed_oracle.ts +++ b/yarn-project/simulator/src/acvm/oracle/typed_oracle.ts @@ -171,7 +171,7 @@ export abstract class TypedOracle { throw new OracleMethodNotAvailableError('checkNullifierExists'); } - getL1ToL2MembershipWitness(_entryKey: Fr): Promise> { + getL1ToL2MembershipWitness(_messageHash: Fr): Promise> { throw new OracleMethodNotAvailableError('getL1ToL2MembershipWitness'); } diff --git a/yarn-project/simulator/src/client/view_data_oracle.ts b/yarn-project/simulator/src/client/view_data_oracle.ts index 40707da52b7..64e06296f82 100644 --- a/yarn-project/simulator/src/client/view_data_oracle.ts +++ b/yarn-project/simulator/src/client/view_data_oracle.ts @@ -226,11 +226,11 @@ export class ViewDataOracle extends TypedOracle { /** * Fetches the a message from the db, given its key. - * @param entryKey - A buffer representing the entry key. - * @returns The l1 to l2 message data + * @param messageHash - Hash of the message. + * @returns The l1 to l2 membership witness (index of message in the tree and sibling path). */ - public async getL1ToL2MembershipWitness(entryKey: Fr) { - return await this.db.getL1ToL2MembershipWitness(entryKey); + public async getL1ToL2MembershipWitness(messageHash: Fr) { + return await this.db.getL1ToL2MembershipWitness(messageHash); } /** diff --git a/yarn-project/simulator/src/public/db.ts b/yarn-project/simulator/src/public/db.ts index 54f1f1d4cbe..8f7524bff1f 100644 --- a/yarn-project/simulator/src/public/db.ts +++ b/yarn-project/simulator/src/public/db.ts @@ -79,12 +79,12 @@ export interface PublicContractsDB { /** Database interface for providing access to commitment tree, l1 to l2 message tree, and nullifier tree. */ export interface CommitmentsDB { /** - * Gets a confirmed L1 to L2 message for the given entry key. + * Gets a confirmed L1 to L2 message for the given message hash. * TODO(Maddiaa): Can be combined with aztec-node method that does the same thing. - * @param entryKey - The entry key. - * @returns - The l1 to l2 message object + * @param messageHash - Hash of the message. + * @returns The l1 to l2 membership witness (index of message in the tree and sibling path). */ - getL1ToL2MembershipWitness(entryKey: Fr): Promise>; + getL1ToL2MembershipWitness(messageHash: Fr): Promise>; /** * Gets the index of a commitment in the note hash tree. diff --git a/yarn-project/simulator/src/public/public_execution_context.ts b/yarn-project/simulator/src/public/public_execution_context.ts index dffd03f579a..31e9eb1ee88 100644 --- a/yarn-project/simulator/src/public/public_execution_context.ts +++ b/yarn-project/simulator/src/public/public_execution_context.ts @@ -93,11 +93,11 @@ export class PublicExecutionContext extends TypedOracle { /** * Fetches the a message from the db, given its key. - * @param entryKey - A buffer representing the entry key. + * @param messageHash - Hash of the massage. * @returns The l1 to l2 message data */ - public async getL1ToL2MembershipWitness(entryKey: Fr) { - return await this.commitmentsDb.getL1ToL2MembershipWitness(entryKey); + public async getL1ToL2MembershipWitness(messageHash: Fr) { + return await this.commitmentsDb.getL1ToL2MembershipWitness(messageHash); } /**