Ivan Litteri
    • 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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    # Gnark's infinite loop call trace and explanation As said in the [post](https://www.notamonadtutorial.com/how-to-use-the-consenyss-gnark-zero-knowledge-proof-library-and-disclosure-of-a-ddos-bug/) there is a bug in Gnark when using the low-level API for building an R1CS. The code that causes it is the following: ```go /* R1CS Building */ // (X * Y) == Z + 5 // X is secret // Y is public // Z is public // 5 is constant r1cs := cs_bn254.NewR1CS(1) // Variables _ = r1cs.AddPublicVariable("1") // the ONE_WIRE Y := r1cs.AddPublicVariable("Y") Z := r1cs.AddPublicVariable("Z") X := r1cs.AddSecretVariable("X") // Constants FIVE := r1cs.FromInterface(5) CONST_FIVE_TERM := r1cs.MakeTerm(&FIVE, 0) CONST_FIVE_TERM.MarkConstant() // Coefficients COEFFICIENT_ONE := r1cs.FromInterface(1) // Constraints // (1 * X) * (1 * Y) == (1 * Z) + (5 * 1) constraint := constraint.R1C{ L: constraint.LinearExpression{r1cs.MakeTerm(&COEFFICIENT_ONE, X)}, // 1 * X R: constraint.LinearExpression{r1cs.MakeTerm(&COEFFICIENT_ONE, Y)}, // 1 * Y O: constraint.LinearExpression{ r1cs.MakeTerm(&COEFFICIENT_ONE, Z)}, // 1 * Z 1 CONST_FIVE_TERM, // 5 } r1cs.AddConstraint(constraint) ... ``` This bug not only makes the execution to go into an infinite loop but it could use all the available memory! Here we present kind of an execution trace that leads to the bug's origin and what we understand is happening there. ## Path to the bug First of all, we need to understand what `MarkConstant()` is doing. `MarkConstant()` is a method for `Term`s. `Term` represents a $\mathbb{coefficient} \cdot \mathbb{value}$ in a constraint system and it is defined as follows in the [`constraints/term.go` module](https://github.com/ConsenSys/gnark/blob/master/constraint/term.go#L22) (or `constraint` package): ```go type Term struct { CID, VID uint32 } ``` where `CID` is the coefficient ID that represents the index of the concrete coefficient of the term and `VID` is the value ID that represents the index of the concrete value of the term. `MarkConstant()` basically sets `VID` to the max `uint32` value ```go func (t *Term) MarkConstant() { t.VID = math.MaxUint32 } ``` Then the API exposes another method to know if a given term is constant ```go func (t *Term) IsConstant() bool { return t.VID == math.MaxUint32 } ``` Now that we know what `MarkConstant()` does, it'd make more sense to say that the bug is caused because the `VID` is set to this high value. Let's see why. Everything starts at `AddConstraint` in the [`r1cs.go` module](https://github.com/ConsenSys/gnark/blob/master/constraint/bn254/r1cs.go). It may look redundant but this function adds a constraint to a circuit and returns a constraint ID (`cID`) ```go func (cs *R1CS) AddConstraint(r1c constraint.R1C, debugInfo ...constraint.DebugInfo) int { profile.RecordConstraint() cs.Constraints = append(cs.Constraints, r1c) cID := len(cs.Constraints) - 1 if len(debugInfo) == 1 { cs.DebugInfo = append(cs.DebugInfo, constraint.LogEntry(debugInfo[0])) cs.MDebug[cID] = len(cs.DebugInfo) - 1 } cs.UpdateLevel(cID, &r1c) return cID } ``` Everything runs correctly but the execution doesn't go beyond `UpdateLevel()`, which is a passthrough method that calls another `updateLevel` in the [`level_builder.go` module](https://github.com/ConsenSys/gnark/blob/master/constraint/level_builder.go) ```go func (r1cs *R1CSCore) UpdateLevel(cID int, c Iterable) { r1cs.updateLevel(cID, c) } ``` where the real "update level" logic lies ```go func (system *System) updateLevel(cID int, c Iterable) { system.lbOutputs = system.lbOutputs[:0] system.lbHints = map[*Hint]struct{}{} level := -1 wireIterator := c.WireIterator() for wID := wireIterator(); wID != -1; wID = wireIterator() { // iterate over all wires of the R1C system.processWire(uint32(wID), &level) } // level = max(dependencies) + 1 level++ // mark output wire with level for _, wireID := range system.lbOutputs { for int(wireID) >= len(system.lbWireLevel) { // we didn't encounter this wire yet, we need to grow b.wireLevels system.lbWireLevel = append(system.lbWireLevel, -1) } system.lbWireLevel[wireID] = level } // we can't skip levels, so appending is fine. if level >= len(system.Levels) { system.Levels = append(system.Levels, []int{cID}) } else { system.Levels[level] = append(system.Levels[level], cID) } } ``` This is not the function where the infinite, it is `processWire` in this loop ```go for wID := wireIterator(); wID != -1; wID = wireIterator() { // iterate over all wires of the R1C system.processWire(uint32(wID), &level) } ``` This `for` iterates successfully until the `wID` which corresponds to `VID` in the `wireIterator`, corresponds to the `VID` of the term that is set to be the max `uint32`. Let's get into `processWire` ```go func (system *System) processWire(wireID uint32, maxLevel *int) { if wireID < uint32(system.GetNbPublicVariables()+system.GetNbSecretVariables()) { return // ignore inputs } for int(wireID) >= len(system.lbWireLevel) { // we didn't encounter this wire yet, we need to grow b.wireLevels system.lbWireLevel = append(system.lbWireLevel, -1) } if system.lbWireLevel[wireID] != -1 { // we know how to solve this wire, it's a dependency if system.lbWireLevel[wireID] > *maxLevel { *maxLevel = system.lbWireLevel[wireID] } return } // we don't know how to solve this wire; it's either THE wire we have to solve or a hint. if h, ok := system.MHints[int(wireID)]; ok { // check that we didn't process that hint already; performance wise, if many wires in a // constraint are the output of the same hint, and input to parent hint are themselves // computed with a hint, we can suffer. // (nominal case: not too many different hints involved for a single constraint) if _, ok := system.lbHints[h]; ok { // skip return } system.lbHints[h] = struct{}{} for _, hwid := range h.Wires { system.lbOutputs = append(system.lbOutputs, uint32(hwid)) } for _, in := range h.Inputs { for _, t := range in { if !t.IsConstant() { system.processWire(t.VID, maxLevel) } } } return } // it's the missing wire system.lbOutputs = append(system.lbOutputs, wireID) } ``` It is a big function but our infinite loop lies in the first `for while` loop ```go for int(wireID) >= len(system.lbWireLevel) { // we didn't encounter this wire yet, we need to grow b.wireLevels system.lbWireLevel = append(system.lbWireLevel, -1) } ``` At this point, if you would like to figure out by yourself why this is an infinite loop, remember that `wireID` is the max `uint32` value and consider that `len()` returns a value of type `int`. ## Why it loops infinitely and could consume your memory If you didn't come to a conclusion, let me be your guest. This Golang `while` will loop infinitely because the condition won't be false because `len()` could never be able to return a value bigger than `wireID`. This is the reason for the infinite loop, and the reason for the memory usage is the line that is inside the `for`'s scope. It is appending a `-1` every iteration meaning a 4 to 8 byte memory usage increase every cycle. With this said, you probably figured out that the bug could not only be caused because of marking a term as constant but also by setting a high `CID` for the term! ## Call Trace ```mermaid flowchart AC[AddConstraint] --> UL[UpdateLevel] UL[UpdateLevel] --> UL2[updateLevel] UL2[updateLevel] --> PW[processWire] ```

    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
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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