MixBytes
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • 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 Help
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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    ![](https://i.imgur.com/FBTn5C5.gif) # Introduction [ChatGPT](https://chat.openai.com/) has brought about a considerable transformation in programming and research. This article will delve into various prompts that can be immensely beneficial for a security auditor. # Before You Start To ensure OpenAI doesn't utilize your conversation for model training while auditing, remember to disable the checkbox: ![](https://hackmd.io/_uploads/rkV0jHoK3.png) # Beware of the Problem with Input Size As you may have anticipated, GPT has its limitations when it comes to input size: ![](https://hackmd.io/_uploads/HJI1Y5Tth.png) We also encountered an unexpected bug in GPT-4, where it silently disregarded the lower part of the input without any indication of an error. For instance, when we fed a big contract into GPT-3.5 and asked it to disregard everything above and just answer "1+1=?", it impressively provided the correct answer: ![](https://hackmd.io/_uploads/BkOft56th.png) However, GPT-4 simply summarized the top part of the input, completely overlooking the question: ![](https://hackmd.io/_uploads/rJN7Kc6K3.png) This could lead to a negative situation where GPT-4 appears to offer analysis but actually cuts off your request, missing crucial information at the bottom. Beware! # 1. "Find vulnerabilities!" The most obvious way to use ChatGPT is to ask ChatGPT to discover vulnerabilities in the code. Let's try doing this for a small staking contract [[→ see code]](https://gist.github.com/knek-little-projects/51e59a52f15e21cf83893c03f58c27b4). The contract had several issues that we would like to identify via GPT: 1. A DOS vulnerability in `unstake()` when dealing with a large stake. 2. The confusion between`_reward` and `_amount` in `unstake()`. 3. The problem of calling `stake()` twice overwrites the user's previous stake. We presented the prompt as follows: "Find vulnerabilities" → "More" → "More": ![](https://hackmd.io/_uploads/rJdB9caF2.png) The result: Version | Vuln #1 | Vuln #2 | Vuln #3 | False Alarms -|-|-|-|- GPT-3.5 | - | - | - | 18 GPT-4 | FOUND | - | FOUND | 20 Both GPT-3.5 and GPT-4 raised several false alarms, with GPT-3.5 performing the worst. However, GPT-4 impressively identified two out of the three vulnerabilities! Great job! In summary, GPT can be effectively used as a scanner for small, isolated contracts or functions, thereby enhancing the quality of audits. However, brace yourself for a considerable number of false alarms and don't expect it to uncover all vulnerabilities. Keep in mind that applying this method to large contracts poses challenges: * GPT cannot handle large inputs, necessitating the division of the contract into parts. But be cautious, as GPT starts to forget various details from the beginning of the conversation as you send parts, ultimately affecting the result. * Additionally, if the contract you're auditing involves external integrations or inherits from other contracts, ensure you provide GPT with documentation for these dependencies. Without understanding the context, GPT may yield subpar results.So, proceed with care! # 2. "Simplify the code..." At the outset of an audit, your primary mission is to grasp the inner workings of the protocol at a high level. With the aid of GPT, you possess a powerful tool to streamline complex code, clarify variable names, remove unnecessary comments or events, reduce the code by substituting certain arguments. All of this accelerates your immersion into the protocol. Let's embark on this with a practical example – simplifying the `liquidate_extended()` and `_liquidate()` functions from crvUSD [[→see code]](https://github.com/curvefi/curve-stablecoin/blob/64dc13db563ec6067c75c662ee71a285442ef638/contracts/Controller.vy#L994-L1106). The code of these functions is fed into GPT-4, and prompts are employed one by one, watching the result: ``` 1. Merge _liquidate() into liquidate_extended() 2. Simplify the code knowing that the argument `user` is always equal to `msg.sender` 3. Simplify the code knowing that the argument `use_eth` is always equal to `true` 4. Simplify the code knowing that the argument `frac` is always equal to `10**18` 5. Simplify the code knowing that the argument `min_x` is always equal to `0` 6. Strip types 7. Replace `xy = ...` to `stablecoin_amount, collateral_amount = ...` 8. Simplify the code by adding a `require(debt > stablecoin_amount)` 9. Simplify the code knowing that `callbacker` is always `empty(address)` 10. Replace unsafe_ by respective math ops ``` This is what we get in the end: ```solidity def liquidate_extended(): """ Perform a bad self-liquidation if health is not good """ debt, rate_mul = self._debt(msg.sender) stablecoin_amount, collateral_amount = AMM.withdraw(msg.sender, self._get_f_remove(10**18, 0)) require(debt > stablecoin_amount) STABLECOIN.transferFrom(AMM.address, self, stablecoin_amount) to_repay = debt - stablecoin_amount self._withdraw_collateral(msg.sender, collateral_amount) STABLECOIN.transferFrom(msg.sender, self, to_repay) self.redeemed += debt self.loan[msg.sender] = Loan({initial_debt: 0, rate_mul: rate_mul}) self._remove_from_list(msg.sender) d = self._total_debt.initial_debt * rate_mul / self._total_debt.rate_mul self._total_debt.initial_debt = max(d, debt) - debt self._total_debt.rate_mul = rate_mul ``` The outcome reveals a transformed code, now remarkably more comprehensible than its [original version](https://github.com/curvefi/curve-stablecoin/blob/64dc13db563ec6067c75c662ee71a285442ef638/contracts/Controller.vy#L994-L1106). Now we can scroll up our dialogue with GPT-4 and modify certain prompts. For example, we could ask it to simplify the code for the case `callbacker==msg.sender`, to see a different code flow for this function. These simplifications can be highly beneficial during the initial stages of an audit especially when you need to quickly understand the high-level workings of the protocol. Important notes: * GPT-4 performed great! * GPT-3.5 failed and produced wrong code. * GPT-4 also fails when we ask it to do everything at once with a single combined prompt instead of 10 consecutive requests. # 3. Checking Invariants Harness the GPT to unlock the secrets of invariants, especially when confronted with formidable tasks like navigating through vast functions and unraveling code paths with significant ramifications. Let's consider `adjustTrove()` and `_adjustTrove()` functions from Ethos (clone of LUSD) as an example [[→ see code]](https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L268-L373). Suppose we seek to uncover scenarios where the fee eludes the grasp of the caller. We use the prompt: ![](https://hackmd.io/_uploads/H12GTqaYh.png) GPT-4 accurately suggests that the fee is only levied under specific conditions: `_isDebtIncrease=true && isRecoveryMode=false`. Great! With the ability to automatically identify logical paths with specific consequences, you can quickly and effortlessly check your suspicions about various vulnerabilities. # 4. Question Mining An auditor's prowess soars with each challenging question they pose and answer, for it enriches the tapestry of the audit's quality. Why not harness GPT's intellect to generate questions for us? We're not after mundane checklists; we crave astute inquiries that are relevant and easily verifiable. Behold the magic template we conjured: ``` Imagine you are a security researcher and you are auditing [DESCRIBE THE PROJECT]. [DESCRIBE TECHNICAL DETAILS]. To find vulnerabilities in the project, you must read these functions and ask three of the most important edge-case questions about them. This will help you identify bugs or vulnerabilities. What would those three questions be? Ask very specific questions and provide suspicious arguments and code path you want to check. ``` Yet, heed the delicate balance! The quality of GPT's responses dances upon the prompt. Take for instance some code from [crvUSD](https://github.com/curvefi/curve-stablecoin). First, we merged several of its functions [[1](https://github.com/curvefi/curve-stablecoin/blob/64dc13db563ec6067c75c662ee71a285442ef638/contracts/Controller.vy#L574-L617),[2](https://github.com/curvefi/curve-stablecoin/blob/64dc13db563ec6067c75c662ee71a285442ef638/contracts/AMM.vy#L662-L743)] into one [[→ see code]](https://gist.github.com/knek-little-projects/10d9ff262d281212852a31c627eb7ece). And then prompted: ![](https://hackmd.io/_uploads/S1GMDk0t3.png) To assess the quality of generation, we divided the resulting questions into three categories: 1. **Nonsense.** For example, when GPT suggests checking negative values of uin256. 2. **Lazy.** For example, when it asks what will happen if you pass the `collateral==0`, even though there's a check in the code `assert collateral * X / Y > 100`, which forbids zero values. 3. **Vague.** For example, when it suggests checking all unsafe math operations in the code. This is a typical question from a static checklist and we don't need that. 4. **Good, specific question.** For example, when GPT states that `create_loan()` can accept a `collateral` value that doesn't match `msg.value`, and there's a call to an unknown part of the code, `_deposit_collateral(collateral, msg.value)`. And GPT wonders: does this unknown function correctly deal with these two values possibly not matching? Merging several functions, we engaged GPT-4 to weave 15 questions, and here's what we got: Generated questions | Quantity -|- Nonsense | 1 Lazy | 1 Vague | 0 Good specific question | 13 Great result! # Conclusion We've unveiled some techniques that accelerate your understanding of a protocol and elevate the grandeur of your audits. The realm of AI is a burgeoning landscape, and fear not, for mastery of this amazing tool shall lead you to extraordinary feats. So, embrace the power of GPT, and together, we shall embark on an endless journey of discovery! ![](https://hackmd.io/_uploads/SyyGKl0tn.png)

    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