智能合約設計模式--COP

Design by contract

solidity這門語言設計思路是什麼?
什麼是COP?程序員

COP

Design by contract

面向條件的編程(COP)是面向合約編程的一個子域,做爲一種面向函數和命令式編程的混合模式。COP解決了這個問題,經過須要程序員顯示地枚舉全部的條件。邏輯變得扁平,沒有條件的狀態變化。條件片斷能夠被正確的文檔化,複用,能夠根據需求和實現來推斷。重要的是,COP在編程中把預先條件看成爲一等公民。這樣的模式規範能保證合約的安全。編程

post-condition

contract PostCheck {

    uint public data = 0;

    // Check that the 'data' field was set to the value of '_data'.
    modifier data_is_valid(uint _data) {
        _
        if (_data != data)
            throw;
    }

    function setData(uint _data) data_is_valid(_data) {
        data = _data;
    }

}

pre- and post-conditions

"_"安全

contract PrePostCheck {

    uint public data = 0;

    // Check that the input '_data' value is not the same as the value
    // already stored in 'data'.
    modifier data_is_valid(uint _data) {
        if (_data == data)
           throw;
        _
    }

    // Check that the 'data' field was set to the value of '_data'.
    modifier data_was_updated(uint _data) {
        _
        if (_data != data)
            throw;
    }

    function setData(uint _data) data_is_valid(_data) data_was_updated(_data) {
        data = _data;
    }

}

FEATURES

  • 函數主體沒有條件判斷

例子:app

contract Token {
    // The balance of everyone
    mapping (address => uint) public balances;
    // Constructor - we're a millionaire!
    function Token() {
        balances[msg.sender] = 1000000;
    }
    // Transfer `_amount` tokens of ours to `_dest`.
    function transfer(uint _amount, address _dest) {
        balances[msg.sender] -= _amount;
        balances[_dest] += _amount;
    }
}

改進後:函數

function transfer(uint _amount, address _dest) {
    if (balances[msg.sender] < _amount)
        return;
    balances[msg.sender] -= _amount;
    balances[_dest] += _amount;
}

COP的風格post

modifier only_with_at_least(uint x) {
    if (balances[msg.sender] >= x) _;
}

function transfer(uint _amount, address _dest)
only_with_at_least(_amount) {
    balances[msg.sender] -= _amount;
    balances[_dest] += _amount;
}

擴展閱讀:

相關文章
相關標籤/搜索