3
1

More than 3 years have passed since last update.

[solidity]コントラクトにバグが見つかった場合にコントラクトの実行を止めるデザインパターン(Emergency Stop)

Posted at

記事の内容

コントラクトは一度デプロイされると修正が出来ないので、バグが見つかった場合に安全に実行出来なくする必要があります。
この記事ではそのデザインパターンをメモ

参考

solidity-patterns Emergency Stop

想定するユースケース

コントラクトをパブリック型で使用する場合 かつ 送金処理などの不正利用による被害に繋がる可能性がある場合

サンプルコード

pragma solidity ^0.5.16;

contract EmergencyStop {

    bool isStopped = false;

    modifier stoppedInEmergency {
        require(!isStopped);
        _;
    }

    modifier onlyWhenStopped {
        require(isStopped);
        _;
    }

    modifier onlyAuthorized {
        // Check for authorization of msg.sender here
        _;
    }

    function stopContract() public onlyAuthorized {
        isStopped = true;
    }

    function resumeContract() public onlyAuthorized {
        isStopped = false;
    }

    function deposit() public payable stoppedInEmergency {
        // Deposit logic happening here
    }

    function emergencyWithdraw() public onlyWhenStopped {
        // Emergency withdraw happening here
    }
}

ざっくりコード解説

    modifier stoppedInEmergency {
        require(!isStopped);
        _;
    }

    modifier onlyWhenStopped {
        require(isStopped);
        _;
    }

内部変数を見て処理を実施するか判断を行う修飾子の定義

    function stopContract() public onlyAuthorized {
        isStopped = true;
    }

    function resumeContract() public onlyAuthorized {
        isStopped = false;
    }

処理実行判定用の内部変数切り替え関数

    function deposit() public payable stoppedInEmergency {
        // Deposit logic happening here
    }

    function emergencyWithdraw() public onlyWhenStopped {
        // Emergency withdraw happening here
    }

内部変数がTrueの時、Falseの時それぞれで動作する関数

簡単な作りですが、この作りでコントラクト内にバグが見つかった場合、安全に動作を止めることが出来ます。

Emergency Stopパターンが使われているコード

OpenZeppelin Pausable.sol

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1