PSE zkEVM
      • 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
    ## Requirement - Verify a list of transactions - In the beginning of each transaction or internal call, verify one of: - Simple ether transfer and goto next transaction - Contract creation and begin bytecode execution - Contract interaction and begin bytecode execution - In each step of bytecode execution, we need to verify all kinds of possible result, which includes all opcode and their different success or failure case. - In the end of each internal call, it resume to caller. (A call ends with any failure execution results or success of `STOP`, `RETURN`, or `REVERT`) - In the end of each transaction, it handles refund and coinbase reward, then continue to next transaction. (A valid transaction always ends with success of `STOP`, `RETURN`, or `REVERT`) What's annoying is there are 142 opcodes in total, each of them also have a few possible execution results, which sum to around **470 possible execution results**. (plus few call initialization cases) If we treat `ErrOutOfGas` as 2 different errors `ErrOutOfConstantGas` and `ErrOutOfDynamicGas`, and the former with other common errors which could be verified easily as an single case (other like `ErrStackUnderflow`, `ErrStackUnderflow`, `ErrWriteProtection`, `ErrDepth`, `ErrInsufficientBalance`), then we have **187 possible execution results**, which seems better but still many for a circuit. In the end there will be less cause we will find some opcodes can be handled without any extra cost (like `DUP*` and `SWAP*`). > In current impl I didn't treat common errors as an single case because I thought it won't save too much, but now for me it seems we should do this to avoid impl redundancy. Then it seems only around 30 opcodes need 2 cases (success and dynamic OOG) and only `CREATE*` needs to be taken care specially. Others only need to focus on success case. > [name=han] See [here](https://gist.github.com/han0110/3aa1381149b44e77d338645fe0a09025) for the estimation of possible execution results. Or see [`evm-opcodes`](https://github.com/wolflo/evm-opcodes) by [wolflo](https://github.com/wolflo) for a quick reference for EVM opcodes, which also explains the gas cost fantastically. > The pre-compiled contracts are not considered yet, it seems we could treats them as special opcode that constraint address to some value. ## Current Implementation ### Limitation Assume finally we have each polynomial degree to $2^{25}$, then we have - Gate degree bound: $9$ - Subset argument degree bound (input + table): $7$ > [Reference](https://github.com/zcash/halo2/blob/main/src/plonk/lookup.rs#L69). Not certainly sure about this, need @yingtong's confirmation. > [name=han] ### Layout - Width: 32 + some fixed and advice selectors - Height: 10 - Rotation: - 0~9 for all columns - 10 for tracking cells accessible to next step (`gc`, `sp`, etc...) - Cell Usage: - For Branching: - 1 bool cell `is_padding` to identify whether it's a padding - 1 bool cell `is_executing` to identify whether it's executing bytecode or initializing a call - 80 bool cells `q_ops` for op gadgets, each op gadget could handle more than 1 op (80 comes from `142 - (num_push - 1) - (num_dup - 1) - (num_swap - 1)`, could be less in the future). - Other: - $\le 14$ tracking cells, which are next step accessible like `global_counter`, `call_id`, `bytecode_source_kind`, `bytecode_source`, `stack_pointer`, etc... - $7 \cdot 32$ generic usage cells (7 comes from the most costly case: the success of `CALL` which pops 7 words from stack) - Subset Arguments - 7 bus mapping lookup (7 comes from the same reason as above) - 32 byte range lookup - 32 fixed table lookup ## Potential Optimization ### Assuming memory size has a hard bound $2^{24}$ When memory is used to $2^{24}$, the gas cost will be around 18 times of current block gas limit $30000000$. ($3 \cdot 2^{19} + \frac{2^{2\cdot 19}}{512} = 538443776 \approx 18 \cdot 30000000$) If we can assume the memory will always be in $2^{24}$ (prover can't create a proof if memory size out of the range), then any memory offset or size pop from stack will only cost 3 cells instead of 32, and we can reduce words usage from 7 to 4. The reason is most opcode uses $\le 3$ words with some auxilary witness, and those opcode use more than 3 words always contain 2~4 memory offset and size, which can be put inside single word together if we assume so. Then we can make the height of layout become 7 instead of 10 But not sure if such incompatible with EVM will break some current DApp, need to do more investigation. ### Narrow down circuit to reduce subset arguments Currently we have so many subset arguments... A subset argument costs 3 commitments and 5 evaluations (shuffled table + shuffled input accessible to previous + 1 shuffle product accessible to next), which seems really costly. > [Reference](https://github.com/zcash/halo2/blob/main/examples/cost-model.rs#L242). Not sure if it's correct in our case, need @yingtong and @kilic's confirmation. > [name=han] With narrower circuit seems reasonable because we then can make good use of a single subset argument, but still have some drawback: - Pros - Less subset arguments - Cons - More rotation access will be required cause we still need so many cells to put witness - We need to more effort to take care of the layout (be awareness of which columns to put witness for lookup) - Extra witness selector to enable the subset argument. - Some data redundancy (seems not big deal) For each subset argument, we handle the layout: - Bus mapping lookup - TODO - Byte range lookup - Put word in the same row (already implemented) - Fixed table lookup - Add another tag column - Set tag value when enabled, otherwise set it to 0 - Lookup by `(tag * input, tag * table)` for all-zero-row when disabled ## Other Random Thoughts ### Allow Higher Gate Degree Bound They are several approaches to do branching (creation of bool expression for branches), to represetn $N$ unrolled branches, we can do: | Description | Degree Cost | Cell Cost | Note | | ------------------------------------ | ----------- | ----------- | --------------------------------- | | Lagrange basis in single cell | $N$ | $1$ | State circuit currently uses this | | Binary composition in $\log$ cells | $\log_2(N)$ | $\log_2(N)$ | | | Stand-alone booleans in $N$ cells | $1$ | $N$ | Current implementation uses this nestedly | > Wondering if there are more choices to do efficient branching. > [name=han] Since we have 186 possible execution results (might be much less in the future), we can binary composition with 8 bit to represent each case, which leads to a degree 8 synthetic selector. It will be too high for previous limitation, but if we relax the mul degree bound to 16, then we can reduce 80 selector to only 8. It seems not beneficial cause we only save height from 7 to 5, but our total poly degree is also half. And the linearisation could be much more complicated. ### Outsource Word Operation The reason the previous approach doesn't save is because the 4 words still dominate the step cost. If we can outsource word operation, and with the previous approach, the circuit could be much less wide. So like arithmetic, bitwise, comparator, etc... which needs to be verified byte to byte will be handle in another circuit as a table. Some special case like bytecode copy, we can assume bytecode table is constraint to order bytecode by index, then do lookup like: ```rust meta.lookup(|meta| { // ... // encode table with continously 32 rotation instead of decompressing in evm circuit step let a_word = meta.query_advice(advice_opcode, Rotaion::cur()) let t_word = (0..32) .iter() .map(|rotation| meta.query_advice(table_opcode, Rotation(rotation))) .enumerate() .fold( Expression::Constant(F::zero()), |acc, (idx, op)| acc + op * r.exp(idx) ); vec![ // ... (a_word, t_word) ] }); ``` Then we don't need to decompress word into 32 bytes in evm circuit. Other case like memory copy, we need some other constraint on bus mapping to perform such trick. ### Replace Fixed Selector with Witness Currently there is a fixed selector to serve as a pivot to enable each step, it enable in the first row of every 10 rows to fit the most costly case. What if we replace the fixed selector with a witness one, then we use another fixed selector to constraint the first row's of the witness pivot to 1, then each case will constraint next N+1 row's witness pivot to 1, where N is the amount of rows the case requires. Then we don't waste any rows ever. To visualize, we can treat the circuit as a giant table, each gadget is just sliding from top to bottom to verify the cells satisfy the constraints when it's enabled, so we should be able to do this trick. Not sure if there is some drawback (security issue, more complicated linearisation on verifier, etc...)

    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