A guide to smart contract security best practices

Overview

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
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
    opened by maurelian 15
  • 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.
    opened by maurelian 14
  • 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

    help wanted To Do opsec 
    opened by maurelian 12
  • 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].

    opened by f-daniel 9
  • 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)

    opened by nemild 9
  • 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.

    help wanted 
    opened by maurelian 8
  • 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

    opened by bokkypoobah 7
  • 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;
    }
    
    opened by maiffany 7
  • 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 !

    opened by conglt10 6
  • 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.

    help wanted To Do 
    opened by maurelian 6
  • 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;
            }
        }
    
    To Do 
    opened by kadenzipfel 5
  • 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?

    opened by David-B-Diligence 0
  • 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 ?

    opened by tonynoce 0
  • Event Monitoring suggests using `transfer()`

    Event Monitoring suggests using `transfer()`

    opened by David-B-Diligence 0
  • Broken links in `README.md`

    Broken links in `README.md`

    Contexts:

    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.

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

    Problem:

    Here, the contributing and bibliography redirects do not function as intended, and lead to a 404/Path not found error.

    Solution:

    If they do exist, the problem most likely arises because of the GitHub change from master to main and can be fixed as such.

    Cheers!

    opened by krakxn 0
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
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

null 0 Jan 4, 2022
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

Juno 249 Dec 1, 2022
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

Tally 34 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

Nuxify Inc. 3 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

OpenZeppelin 20.7k Dec 3, 2022
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

EOSIO 11.3k Nov 28, 2022
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

null 0 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

Ali Shokoohi 1 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

Sina Khalili 1 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

Tibebes. 1 Jan 4, 2022
DERO: Secure, Anonymous Blockchain with Smart Contracts. Subscribe to Dero announcements by sending mail to [email protected] 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

null 274 Nov 28, 2022
The bare metal Go smart card

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

F-Secure Foundry 143 Nov 28, 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

TrustFi Network 19 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

null 42 Nov 15, 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 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.

Offchain Labs 997 Dec 7, 2022
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

SundaeSwap Finance 137 Nov 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

null 3 Jul 24, 2022
A Binance Smart Chain client based on the go-ethereum fork

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

null 1.9k Nov 29, 2022
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

Amit Gupta 0 Dec 5, 2021