《以太坊技术详解与实战》第6章 - 智能合约案例详解

在第 5 章中,我们介绍了智能合约的编译工具 Solc 、开发框架 Truffle 、集成开发环境Remix ,以及开发智能合约时需要注意的安全性问题 。 结合第 4 章中 Solidity 的基础知识,开发者已经学习如何开发、部署、调试一个以太坊智能合约了 。 前两章中我们也给出了一些智能合约的示例代码,但是这些示例都很简单,主要是用来介绍 Solidity 语法和基本功能的 。 在这一章中我们会介绍几个有具体应用场景的智能合约,这些智能合约部分来自于Solidity 官网上的示例(见:https://solidity.readthedocs.io/en/v0.4.25/solidity-by-example.html),十分有代表性,能体现出以太坊智能合约的主要特性 。 本章会对这些例子进行深入的剖析和解读,并且挖掘其中隐含的问题,提出针对性的建议和优化 。 通过分析和学习这些示例,开发者会对去中心化应用和以太坊智能合约有更深入的认识 。

6.1投票

在现实生活中,投票是一个最能体现公平民主的机制,而且有广泛的应用场景 。 但是以往的投票过程,都或多或少存在着人为干预的风险,而区块链提供了公开透明、不可篡改的技术保障,使得利用区块链技术进行投票有着天然的可靠性 。
以太坊官方也给出了一个针对投票的智能合约示例 Ballot。 Ballot 合约是一个十分完整的投票智能合约,这个合约不仅支持基本的投票功能,投票人还可以将自己的投票权委托给其他人 。 虽然投票人身份和提案名称是由合约发布者制定的,不过这不影响投票结果的可信度 。 这个合约相对比较复杂,也展示出了一个去中心智能合约运作的很多特性 。

pragma solidity ^0.4.22;

/// @title Voting with delegation.
contract Ballot {
    // This declares a new complex type which will
    // be used for variables later.
    // It will represent a single voter.
    //投票者 Voter 的数据结构
    struct Voter {
        uint weight; // weight is accumulated by delegation,  该投票者的投票所占的权重
        bool voted;  // if true, that person already voted,  是否已经投过票
        address delegate; // person delegated to,  该投票者投票权的委托对象
        uint vote;   // index of the voted proposal,  投票对应的提案编号( Index )
    }

    // This is a type for a single proposal. 
    // 提案 Proposal 的数据结构
    struct Proposal {
        bytes32 name;   // short name (up to 32 bytes) ,  提案的名称
        uint voteCount; // number of accumulated votes,  该提案目前的票数
    }
	
	//投票的主持人
    address public chairperson;

    // This declares a state variable that
    // stores a `Voter` struct for each possible address.
    // 投票者地址和状态的对应关系
    mapping(address => Voter) public voters;

    // A dynamically-sized array of `Proposal` structs.
    // 提案的列表
    Proposal[] public proposals;

    /// Create a new ballot to choose one of `proposalNames`.
    // 在初始化合约时 , 给定一个提案名称的列表
    constructor(bytes32[] proposalNames) public {
        chairperson = msg.sender;
        voters[chairperson].weight = 1;

        // For each of the provided proposal names,
        // create a new proposal object and add it
        // to the end of the array.
        for (uint i = 0; i < proposalNames.length; i++) {
            // `Proposal({...})` creates a temporary
            // Proposal object and `proposals.push(...)`
            // appends it to the end of `proposals`.
            proposals.push(Proposal({
                name: proposalNames[i],
                voteCount: 0
            }));
        }
    }

    // Give `voter` the right to vote on this ballot.
    // May only be called by `chairperson`.
    // 只有 chairperson 有给 toVoter 地址投票的权利
    function giveRightToVote(address voter) public {
        // If the first argument of `require` evaluates
        // to `false`, execution terminates and all
        // changes to the state and to Ether balances
        // are reverted.
        // This used to consume all gas in old EVM versions, but
        // not anymore.
        // It is often a good idea to use `require` to check if
        // functions are called correctly.
        // As a second argument, you can also provide an
        // explanation about what went wrong.
        require(
            msg.sender == chairperson,
            "Only chairperson can give right to vote."
        );
        require(
            !voters[voter].voted,
            "The voter already voted."
        );
        require(voters[voter].weight == 0);
        voters[voter].weight = 1;
    }

    /// Delegate your vote to the voter `to`.
    // 投票者将自己的投票机会授权另外一个地址
    function delegate(address to) public {
        // assigns reference
        Voter storage sender = voters[msg.sender];
        require(!sender.voted, "You already voted.");

        require(to != msg.sender, "Self-delegation is disallowed.");

        // Forward the delegation as long as
        // `to` also delegated.
        // In general, such loops are very dangerous,
        // because if they run too long, they might
        // need more gas than is available in a block.
        // In this case, the delegation will not be executed,
        // but in other situations, such loops might
        // cause a contract to get "stuck" completely.
        while (voters[to].delegate != address(0)) {
            to = voters[to].delegate;

            // We found a loop in the delegation, not allowed.
            require(to != msg.sender, "Found loop in delegation.");
        }

        // Since `sender` is a reference, this
        // modifies `voters[msg.sender].voted`
        sender.voted = true;
        sender.delegate = to;
        Voter storage delegate_ = voters[to];
        if (delegate_.voted) {
            // If the delegate already voted,
            // directly add to the number of votes
            proposals[delegate_.vote].voteCount += sender.weight;
        } else {
            // If the delegate did not vote yet,
            // add to her weight.
            delegate_.weight += sender.weight;
        }
    }

    /// Give your vote (including votes delegated to you)
    /// to proposal `proposals[proposal].name`.
    // 投票者根据提案列表编号 ( proposal ) 进行投票
    function vote(uint proposal) public {
        Voter storage sender = voters[msg.sender];
        require(!sender.voted, "Already voted.");
        sender.voted = true;
        sender.vote = proposal;

        // If `proposal` is out of the range of the array,
        // this will throw automatically and revert all
        // changes.
        proposals[proposal].voteCount += sender.weight;
    }

    /// @dev Computes the winning proposal taking all
    /// previous votes into account.
    // 根据 proposals 里的票数统计 ( voteCount ) 计算出票数最多的提案 编号
    function winningProposal() public view
            returns (uint winningProposal_)
    {
        uint winningVoteCount = 0;
        for (uint p = 0; p < proposals.length; p++) {
            if (proposals[p].voteCount > winningVoteCount) {
                winningVoteCount = proposals[p].voteCount;
                winningProposal_ = p;
            }
        }
    }

    // Calls winningProposal() function to get the index
    // of the winner contained in the proposals array and then
    // returns the name of the winner
    // 获取票数最多的提案名称。其 中调用了 winningProposal () 函数
    function winnerName() public view
            returns (bytes32 winnerName_)
    {
        winnerName_ = proposals[winningProposal()].name;
    }
}

你可能感兴趣的:(区块链)