Thomas Coratger
    • Create new note
    • Create a note from template
      • 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
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me 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 New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # LeanVM Compiler > Inspired by the analysis documentation from Morgan Thomas: https://docs.google.com/document/d/1wh2WoMo3r4fSJWHr8OzS6ogJlLKQ6Ai_SIPFIh5eeTE/edit?tab=t.0 > ## Why do we need a compiler for leanVM? Before diving into the compiler, let's understand its target. The leanVM is not a general-purpose machine like the other zkVMs targetting real time proving on the L1. It's designed with a single, crucial goal in mind: post-quantum signature aggregation on Ethereum. * **The Task**: To prove the aggregation and recursive merging of many XMSS hash-based signatures. This boils down to proving a massive number of Poseidon2 hashes glued together with specific logic. * **The Target ISA**: The compiler generates bytecode for the leanVM's Instruction Set Architecture (ISA), which is tailored for this task. Key features include: * **Field**: The small and efficient KoalaBear prime field ($p = 2^{31} - 2^{24} + 1$). * **Memory**: A simple read-only memory model. * **Registers**: A minimalist set with just a program counter (`pc`) and a frame pointer (`fp`). * **Instructions**: A few core opcodes (`ADD`, `MUL`, `DEREF`, `JUMP`) and some precompiles for hashing (`POSEIDON`), cryptography (`DOT_PRODUCT`), and proof system internals (`MULTILINEAR_EVAL`). The compiler's essential role is to translate human-readable logic into the VM's constrained, ZK-friendly bytecode. For a program of this scale, writing bytecode manually is impractically complex and prone to error, making a dedicated compiler the most viable approach. Crucially, the compiler is a distinct component that can be designed and developed in parallel with the core proof system. ## Writing Code in the leanSig DSL The high-level language for the leanVM is the leanSig DSL. It's designed to provide familiar programming constructs while mapping cleanly to the underlying ZK constraints. * **Syntax & Semantics**: It has a Rust-like syntax and C-like semantics. * **Core Type**: The only first-class type is a scalar, representing a base field element. * **Features**: * Basic arithmetic (`+`, `*`, `/`, `-`). * Control flow: `if`, `match`, `for` loops, and function calls. * Memory management via `malloc` and `malloc_vec` for dynamic allocation. * Direct access to VM features through keywords like `poseidon16`, `dot_product`, and `decompose_bits`. * **Optimization Hints**: The programmer can guide the compiler with annotations like `#[inline]`, `#[unroll]`, and `const` function arguments. ## Four-Stage Compilation Pipeline The leanSig compiler transforms DSL code into executable bytecode through a four-stage process: 1. **Parsing**: The source code is parsed into an Abstract Syntax Tree (AST). This stage performs basic validation, like checking if functions are defined. 2. **Simplification**: The AST is transformed into a simpler, more canonical form. This is where high-level language features are "desugared": * Functions marked `#[inline]` are inlined. * Functions with `const` arguments are specialized for each call site. * Constant expressions are evaluated at compile time (constant folding). * `for` loops are rewritten into recursive functions (ZK-friendly pattern!). 3. **Intermediate Code Generation**: The simplified AST is compiled into an intermediate bytecode. This stage is important for memory layout, as it's where stack frames are planned and high-level constructs are translated into a sequence of low-level operations. 4. **Final Code Generation**: The intermediate representation is converted into the final, low-level bytecode. This stage lays out the instructions in memory, materializes constants, and inserts the necessary entry and finalization code. ## Compiler Challenges & ZK-Friendly Strategies Compiling for a zk-VM isn't like compiling for a normal CPU. Every choice has consequences for the proving cost. Let's discuss some of the interesting strategies used in the leanVM compiler. ### Handling Control Flow * **Loops**: How do you handle a `for` loop when the machine can't make arbitrary jumps? The leanSig compiler uses a standard ZK trick: * If the number of iterations is small and known at compile-time, the loop is unrolled. * Otherwise, the loop is automatically rewritten as a recursive function. This replaces dynamic jumps with function calls, which have a predictable memory and instruction layout. * **Switch Statements**: To implement a `match` or `switch` statement, the compiler uses an arithmetic trick instead of a jump table. It places the code for each branch at regular intervals in memory and computes the jump destination directly: `dest = base_address + branch_index * block_size`. (Note: For soundness reasons, this requires the program to assert `branch_index` < `total_number_of_branches`) * **Functions & The Stack**: With a read-only memory model, the stack can't be reused in the traditional sense. When a function is called: * A new, fresh memory region (stack frame) is allocated. * The old `pc` and `fp` are saved to the top of the new frame. * The `fp` register is updated to point to this new frame. * Interestingly, the allocation pointer (`ap`) is a Prover-only concept used during execution to find free memory. It doesn't need to be part of the VM state or the proof, simplifying the AIR. ### Memory Management & Hints * **`malloc`**: How does `malloc` work with read-only memory and no OS? * The compiler distinguishes between compile-time known sizes (stack allocated) and dynamic sizes (heap allocated). * For dynamic sizes, it emits a `RequestMemory` hint. This hint is not an instruction and doesn't go into the trace. Instead, it tells the *execution engine* (the Prover) to allocate memory from a heap pointer. * The execution engine actually runs the program twice: the first pass calculates the total required heap size, and the second pass performs the actual execution with correctly laid out memory. ### Open Questions for Discussion * The "unroll or recurse" strategy for loops is common. What are the performance trade-offs? When does recursion become cheaper than unrolling a large loop? * The two-pass execution for `malloc` is an interesting solution. Are there alternative ways to handle dynamic memory allocation in a zk-VM? What are their pros and cons? ## Correctness and Performance The technical analysis of the leanVM compiler highlights two critical, long-term goals. ### Proving Compiler Correctness How do we trust that the compiler doesn't introduce bugs? A full formal verification of the compiler could add value. A more pragmatic approach is to build a **verifying compiler**. * **Verified Compiler**: Proves that for *all possible* source programs, the compilation is correct. * **Verifying Compiler**: For *each specific program it compiles*, it produces a proof of correctness alongside the bytecode. Possible recommendation for leanVM is to pursue the path of a verifying compiler, likely by porting it to a proof assistant like Coq or Lean. This requires creating formal mathematical definitions of the DSL and ISA semantics. ### Optimizing for Proving Cost Compiler optimizations are usually about execution speed. Here, the goal is to minimize the cost of generating a proof. This requires a different mindset. * **Cost Model**: Since generating a proof is expensive, the optimizer can't just try a compilation and measure the result. It needs a cheap cost model—a function that *estimates* the proving cost based on metrics like bytecode size, cycle count, memory footprint, and opcode frequency. * **Combinatorial Optimization**: Choosing whether to inline a function or unroll a loop is a complex decision. The best choice depends on the context of the entire program. The analysis suggests treating the DSL annotations (`#[inline]`, `#[unroll]`) as *suggestions* for a combinatorial optimization search that tries to find the best global configuration for minimizing the cost model. ### Open Questions for Discussion * What are the most important factors for a ZK proving cost model? Is it trace length, constraint degree, or something else? * How can we balance the complexity of advanced compiler optimizations against the need for the compiler itself to be simple and verifiable? * The leanVM ISA is minimal. What single instruction, if added, would provide the biggest performance improvement for the XMSS signature program? (e.g. bitwise operations?)

    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