Mooly Sagiv
    • 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
    # Post-Mortem Analysis of the Notional Finance Vulnerability - A Vacuous Invariant ## Introduction On January 7, 2022, [Notional Finance reported about a critical vulnerability prevented in their smart contracts](https://blog.notional.finance/critical-bug-payout-report/). The vulnerability arised due to a potential double-counting of assets, as the same asset could appear both as a "bitmap currency" and an "active currency". The Notional team was aware during development that no asset should never be marked both as "bitmap" and "active", and has employed Formal Verification and the Certora Prover by writing an _invariant_ whose declared purpose was to check that such a state could never be reached. Invariants are properties of program states describing the integrity of the program and thus preventing bad surprises. The utility of invariants for program safey is widely recognized since the beginning of Computer Science. Invariants play an important role in DeFi security since "code is law" and code can be executed by everybody with no ability to revert transactions. Thus, when an invariant is violated, all bets are off. Invariants can either be enfored dynamically via runtime checks, or proved statically before the code is deployed via formal verification tools like the [Certora](https://www.certora.com) Prover. The invariant that the Notional Finance team wrote and checked in their code was unfortunately not describing the property the developers had in mind. Due to a logical error, the invariant was _vacuous_, i.e. there was no way to violate it. It thus showed up as "verified" in the output of the Certora Prover. A white hacker has since reported that the code is vulnerable, by reaching a program state that was expected to be infeasible. As soon as we received the report from the Notional Finance team, we studied the original invariant, corrected it to describe the original intention of the developers, and confirmed that the correct invariant could have flagged the issue beforehand. In this post, we describe both the wrong and correct invariants, and the lessons learned. In particular, we discuss our soon to be coming improvements to the tool to prevent such situations in the future. ## The state of the Notional Finance system An asset (or currency) deposited to an account in Notional can belong to either one of two types: "bitmap", which has to be explicitly enabled using the `enableBitmapCurrency` method, and "active", which is the automatic group to which an asset is assigned. It is expected that if a user calls `enableBitmapCurrency`, the system would ensure the asset is no longer marked as an "active" currency. In particular, assets are represented using 14 bits. Each asset can have up to two flags set for it, and so it takes up to 16 bits (or 2 bytes) in storage. Each account is associated with a `bitmapCurrencyId` field of type `uint16`, and with an `activeCurrencies` field of type `bytes18` (i.e., 144 bits), which holds up to 9 assets. For the state to be correct, a non-zero, 14-bit value representing the asset in `bitmapCurrencyId` must not appear in *any* of the slots of `activeCurrencies`. # The Vacuous Invariant The original invariant that was written to dsecribe the idea of non-intersecting assets was as follows: ``` // WRONG INVARIANT invariant bitmapCurrencyIsNotDuplicatedInActiveCurrencies( address account, uint144 i ) 0 <= i && i < 9 && getBitmapCurrency(account) != 0 && ( // When a bitmap is enabled it can only have currency masks // in the active currencies bytes (hasCurrencyMask(account, i) && getActiveUnmasked(account, i) == 0) || getActiveMasked(account, i) == 0 ) => getActiveUnmasked(account, i) != getBitmapCurrency(account) ``` The invariant is taking an account and an index in `activeCurrencies`, and is expected to check that the currency in the `i`th index is not equal to the bitmap currency (the right hand side of the implication, or the `conclusion`): `getActiveUnmasked(account, i) != getBitmapCurrency(account)`). The left hand side of the implication (the `premise`) was expected to set some natural requirements, e.g. that the index should be between 0 and 9. The invariant uses two auxiliary definitions for looking at the currency stored in slot `i`, one that includes just the 14 bits of the currency (`getActiveUnmasked`), and one that includes the flags (`getActiveMasked`). However, closer inspection of the invariant would show that the conclusion follows trivilly from the premise. In the premise, we first note that it must be that the bitmap currency is non-zero. We then analyze each disjunct separately: - `hasCurrencyMask(account, i) && getActiveUnmasked(account, i) == 0`: this tells us that the currency ID of interest (active unmasked currency ID in slot `i`) is 0. Combined with the information that the bitmap currency is non-zero, it follows directly that the currency ID we examine is not the bitmap currency. So the conclusion therefore follows immediately. - `getActiveMasked(account, i) == 0`: we note that in the spec, the `getActiveMasked` definition returns more bits than `getActiveUnmasked` (16 bits instead of just 14). Therefore, if `getActiveMasked(account, i) == 0` it must be the case that `getActiveUnmasked(account, i)` is also zero. The conclusion follows trivially by a similar argument to the previous case. It therefore follows that the conclusion cannot be ever false if the premise is true. When the Certora Prover checks this invariant, it tries to find a concrete input and state such that: - Before executing some public method in the code, the conclusion follows from the premise. - After executing some public method in the code, the premise is true but the conclusion is false. However, such an input state cannot exist, as the conclusion follows from the premise on all inputs and regardless of what method is executed. # A Corrected Invariant Once # The Certora Prover The Certora prover checks invariants before the code is executed. The Solidity code is compiled into EVM code using the Solidity compiler. Then the EVM code and the invariant is compiled into mathematical constraints. These constraints are solved using existing solvers. SHOW THE VIOLATED STATE # Lessons Learned One of the hardest problems in computer science is coming up with invariants. This requires careful thoghts about the system. The original invariant was almost right but vacoues. The Certora prover can be used to check that an invariant holds on all executions before the code is deployed. We are now adding checks to detect vacous invariants like these invariants. We plan to warn developers againts two types of vacoues rules: 1. Vacoues asserts and invariants. We check that there exist no state that violate the invariant. A simple vacoues invariant is *A-->A* or $A /\ !A$ 2. Vacous require statements. There exists no state which satisfies the expression. A simple exmple is $5> 7$ or $A /\ !A$. Both of cases can be easily prevented using the Certora prover before the code is verified. # Ackoledgements

    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