A guide to smart contract security best practices

Smart Contract Security Best Practices

Visit the documentation site: https://consensys.github.io/smart-contract-best-practices/

Read the docs in Chinese: https://github.com/ConsenSys/smart-contract-best-practices/blob/master/README-zh.md Read the docs in Vietnamese: https://github.com/ConsenSys/smart-contract-best-practices/blob/master/README-vi.md

Contributions are welcome!

Feel free to submit a pull request, with anything from small fixes, to full new sections. If you are writing new content, please reference the contributing page for guidance on style.

See the issues for topics that need to be covered or updated. If you have an idea you'd like to discuss, please chat with us in Gitter.

If you've written an article or blog post, please add it to the bibliography.

Building the documentation site

git clone [email protected]:ConsenSys/smart-contract-best-practices.git
cd smart-contract-best-practices
pip install -r requirements.txt
mkdocs build 

You can also use the mkdocs serve command to view the site on localhost, and live reload whenever you save changes.

Redeploying the documentation site

mkdocs gh-deploy
Owner
ConsenSys Software
ConsenSys is the software engineering leader of the blockchain space. Our full-stack Ethereum products help developers build next-generation networks.
ConsenSys Software
Comments
  • Meta Issue for Gitcoin Bounty

    Meta Issue for Gitcoin Bounty

    Assigment: Add to the ConsenSys Best Practices repository

    Description

    Our documentation should be updated to remain current. We are looking to work with a single contributor who can:

    1. Write in a similar style as the existing content
    2. Has a strong understanding of solidity and the EVM
    3. Can ask well formulated questions, and perform their own research in order to flesh out the very brief descriptions in issues listed below
    4. Has reviewed the existing content, understands the layout, and can make good judgements about where to add new content.

    The following issues describe the work to be done.

    • [x] #169
    • [x] #170
    • [x] #83 (the most recent comments need to be addressed)
    • [x] #55
    • [x] #133
  • Contribute to  the Smart Contract Best Practices

    Contribute to the Smart Contract Best Practices

    About the ConsenSys Smart Contract Best Practices

    Our best practices are the most popular security reference for smart contract developers. We're looking for help maintaining and expanding them.

    Tasks

    Create documentation for 3 unaddressed issues:

    • [ ] #182
    • [ ] #171
    • [ ] #129

    Important

    We are looking to work with a single contributor who can:

    1. Write in a similar style as the existing content
    2. Has a strong understanding of solidity and the EVM
    3. Can ask well formulated questions, and perform their own research in order to flesh out the very brief descriptions in issues listed below
    4. Has reviewed the existing content, understands the layout, and can make good judgements about where to add new content.
  • Add a new section for operational security best practices.

    Add a new section for operational security best practices.

    ISSUE: There are many security consideration outside of programming and architecture, which are not covered here.

    PR REQUEST: A new section should be created (including modifying the [yaml config(https://github.com/ConsenSys/smart-contract-best-practices/blob/master/mkdocs.yml)), which presents the various operational considerations necessary when deploying a contract system.

    These include existing issues:

    [] #92 [] #85 [] #79 [] #97

    As well as: [] proper cold storage for critical private keys [] possible recommendations for M and N on a multisig wallet [] other

  • Add bad usage of EXTCODESIZE

    Add bad usage of EXTCODESIZE

    Added a small write-up of how extcodesize should not be used for verifying externally owned accounts, which unfortunately is fairly common and easily exploitable [1].

  • Should we lock pragma?

    Should we lock pragma?

    This guide argues that pragma be locked to a specific version.

    The Ethereum Solidity guide argues that pragmas should be allowed to move up in the patch version (e.g., ^0.4.20 rather than 0.4.20):

    We do not fix the exact version of the compiler, so that bugfix releases are still possible.

    We should probably debate this, and then make a recommendation. Are there examples in the past where either way caused an issue? If both have caused issues, may want to just highlight tradeoff. Anyone else we should consult on this?

    (cc: @ethers)

  • Reorder the attacks and recommendations sections

    Reorder the attacks and recommendations sections

    The attacks and recco's sections have lots of good content, but need some organization to facilitate navigation.

    I think each page could be divided into at least two top level categories:

    1. Protocol specific
    2. Solidity specific

    This would help differentiate between the fundamental security issues, and ones specific to solidity. It might also help to prepare use for a multi-evm language future.

  • Please add a warning about using Constant State Variables

    Please add a warning about using Constant State Variables

    Details documented in TIB (Today I Burnt) 0.01 ETH Using Constant State Variables In A Solidity Contract.

    Using a constant state variables produces unexpected results, for example:

    uint256 public constant PRESALE_START_DATE = now;
    uint256 public constant PRESALE_END_DATE = PRESALE_START_DATE + 15 minutes;
    uint256 public constant OWNER_CLAWBACK_DATE = PRESALE_START_DATE + 20 minutes;
    

    The variables:

    • PRESALE_START_DATE will ALWAYS have the current time value
    • PRESALE_END_DATE will ALWAYS have a date 15 minutes in the future
    • OWNER_CLAWBACK_DATE will ALWAYS have a date 20 minutes in the future

    Sample contract at 0xe67907329dafd1ff826523e3f491bec8733f7376. Refresh the page and you will see these constant variables update. DO NOT SEND FUNDS TO THIS CONTRACT

  • I think the

    I think the "Pitfalls in Race Condition Solutions" can not work the way you expect

    You've mentioned in your wiki that to solve race condition attack, one can use a lock variable. I quote your code here. And I don't think a lock variable can solve parallel invoking. As you are setting lockBalances to true, I can still go into the withdraw function and thus withdraw the balance again.

    function deposit() public returns (bool) {
        if (!lockBalances) {
            lockBalances = true;
            balances[msg.sender] += msg.value;
            lockBalances = false;
            return true;
        }
        throw;
    }
    
    function withdraw(uint amount) public returns (bool) {
        if (!lockBalances && amount > 0 && balances[msg.sender] >= amount) {
            lockBalances = true;
    
            if (msg.sender.call(amount)()) { // Normally insecure, but the mutex saves it
              balances[msg.sender] -= amount;
            }
    
            lockBalances = false;
            return true;
        }
    
        throw;
    }
    
  • Add README-vi.md for VietNammese Language

    Add README-vi.md for VietNammese Language

    I am a Blockchain developer in VietNam. I see your document is very good. I decided to translate overall your document from English to VietNamese. Thank you !

  • Improve upgradeability section

    Improve upgradeability section

    This post from our friends at Trail of Bits made reference to some outdated content in our best practices.

    It definitely needs to be revisited, and in the shorter term, possibly removed or wrapped in a big fat caveat.

  • Replace rate limiting example

    Replace rate limiting example

    In this section, we have an example circuit breaker contract that performs a rate limiting technique. However, in my opinion, the current example is more complex than necessary, and somewhat unclear.

    Here I've simplified the current example.

        uint internal period; // how many blocks before limit resets
        uint internal limit; // max ether to withdraw per period
        uint internal currentPeriodEnd; // block which the current period ends at
        uint internal currentPeriodAmount; // amount already withdrawn this period
        
        constructor(uint _period, uint _limit) public {
            period = _period;
            limit = _limit;
            
            currentPeriodEnd = block.number + period;
        }
         
        function withdraw(uint amount) public {
            // Update period before proceeding
            updatePeriod();
            
            // Disallow withdraws that exceed current rate limit
            require(currentPeriodAmount + amount < limit, 'exceeds period limit');
            currentPeriodAmount += amount;
            msg.sender.transfer(amount);
        }
        
        function updatePeriod() internal {
            if(currentPeriodEnd < block.number) {
                currentPeriodEnd = block.number + period;
                currentPeriodAmount = 0;
            }
        }
    
  • Delete

    Delete "Insecure Arithmetic" Page?

    Now that "Solidity automatically reverts on integer overflow and underflow, as of version 0.8.0." shall we delete the Insecure Arithmetic page?

  • Explicitly declare state variables

    Explicitly declare state variables

    Reading the docs I found out that some of the state variables are left at the defaults, since this a developer guide with good securities measures shouldn't them be explicitly declared to public / private ?

  • Event Monitoring suggests using `transfer()`

    Event Monitoring suggests using `transfer()`

Troon-NFT-Contract is deployed on Flow Blockchain, which is a white-label smart-contract for NFTs with an addition layer of Brand, Schema and Template

Overview Summary of NFTContract NFTContract is a Non Fungible Token (NFT) standard for Flow blockchain. It offers a powerful set while keeping unneces

Jan 4, 2022
An interoperable smart contract hub
An interoperable smart contract hub

Juno An interoperable smart contract hub which automatically executes, controls or documents a procedure of relevant events and actions according to t

Jan 1, 2023
A smart contract development toolchain for Go

ethgen - A smart contract development toolchain for Go A simple yet powerful toolchain for Go based smart contract development Compile solidity contra

Sep 14, 2022
A Gomora template for building dApps and web3-powered API and smart contract listeners

Gomora dApp A Gomora template for building dApps and web3-powered API and smart contract listeners Local Development Setup the .env file first cp .env

Feb 15, 2022
OpenZeppelin Contracts is a library for secure smart contract development.

A library for secure smart contract development. Build on a solid foundation of community-vetted code. Implementations of standards like ERC20 and ERC

Jan 5, 2023
An open source smart contract platform

EOSIO - The Most Powerful Infrastructure for Decentralized Applications Welcome to the EOSIO source code repository! This software enables businesses

Jan 7, 2023
this is an on-hand guide to cosmos ibc for noobs

cosmos-ibc-for-dummies This is an on-hand guide to cosmos ibc for noobs This guide focuses only on modules/apps section of IBC to show how to build a

Dec 2, 2021
Return list of the contract's events logs

Return list of the contract's events logs Return contract's events logs via sending address, from_block and to_block range only as RAW data. Working w

Oct 12, 2021
Abigen by contract address using etherscan api

Abigen for zoomers Just a simple wrapper to fetch abis from etherscan and run abigen on it. Uses the name of a contract if possible. Usage First put y

Mar 24, 2022
A binary that continuously displays Ethiopian date and time (Amharic). best used in i3-status.

i3-eth-time Display ethiopian calendar date/time in i3-wm! Intended for use in i3-status. How to use Clone/Download repo and compile Open up your i3co

Jan 4, 2022
DERO: Secure, Anonymous Blockchain with Smart Contracts. Subscribe to Dero announcements by sending mail to [email protected] with subject: subscribe announcements
DERO: Secure, Anonymous Blockchain with Smart Contracts.  Subscribe to Dero announcements by sending mail to lists@dero.io with subject: subscribe announcements

Welcome to the Dero Project DERO News Forum Wiki Explorer Source Twitter Discord Github Stats WebWallet Medium Table of Contents ABOUT DERO PROJECT DE

Dec 7, 2022
The bare metal Go smart card
The bare metal Go smart card

Authors Andrea Barisani [email protected] | [email protected] Introduction The GoKey application implements a USB smartcard in pure Go

Dec 8, 2022
Yet another Binance Smart Chain client based on TrustFi Network

TrustFi Smart Chain The goal of TrustFi Smart Chain is to bring programmability and interoperability to Binance Chain. In order to embrace the existin

Mar 27, 2021
The Fabric Smart Client is a new Fabric Client that lets you focus on the business processes and simplifies the development of Fabric-based distributed application.

Fabric Smart Client The Fabric Smart Client (FSC, for short) is a new Fabric client-side component whose objective is twofold. FSC aims to simplify th

Dec 14, 2022
Arbitrum is a Layer 2 cryptocurrency platform that makes smart contracts scalable, fast, and private.
Arbitrum is a Layer 2 cryptocurrency platform that makes smart contracts scalable, fast, and private.

Arbitrum is a Layer 2 cryptocurrency platform that makes smart contracts scalable, fast, and private. Arbitrum interoperates closely with Ethereum, so Ethereum developers can easily cross-compile their contracts to run on Arbitrum. Arbitrum achieves these goals through a unique combination of incentives, network protocol design, and virtual machine architecture.

Jan 8, 2023
Tools to help teams develop smart contracts on the Cardano blockchain
Tools to help teams develop smart contracts on the Cardano blockchain

toolkit-for-cardano toolkit-for-cardano simplifies the development of Cardano smart contracts by providing teams with frequently needed tasks: Build T

Dec 19, 2022
Akroma GO client - Akroma is an EVM based application development platform (smart-contracts).

Akroma Akroma is an EVM based application development platform (smart-contracts). Akroma will utilize a Masternode system, and build out an Oracle pla

Dec 11, 2022
A Binance Smart Chain client based on the go-ethereum fork

A Binance Smart Chain client based on the go-ethereum fork

Dec 31, 2022
Golang libraries for generating QR codes for Smart Health Cards representing COVID-19 Immunizations
Golang libraries for generating QR codes for Smart Health Cards representing COVID-19 Immunizations

go-smarthealthcards Golang libraries for generating QR codes for Smart Health Cards representing COVID-19 Immunizations. Usage Individual Libraries Yo

Dec 5, 2021