Aztec
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `aztec3-speccing-book` :::info PROPOSAL Author: Zac ::: # [OLD] Communication Abstractions (L1<>L2, public<>private). Take 2 N.B. many ideas here drawn from Mike's writeup from April (https://github.com/AztecProtocol/aztec2-internal/blob/3.0/markdown/specs/aztec3/src/architecture/contracts/l1-calls.md) # Organisation of Document This doc is split into 3 parts Part One describes the design goals of this spec, the restrictions we're working under and presents a high-level design with rationalisations provided for the design choices made (e.g. "what" and "why", but not "how") Part Two lists worked examples of implementing some Aztec Connect functionality Part Three describes a more detailed technical specification with no rationalisations (e.g. "how", but not "what" or "why") Part 1 --- - [Objectives](#Objectives) - [Data Structures](#Data-Structures,-Communication-Channels) - [L1->L2 messaging](#Messaging-abstraction-layer) - [L2->L1 messaging](#Calling-L1-functions-from-L2) Part 2 --- - [UniSwap](#Uniswap) Part 3 --- - [Data Structure Definitions](#Data-Structure-Definitions) - [Kernel Circuit Logic](#Kernel-Circuit-Logic) - [Rollup Contract Logic](#Contract-Logic) # Objectives What is the minimal-complexity mechanism to implement L1<>L2 comms? * Enable internal L2 functions to 'call' L1 functions * Enable L1 functions to 'call' L2 functions * Enable a method of public<>private function communication that does not encounter race conditions # High-level Overview All communication that crosses the L2<>L1 boundary is enabled via message passing. * L2 contracts are linked to L1 portal contracts * An L2 contract can send messages to its portal contract * An L1 portal contract can send messages to its linked L2 contract Messages can be used to compose complex sequences of function calls in a failure-tolerant manner. # Data Structures, Communication Channels The following describes all possible **interaction primitives** between public/private functions, L1 contracts and L2 databases. ![](https://hackmd.io/_uploads/SkeEkg8Oj.png) ([from architecture drawings](https://https://app.diagrams.net/#G1xH2fJXMu1dnZarQDrMuKYN-2Qmrf8U0I)) N.B. a unilateral function call is one with no return parameters. i.e. a function can make a unilateral call but cannot perform work on the results of the call. **What are the fundamental restrictions we have to work with?** 1. L1 contracts and L2 functions cannot read from shared state (L2 state is stored in snark-friendly Merkle trees, L1 state is stored in snark-unfriendly Merkle-patricia trees) 2. In an Aztec block, transactions are sequenced as [private calls -> public calls -> L1 calls] 3. L1<>L2 writes can only be acted on in a future block 4. L1 lacks access to SNARK-friendly primitives Communication across domain boundaries is asynchronous with long latency times between triggering a call and acting on the response (e.g. up to 10 minutes, possibly much more depending on design decisions). This doc follows the following heuristic/assumption: **L1 contracts, private functions and public functions are separated domains: all communication is *unilateral*** This doc defines no logic at the protocol level that requires callbacks or responses as a result of a message being sent across the public/private/L1 boundary. These abstractions can be built at a higher level by programming them as contract logic. # Messaging abstraction layer The following image isolates the primitives from fig.1 to enable L2<>L1 communication. ![](https://hackmd.io/_uploads/B141eeLOi.png) > **All write operations take at least 1 block to process** e.g. If an L2 triggers an L1 function and that L1 function writes a message, it cannot be read by an L2 function until the subsequent block. ### Message Boxes We introduce a "message box" database abstraction: The goal is for L2->L1 messages and L1->L2 messages to be treated symmetrically. The L1 messageBox is represented via a Solidity mapping in the rollup's contract storage. The L2 message box is represented via an append-only Merkle tree + nullifier tree. However the interface for both message boxes is similar. The available actions one can perform on a message is identical for both message boxes: ## Consuming messages For both L1/L2 messages, a message can either be *validated* or *consumed*. A *validate* operation asserts that a message exists. A *consume* operation will assert that the message exists. The message is then deleted. #### Q: What is in a "message"? A message is a tuple of the following: > 1. `destinationAddress` > 1. `messageData` For L2->L1 messages, `destinationAddress` is the address of the **L1 portal contract** that is linked to the L2 contract that create the message. The `destinationAddress` is defined by the Kernel circuit, not the function circuit (i.e. an L2 contract can only send messages to its linked portal contract) For L1->L2 messages, `destinationAddress` is the address of the **L2 contract** that is linked to the L1 portal contract that created the message. The `destinationAddress` is defined by the rollup smart contract (i.e. an L1 portal contract can only send messages to its linked L2 contract) The contents of `messageData` are undefined at the protocol level. Constraint to size of [NUM_BYTES_PER_LEAF](/VuCx3iZFStGgzGUgHaVmhg?both#NUM_BYTES_PER_MESSAGE_LEAF). More data requires more messages. ## Emulating function calls via messages The intended behaviour is for messages to represent instructions to execute L2/L1 functions. This can be achieved by formatting the message *payload* to contain a hash of the following: 1. Hash of function parameters (function signature + calldata) 2. (optional) `senderAddress` The `senderAddress` is used if the function call must come from a designated address. This is useful if a transaction writes multiple messages into the message box, where the associated functions must be executed in a specific order. ## Handling Errors Error handling is delegated to the contract developer. If a message triggers a function that has a failure case, this can be supported in one of 2 ways: 1. revert the transaction. This will prevent the message from being consumed. The transaction can be re-tried until successful 2. write a failure message into the L2/L1 message box, which instructs the L2/L1 component of the contract to unwind the transaction # Chaper 2: Worked Examples ## Uniswap ### Tx1: Triggering the swap from L2 ![](https://hackmd.io/_uploads/HkeIl48Os.png) ### Tx2: Executing swap on L1 ![](https://hackmd.io/_uploads/BJbtxELdj.png) Notes: When calling `consumeMessage`, the portal contract derives the message data. For example, the typical pattern could produce a message which is a SHA256 hash of: 1. SHA256(calldata) 2. address of entity calling portal contract (if required) In the above example, some messages do not specify a "from" parameter. These messages are linked to functions that can be called by any entity (e.g. the `swap` function could be designed to be called by a bot; paying the bot some Eth to incentivize it to generate the transaction) ### Tx3: Process swap result on L2 ![](https://hackmd.io/_uploads/B14he4IOi.png) Notes: * If tx fails in unintended way (e.g. out of gas), L1 tx will be reverted and no messages are consumed. i.e. tx can be attempted again * Only UniPortal contract can trigger DaiPortal "deposit" due to message specifying UniPortal as the depositor. Enables tx composability. --- # Part 3: Technical Specification ## Data Structure Definitions ### Message Leaf Added into append-only data tree. A message leaf is a hash of the following: | name | type | description | | --- | --- | --- | | `contractAddress` | address | L2 address of contract Portal is linked to | | `messageHash` | field | SHA256 hash of a byte buffer of size [NUM_BYTES_PER_LEAF](/VuCx3iZFStGgzGUgHaVmhg?both#NUM_BYTES_PER_MESSAGE_LEAF) | `messageHash = SHA256(messageData)`. Hash performed by L1 contract. `messageData` is a `buffer` of size [NUM_BYTES_PER_LEAF](/VuCx3iZFStGgzGUgHaVmhg?both#NUM_BYTES_PER_MESSAGE_LEAF). The message leaf spec does not require messages are unique. This is left to the portal contract if they desire this property (e.g. portal contract can track a nonce). ### Messagebox Queue A dynamic array with max size [`MAX_L1_CALLSTACK_DEPTH`](/VuCx3iZFStGgzGUgHaVmhg?both#MAX_L1_CALLSTACK_DEPTH) Each call item contains: | name | type | description | | --- | --- | --- | | `portalAddress` | u32 | used to define message target | | `chainId` | u32 | (needed if we want to go multichain) | | `message` | sharedBuffer | message to be recorded | ## Kernel-Circuit-Logic #### Creating L2->L1 Messages The public inputs of a user-proof will contain a dynamic array of messages to be added, of size [`MAX_MESSAGESTACK_DEPTH`](/VuCx3iZFStGgzGUgHaVmhg?both#MAX_MESSAGESTACK_DEPTH). The `portalAddress` parameter is supplied by the Kernel circuit and is stored in the circuit verification key. The Kernel circuit will perform the following when processing a transaction: * Iterate over contract's outbound message array and push each item onto the message stack (adding in `portalAddress`) * Validate there is no message stack overflow #### Nullifying L1->L2 messages Nullifier logic is identical to handling regular state nullifiers. ## Contract Logic Define the following storage vars: * `pendingMessageQueue`: dynamic array of messages (FIFO queue) * `messageQueue`: dynamic array of messages (FIFO queue) ### `addMessage(bytes memory message)` (function has no re-entrancy guard) 1. Validate `msg.sender` is a portal contract 2. Look up `portalAddress` that maps to `msg.sender` 3. Push tuple of `(message, portalAddress)` into a FIFO `pendingMessageQueue` ### `processRollup` #### processing messages 1. Validate the rollup circuit has added the leading [`MAX_MESSAGES_PROCESSED_PER_ROLLUP`](/VuCx3iZFStGgzGUgHaVmhg?both#MAX_MESSAGES_PROCESSED_PER_ROLLUP) from `messageQueue` into the data tree 2. Pop processed messages off of `messageQueue` 3. Push `pendingMessageQueue` onto `messageQueue` 4. Clear `pendingMessageQueue` #### processing L2->L1 messagebox writes Iterate over `messageStack` provided by rollup public inputs. Use `mapping(address => bytes) messageBox` to log messages. For each entry, `messageBox[entry.portalAddress] = entry.message` (TODO: handle duplicate messages) ## MessageBox Logic `function consumeMessage(bytes message) public` If `messageBox[msg.sender]` contains `message`, delete message from `messageBox`, otherwise throw an error `function assertMessageExists(bytes message) public` If `messageBox[msg.sender]` does *not* contain `message`, throw an error. ## Rollup Circuit Logic Rollup contract actions: #### L2->L1 messages Concatenate all kernel circuit L1 message stacks into a monolithic L1 messageStack. Monolithic messageStack has max size [`MAX_ROLLUP_L1_MESSAGESTACK_DEPTH`](/VuCx3iZFStGgzGUgHaVmhg?both#MAX_ROLLUP_L1_MESSAGESTACK_DEPTH) Sum of all monolithic callstack calldata is [`MAX_ROLLUP_L1_MESSAGESTACK_BYTES`](/VuCx3iZFStGgzGUgHaVmhg?both#MAX_ROLLUP_L1_MESSAGESTACK_BYTES) The contents of `messageStack` are assigned as public inputs of the rollup circuit. #### L1->L2 Messages For each message in L1's `messageQueue` array, perform the following: 1. Provide a `contract` leaf from the contract tree 2. Validate `contract.portalId == message.portalId` 3. Compute message leaf `H(messageSeparator, contract.contractAddress, message.messageHash)` 4. Add leaf into message tree 5. Extract `message.to`, `message.value`. If nonzero, credit `balances[to] += value` Output `SHA256(messageQueue)` to attest to the messages added into the message tree.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully