陳奕熹
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
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
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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Formal Verification on Smart Contract tags: Formal Verification, Smart Contract, Etherum description: View the slides with "Slide Mode". --- # Formal Verification on Smart Contract <!-- Put the link to this slide here so people can follow --> slides: https://hackmd.io/p/rJzvzC9TN#/ Note: Hello, everyone, I am chen yixi from cheng kung university. So, what is formal verification? and why do we need formal verification? --- ## ![](https://i.imgur.com/eyG0Zas.png) Debug challenges. Note: We had already spend a lot of time debuging compared to developing, and sometimes can not even make sure the efforts on debugging is actually meaningful. ---- ![](https://i.imgur.com/Iew5DGb.png =640x480) Note: Most of the time, we have to deal with something we are not familiar with. So we have to use profiler or debuger to trace or sometime guess the workflow. ---- ![](https://i.imgur.com/cSeEnJH.png =640x400) Confusing operations Note: For example, this is a very simple C implentation of getting an absolute value from a integer. If you are not used to bitwise operation, this might be a little confusing. And, if you think more about this function, how do we prove the correctness of this implementation ? ---- ![](https://i.imgur.com/DVSNXwT.png =1000x) Note: The first idea come into my mind might solve it with brute force, under current processor structure, we assume the whole operation took 50 cycles, so for a 32-bit integer, we will have to use 30 seconds for verification. And for 64-bit integer, we will then have to use almost 4000 years only to verify this simple function. ---- ## Why not just edge case ? ![](https://i.imgur.com/EZ0g5lk.png =800x)<!-- .element: class="fragment" data-fragment-index="1" --> Note: It sounds ridiculous to you, at least to me. So we use test case to detect some frequent mistakes like integer overflow. But how can we ganurantee the coverage of such test case ? And this is the exact counterexample for this implementation. ---- ![](https://i.imgur.com/sOhy50D.png) Compute arbitrary-precision square roots. Note: That is just a simplied example, and this is an real implementation on getting sqare root. This is way harder to get the meaningful test case. ---- ![](https://i.imgur.com/s33qps1.png) Note: And you might think, "it was all because the bad alignment of the coding style" ---- ```c= #define crBegin static int state=0; switch(state) { case 0: #define crReturn(x) do { state=__LINE__; return x; \ case __LINE__:; } while (0) #define crFinish } int decompressor(void) { static int c, len; crBegin; while (1) { c = getchar() if (c == EOF) break; if (c == 0xFF) { len = getchar(); c = getchar(); while (len--) crReturn(c); } else crReturn(c) } crReturn(EOF); crFinish; } ``` Co-routined version of a decompressor for RLE Note: And this is a decompressor for run-length encoding ---- ![](https://i.imgur.com/W4H4bVQ.png) Note: Designing testcase to verify the correctness is always available, however, it is hard to evaluate the effectness and coverage of different test case. Especially when we didn't have a concrete expectation on the specification. --- ![](https://i.imgur.com/gz6Zd2X.png) Note: I assumed that everybody has already know what is blockchain and smart contract, while Blockchain is a distributed ledger, and smart contract helps automate the trading process. ---- ## Cryptocurrency Theft ![](https://i.imgur.com/86wHIkv.png) Note: We all heard about huge finanical loss on cryptocurrency, the security issue is somehow different than what we used to see before. ---- ![](https://i.imgur.com/O0XxxUq.png =700x) Note: Take the DAO event for example, this is a simplified version of the buggy function. ---- ## Normal Usecase ![](https://i.imgur.com/eL4Y110.png) Atomic operation ?<!-- .element: class="fragment" data-fragment-index="1" --> Note: This is how the function "withdraw" should used. When someone, that say, the Wallet Contract tries to withdraw money from Contract DAO, it call function withdraw in Contract DAO, then function withdraw evaluate the value, then call back to Wallet Contract to notify it to receive money, and then modify DAO's balance. ---- ## Re-entrancy Abuse ![](https://i.imgur.com/NgDviOq.png) Note: However, if we change the "receiver function" in Wallet Contract to call withdraw again, since DAO hasn't modify its balance yet, the attacker will be able to call withdraw function for unlimited time in this section. ---- ## Smart Contract Challenges 1. Transactions are processed after a delay<!-- .element: class="fragment" data-fragment-index="1" --> 2. Adversaries can re-order and “frontrun” transactions<!-- .element: class="fragment" data-fragment-index="2" --> 3. All smart contract data is public<!-- .element: class="fragment" data-fragment-index="3" --> 4. Execution is expensive (gas costs, tx fees)<!-- .element: class="fragment" data-fragment-index="4" --> 5. Code is difficult to change (“Code is law”)<!-- .element: class="fragment" data-fragment-index="5" --> Note: Bitcoin can take hours to confirm a tranction The order of transaction within a time section is not ganuaranteed. ---- ## Verification Tools ![](https://i.imgur.com/mK3FG0B.png) Note: So there are many automatic verification tool to assure the correctness of smart contract. Today we'll be focus on KEVM. --- ## Formal Verfication ![](https://i.imgur.com/eJV86RP.png) Note: In KEVM, we re-write the spec into a formal semantic, and then verify it with the proof checker, in KEVM, it is pretty similar to compiler frontend, plus state transition to detect if there is a illegal operation. ---- ## Formal Semantics ![](https://i.imgur.com/pxTipLh.png) [EIP 20: ERC-20 Token Standard](https://eips.ethereum.org/EIPS/eip-20) Note: So, what is formal semantics? Let's look at the ERC20-spec, erc20 spec is a smart contract standard for exchanging ethereum to other 3rd party token. As you can see here, there are some interface like balanceof(), approve(), and today we will be focus on transferfrom() Transfrom() allow the 3rd party account to help transfer money from other account to account, the caller should be the 3rd party account, and from account, to account. ---- ![](https://i.imgur.com/SyARgrU.png) Note: Before the 3rd party account calls "transferFrom()", from_account should first call approve() function to permit 3rd party account for a certain amount of money. This make sense, right? ---- ![](https://i.imgur.com/ZNFsg5s.png =600x) 1. Allowance: Should we modify it ?<!-- .element: class="fragment" data-fragment-index="1" --> 2. Gas: Potential Gas Depletion ?<!-- .element: class="fragment" data-fragment-index="2" --> Note: But what if the to_account and from_account is the same account ? First, should we modify the allowance since it is a weird transaction ? And since it should always be successful, do we have to check the transfer value to make sure it is small enough ? Finally, the meaningless contraction also consume gas, which might in the end deplete the total gas storage ? ---- ## Formal Verfication Is Not A Magic [runtimeverification/erc20-semantics/erc20.k](https://github.com/runtimeverification/erc20-semantics/blob/master/erc20.k) ![](https://i.imgur.com/iL8ZdR3.png =800x) /\*uint128 a = 1\*/ Note: Formal Semantic is the requirement of conducting formal verification, formal verfication is not a magic, you must have to be fully aware of the whole structure behavior and possible side effects, otherwise, it is totally useless. Especially while nowadays project structures are getting more and more complex, the difficulty to construct a formal semantic is getting harder and harder. So formal verification requires lots of time and efforts, so it is too hard for massive deployment. ---- ## Formal Verification ![](https://i.imgur.com/iNiCvUN.png)<!-- .element: class="fragment" data-fragment-index="1" --> Note: But if you make it to the correct formal semantic of your specs and implementations, then we can move on to formal verification. Formal verification use the concept of symbolic execution. Take these two implementation for example, according to ERC20-spec, the totalSupply function should return the 3rd party token total amount, and the upper one should be the correct one, while the lower one is the crappy one. ---- ## Symbolic execution ![](https://i.imgur.com/sbJjNBx.png) Note: When there is a branch situatation, the workflow will split into applying different corresponding rule, and the whole graph is construct with series of condition state. Once the graph is completed, it will verify each available execution path by choosing a representing number that fullfill all the condition along with its path, and compare the result with spec and implementation. ---- ![](https://i.imgur.com/fDh5Hvq.png =900x) when supply != 0x1000....0000 ---- ![](https://i.imgur.com/VEtm1Zl.png =900x) when supply == 0x1000....0000 --- ## Reference 1. [Beginner Guide for EVM Execution](https://github.com/kframework/evm-semantics/blob/master/evm.md) 2. [K: A Semantic Framework for Programming Languages and Formal Analysis Tools, Grigore Rosu](https://pdfs.semanticscholar.org/7160/ab5a93942d49c3de7939e3699f21f51851a6.pdf) 3. [Detailed Kprove Beginner Guide](https://github.com/runtimeverification/verified-smart-contracts/blob/master/resources/kprove-tutorial.md) 4. [KAST syntax guide](https://github.com/kframework/k-legacy/wiki/KAST) 5. [Formal verification of ERC-20 contracts ( Very Useful )](https://runtimeverification.com/blog/erc-20-verification/) 6. [Formal Verification of HackerGold (HKG) ERC20 Token Contract](https://github.com/runtimeverification/verified-smart-contracts/tree/master/erc20/hkg) 7. [Formal verification of ERC-20 contracts](https://runtimeverification.com/blog/erc-20-verification/)

    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