HackMD
  • Prime
    Prime  Full-text search on all paid plans
    Search anywhere and reach everything in a Workspace with Prime plan.
    Got it
      • Create new note
      • Create a note from template
    • Prime  Full-text search on all paid plans
      Prime  Full-text search on all paid plans
      Search anywhere and reach everything in a Workspace with Prime plan.
      Got it
      • Options
      • Versions and GitHub Sync
      • Transfer ownership
      • Delete this note
      • Template
      • Save as template
      • Insert from template
      • Export
      • Dropbox
      • Google Drive
      • Gist
      • Import
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
      • Download
      • Markdown
      • HTML
      • Raw HTML
      • Sharing Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • More (Comment, Invitee)
      • Publishing
        Everyone on the web can find and read all notes of this public team.
        After the note is published, everyone on the web can find and read this note.
        See all published notes on profile page.
      • Commenting Enable
        Disabled Forbidden Owners Signed-in users Everyone
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Invitee
      • No invitee
    Menu Sharing Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Versions and GitHub Sync Transfer ownership Delete this note
    Export
    Dropbox Google Drive Gist
    Import
    Dropbox Google Drive Gist Clipboard
    Download
    Markdown HTML Raw HTML
    Back
    Sharing
    Sharing Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    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
    More (Comment, Invitee)
    Publishing
    Everyone on the web can find and read all notes of this public team.
    After the note is published, everyone on the web can find and read this note.
    See all published notes on profile page.
    More (Comment, Invitee)
    Commenting Enable
    Disabled Forbidden Owners Signed-in users Everyone
    Permission
    Owners
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Invitee
    No invitee
       owned this note    owned this note      
    Published Linked with GitHub
    Like BookmarkBookmarked
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # MiMC Hashing in the EVM using EVM384 **TLDR** This post presents potential cost reductions for on-chain computation of the MiMC hash function implemented using [EVM384-v7](https://notes.ethereum.org/@poemm/evm384-interface-update#Interface-v7) opcodes. Limitations of the EVM384 spec discovered as a result of this work are also discussed. --- MiMC is a snark-friendly hash function that has seen considerable use on Ethereum. A notable use-case is in decentralized coin-mixers such as Tornado Cash where the MiMC cipher is currently invoked 40 times per deposit. According to [Tornado Cash Specs](https://github.com/tornadocash/tornado-core#specs), this greatly dominates the cost of deposits (1,088,354 gas), which are ~3x more expensive than withdrawals from the system. The implementation of MiMC used by Tornado Cash is in Iden3's Circomlib library. The EVM bytecode is produced by a Javascript [generator](https://github.com/iden3/circomlib/blob/master/src/mimcsponge_gencontract.js). A look at the [inner loop](https://github.com/iden3/circomlib/blob/master/src/mimcsponge_gencontract.js#L53-L78) shows a reliance on `ADDMOD`/`MULMOD` which are priced according to a generic algorithm. Additionally a significant portion of the EVM overhead comes from stack manipulation using `DUP/SWAP` to keep parameters in the correct ordering for the current and subsequent round. ## MiMC Implementation The EVM384 implementation of MiMC is [here](https://github.com/jwasinger/mimc-evm384). --- | MiMC Implementation | Gas Cost | | ----------- | ----------- | | EVM (Circomlib) | 17460 | | EVM384 | 11414 | **Table 1.** The cost of a single call to MiMC's cipher. --- This implementation uses a slightly modified EVM384-v7 with smaller offsets, to save on code size, among other reasons. The costs are calculated using the opcode costs set by [update 5](https://notes.ethereum.org/@poemm/evm384-update5#Proposed-EVM384-Gas-Costs). However we expect significant cost reduction once the potential optimisations mentioned in the next section are considered. Compared to the Circomlib implementation, we note an additional benefit: the use of `EVM384` opcodes, which pack multiple parameters (memory offsets) into a single stack item, greatly improves readability of the [generator code](https://github.com/jwasinger/mimc-evm384/blob/master/src/mimcsponge.js#L14) by removing the need for stack manipulation. For a fair comparison of gas savings within Tornado Cash we must clarify a few details. A Tornado deposit computes the root of 20-level binary merkle, calling MiMC's cipher twice per level. While the EVM (and so Circomlib's implementation) handles numbers using big-endian byte order, EVM384 is little-endian currently. We have [noted](https://notes.ethereum.org/@poemm/evm384-update3#Interface-Endianness) some slowdown for making EVM384 big-endian. Hence we have multiple options: - a) For a drop-in-replacement byteswapping must be performed. We [prototyped](https://github.com/axic/evm-bswap-golfing) that using existing EVM opcodes and a new [`BSWAP` opcode](https://github.com/ewasm/EIPs/blob/evm384/EIPS/eip-draft-bswap.md). - b) For the best cost efficiency one would modify Tornado Cash to use a different interface to Circomlib's. - c) Consider a big-endian version of EVM384 once again. We plan to release an update about these options later. ## Limitations of EVM384 EVM384 aimed to add support for modular arithmetic on values up to 384-bits. The implementations and specification are based on modular addition/subtraction and Montgomery multiplication algorithms operating on large integers represented as 6x64 bit limbs. <small>Note that performant arithmetic on values larger than the system word size is often implemented using numbers represented as multiple word-sized "limbs".</small> It was assumed that the Montgomery multiplication algorithm used for EVM384-v7 implementations (algorithm 14.36 from The Handbook of Applied Cryptography) would produce correct values for moduli occupying less than the full 6 limbs (i.e. cases where the most significant limb is `0x00...00`). This would allow EVM384-v7's `MULMODMONT384` to cover smaller moduli. When this assumption was revealed to be false while attempting to use `MULMODMONT384` with a 254-bit/4x64bit-limbed modulus (Tornado uses MiMC with BN128's curve order), several iterations were [brainstormed](https://notes.ethereum.org/@axic/H1DMHeild) and [implemented](https://github.com/jwasinger/evm1024). Since then, an additional property of the design of EVM384-v7 came to light which reveals the need for further iteration(s) on the spec: Remember that Montgomery multiplication makes use of a special constant derived from a given modulus using an expensive modular inverse. The `MULMODMONT384` opcode requires the user to pre-compute this constant and pass it as a parameter. Because Montgomery multiplication algorithms we were aware of produce defined (but potentially incorrect/"garbage") outputs on all inputs regardless of whether the "Montgomery constant" is correctly computed, it was assumed that the spec for `MULMODMONT384` could strictly follow the behavior of a chosen algorithm. However, as it was later pointed out (first by Jordi Baylina from Iden3), having a setup mechanism would remove some overhead and reduce some pricing risk. This in turn also opens the door for using multiple algorithms and removes the need for keeping implementation quirks part of the specification. --- Special thanks to Alex Beregszazi for implementation of ABI handler code compatible with the Circomlib implementation of MiMC, review and proposal of solutions regarding byteswapping for EVM384 and review/contributions on this document. Stay tuned for the release of additional updates and new proposals.

    Import from clipboard

    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 lost their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template is not available.


    Upgrade

    All
    • All
    • Team
    No template found.

    Create custom template


    Upgrade

    Delete template

    Do you really want to delete this template?

    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 via Google

    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

    Tutorials

    Book Mode Tutorial

    Slide Mode Tutorial

    YAML Metadata

    Contacts

    Facebook

    Twitter

    Feedback

    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

    Versions and GitHub Sync

    Sign in to link this note to GitHub Learn more
    This note is not linked with GitHub Learn more
     
    Add badge Pull Push GitHub Link Settings
    Upgrade now

    Version named by    

    More Less
    • Edit
    • Delete

    Note content is identical to the latest version.
    Compare with
      Choose a version
      No search result
      Version not found

    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. Learn more

         Sign in to GitHub

        HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.

        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
        Available push count

        Upgrade

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Upgrade

        Danger Zone

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

        Syncing

        Push failed

        Push successfully