用例子说明 Solidity

投票

下面的合同很复杂,但是展示了Solidity的很多特性。它执行投票合同。当然,电子投票的主要问题是如何将投票权分配给正确的人,以及如何防止操纵。我们不会解决这里的所有问题,但至少我们会展示如何进行委托投票,从而使计票 自动且完全透明 同时。

其想法是在每张选票上创建一个合同,为每个选项提供一个简短的名称。然后,担任主席的合同创建者将赋予对每个地址单独投票的权利。

地址后面的人可以选择投票给他们自己,或者把他们的投票委托给他们信任的人。

投票结束时, winningProposal() 将以最大票数返回提案。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/// @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.
    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
    }

    // This is a type for a single 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[] memory proposalNames) {
        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`.
    function giveRightToVote(address voter) external {
        // 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) external {
        // 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`.
    function vote(uint proposal) external {
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "Has no right to vote");
        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.
    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
    function winnerName() external view
            returns (bytes32 winnerName_)
    {
        winnerName_ = proposals[winningProposal()].name;
    }
}

可能的改进

目前,需要许多交易来将投票权分配给所有参与者。你能想出更好的办法吗?

全盲拍卖

在本节中,我们将展示在以太坊上创建完全盲拍卖合同是多么容易。我们将从公开拍卖开始,每个人都可以看到所做的出价,然后将此合同扩展为盲拍卖,在竞标期结束之前不可能看到实际出价。

简单公开拍卖

下面这个简单拍卖合同的大意是,每个人都可以在竞价期间发出自己的出价。投标已经包括汇款/以太,以便使投标人约束他们的投标。如果最高出价被提高,之前出价最高的人会拿回他们的钱。投标期结束后,必须手动调用合同才能让受益人收到钱-合同不能自我激活。

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract SimpleAuction {
    // Parameters of the auction. Times are either
    // absolute unix timestamps (seconds since 1970-01-01)
    // or time periods in seconds.
    address payable public beneficiary;
    uint public auctionEndTime;

    // Current state of the auction.
    address public highestBidder;
    uint public highestBid;

    // Allowed withdrawals of previous bids
    mapping(address => uint) pendingReturns;

    // Set to true at the end, disallows any change.
    // By default initialized to `false`.
    bool ended;

    // Events that will be emitted on changes.
    event HighestBidIncreased(address bidder, uint amount);
    event AuctionEnded(address winner, uint amount);

    // Errors that describe failures.

    // The triple-slash comments are so-called natspec
    // comments. They will be shown when the user
    // is asked to confirm a transaction or
    // when an error is displayed.

    /// The auction has already ended.
    error AuctionAlreadyEnded();
    /// There is already a higher or equal bid.
    error BidNotHighEnough(uint highestBid);
    /// The auction has not ended yet.
    error AuctionNotYetEnded();
    /// The function auctionEnd has already been called.
    error AuctionEndAlreadyCalled();

    /// Create a simple auction with `biddingTime`
    /// seconds bidding time on behalf of the
    /// beneficiary address `beneficiaryAddress`.
    constructor(
        uint biddingTime,
        address payable beneficiaryAddress
    ) {
        beneficiary = beneficiaryAddress;
        auctionEndTime = block.timestamp + biddingTime;
    }

    /// Bid on the auction with the value sent
    /// together with this transaction.
    /// The value will only be refunded if the
    /// auction is not won.
    function bid() external payable {
        // No arguments are necessary, all
        // information is already part of
        // the transaction. The keyword payable
        // is required for the function to
        // be able to receive Ether.

        // Revert the call if the bidding
        // period is over.
        if (block.timestamp > auctionEndTime)
            revert AuctionAlreadyEnded();

        // If the bid is not higher, send the
        // money back (the revert statement
        // will revert all changes in this
        // function execution including
        // it having received the money).
        if (msg.value <= highestBid)
            revert BidNotHighEnough(highestBid);

        if (highestBid != 0) {
            // Sending back the money by simply using
            // highestBidder.send(highestBid) is a security risk
            // because it could execute an untrusted contract.
            // It is always safer to let the recipients
            // withdraw their money themselves.
            pendingReturns[highestBidder] += highestBid;
        }
        highestBidder = msg.sender;
        highestBid = msg.value;
        emit HighestBidIncreased(msg.sender, msg.value);
    }

    /// Withdraw a bid that was overbid.
    function withdraw() external returns (bool) {
        uint amount = pendingReturns[msg.sender];
        if (amount > 0) {
            // It is important to set this to zero because the recipient
            // can call this function again as part of the receiving call
            // before `send` returns.
            pendingReturns[msg.sender] = 0;

            if (!payable(msg.sender).send(amount)) {
                // No need to call throw here, just reset the amount owing
                pendingReturns[msg.sender] = amount;
                return false;
            }
        }
        return true;
    }

    /// End the auction and send the highest bid
    /// to the beneficiary.
    function auctionEnd() external {
        // It is a good guideline to structure functions that interact
        // with other contracts (i.e. they call functions or send Ether)
        // into three phases:
        // 1. checking conditions
        // 2. performing actions (potentially changing conditions)
        // 3. interacting with other contracts
        // If these phases are mixed up, the other contract could call
        // back into the current contract and modify the state or cause
        // effects (ether payout) to be performed multiple times.
        // If functions called internally include interaction with external
        // contracts, they also have to be considered interaction with
        // external contracts.

        // 1. Conditions
        if (block.timestamp < auctionEndTime)
            revert AuctionNotYetEnded();
        if (ended)
            revert AuctionEndAlreadyCalled();

        // 2. Effects
        ended = true;
        emit AuctionEnded(highestBidder, highestBid);

        // 3. Interaction
        beneficiary.transfer(highestBid);
    }
}

全盲拍卖

前一次公开拍卖在下文中扩展为 全盲拍卖 。 全盲拍卖 的好处是在投标期结束前没有时间压力。在一个透明的计算平台上创建一个盲目的拍卖听起来像是一个矛盾,但密码学才是救命稻草。

投标期 ,投标者实际上并不发送他们的出价,而只是它的散列版本。由于目前认为几乎不可能找到两个散列值相等的(足够长的)值,投标人承诺按此进行投标。在投标期结束后,投标人必须公开他们的投标书:他们不加密地发送他们的价值,合同检查散列值是否与投标期间提供的哈希值相同。

另一个挑战是如何进行拍卖 捆绑和盲板 同时:防止竞买人在竞拍中得标后不把钱寄出去的唯一办法就是让他们把钱和出价一起寄出去。由于价值传递在以太坊中是不能被蒙蔽的,任何人都可以看到价值。

以下合同通过接受任何大于最高出价的价值来解决这个问题。由于这当然只能在公开阶段进行检查,因此一些投标可能 无效 ,这是有目的的(它甚至提供了一个明确的标志,将无效的投标与高价值的转让放在一起):投标人可以通过放置几个高或低的无效投标来混淆竞争。

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract BlindAuction {
    struct Bid {
        bytes32 blindedBid;
        uint deposit;
    }

    address payable public beneficiary;
    uint public biddingEnd;
    uint public revealEnd;
    bool public ended;

    mapping(address => Bid[]) public bids;

    address public highestBidder;
    uint public highestBid;

    // Allowed withdrawals of previous bids
    mapping(address => uint) pendingReturns;

    event AuctionEnded(address winner, uint highestBid);

    // Errors that describe failures.

    /// The function has been called too early.
    /// Try again at `time`.
    error TooEarly(uint time);
    /// The function has been called too late.
    /// It cannot be called after `time`.
    error TooLate(uint time);
    /// The function auctionEnd has already been called.
    error AuctionEndAlreadyCalled();

    // Modifiers are a convenient way to validate inputs to
    // functions. `onlyBefore` is applied to `bid` below:
    // The new function body is the modifier's body where
    // `_` is replaced by the old function body.
    modifier onlyBefore(uint time) {
        if (block.timestamp >= time) revert TooLate(time);
        _;
    }
    modifier onlyAfter(uint time) {
        if (block.timestamp <= time) revert TooEarly(time);
        _;
    }

    constructor(
        uint biddingTime,
        uint revealTime,
        address payable beneficiaryAddress
    ) {
        beneficiary = beneficiaryAddress;
        biddingEnd = block.timestamp + biddingTime;
        revealEnd = biddingEnd + revealTime;
    }

    /// Place a blinded bid with `blindedBid` =
    /// keccak256(abi.encodePacked(value, fake, secret)).
    /// The sent ether is only refunded if the bid is correctly
    /// revealed in the revealing phase. The bid is valid if the
    /// ether sent together with the bid is at least "value" and
    /// "fake" is not true. Setting "fake" to true and sending
    /// not the exact amount are ways to hide the real bid but
    /// still make the required deposit. The same address can
    /// place multiple bids.
    function bid(bytes32 blindedBid)
        external
        payable
        onlyBefore(biddingEnd)
    {
        bids[msg.sender].push(Bid({
            blindedBid: blindedBid,
            deposit: msg.value
        }));
    }

    /// Reveal your blinded bids. You will get a refund for all
    /// correctly blinded invalid bids and for all bids except for
    /// the totally highest.
    function reveal(
        uint[] calldata values,
        bool[] calldata fakes,
        bytes32[] calldata secrets
    )
        external
        onlyAfter(biddingEnd)
        onlyBefore(revealEnd)
    {
        uint length = bids[msg.sender].length;
        require(values.length == length);
        require(fakes.length == length);
        require(secrets.length == length);

        uint refund;
        for (uint i = 0; i < length; i++) {
            Bid storage bidToCheck = bids[msg.sender][i];
            (uint value, bool fake, bytes32 secret) =
                    (values[i], fakes[i], secrets[i]);
            if (bidToCheck.blindedBid != keccak256(abi.encodePacked(value, fake, secret))) {
                // Bid was not actually revealed.
                // Do not refund deposit.
                continue;
            }
            refund += bidToCheck.deposit;
            if (!fake && bidToCheck.deposit >= value) {
                if (placeBid(msg.sender, value))
                    refund -= value;
            }
            // Make it impossible for the sender to re-claim
            // the same deposit.
            bidToCheck.blindedBid = bytes32(0);
        }
        payable(msg.sender).transfer(refund);
    }

    /// Withdraw a bid that was overbid.
    function withdraw() external {
        uint amount = pendingReturns[msg.sender];
        if (amount > 0) {
            // It is important to set this to zero because the recipient
            // can call this function again as part of the receiving call
            // before `transfer` returns (see the remark above about
            // conditions -> effects -> interaction).
            pendingReturns[msg.sender] = 0;

            payable(msg.sender).transfer(amount);
        }
    }

    /// End the auction and send the highest bid
    /// to the beneficiary.
    function auctionEnd()
        external
        onlyAfter(revealEnd)
    {
        if (ended) revert AuctionEndAlreadyCalled();
        emit AuctionEnded(highestBidder, highestBid);
        ended = true;
        beneficiary.transfer(highestBid);
    }

    // This is an "internal" function which means that it
    // can only be called from the contract itself (or from
    // derived contracts).
    function placeBid(address bidder, uint value) internal
            returns (bool success)
    {
        if (value <= highestBid) {
            return false;
        }
        if (highestBidder != address(0)) {
            // Refund the previously highest bidder.
            pendingReturns[highestBidder] += highestBid;
        }
        highestBid = value;
        highestBidder = bidder;
        return true;
    }
}

安全远程购买

远程采购商品目前需要多方相互信任。最简单的配置包括卖方和买方。买方希望从卖方处收到一件物品,而卖方则希望得到金钱(或等价物)作为回报。问题在于这里的货物:无法确定货物是否已到达买方。

有多种方法可以解决这个问题,但都有一个或另一个方面的不足。在下面的例子中,双方都必须将物品价值的两倍存入合同作为第三方保管。一旦发生这种情况,这笔钱将被锁定在合同内,直到买方确认他们收到了货物。在那之后,买方将得到价值(他们定金的一半)的返还,而卖方得到价值的三倍(他们的定金加上价值)。这背后的想法是,双方都有解决问题的动力,否则他们的钱就永远锁着。

当然,这个契约并不能解决问题,但是提供了一个概述,说明如何在契约中使用类似状态机的构造。

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Purchase {
    uint public value;
    address payable public seller;
    address payable public buyer;

    enum State { Created, Locked, Release, Inactive }
    // The state variable has a default value of the first member, `State.created`
    State public state;

    modifier condition(bool condition_) {
        require(condition_);
        _;
    }

    /// Only the buyer can call this function.
    error OnlyBuyer();
    /// Only the seller can call this function.
    error OnlySeller();
    /// The function cannot be called at the current state.
    error InvalidState();
    /// The provided value has to be even.
    error ValueNotEven();

    modifier onlyBuyer() {
        if (msg.sender != buyer)
            revert OnlyBuyer();
        _;
    }

    modifier onlySeller() {
        if (msg.sender != seller)
            revert OnlySeller();
        _;
    }

    modifier inState(State state_) {
        if (state != state_)
            revert InvalidState();
        _;
    }

    event Aborted();
    event PurchaseConfirmed();
    event ItemReceived();
    event SellerRefunded();

    // Ensure that `msg.value` is an even number.
    // Division will truncate if it is an odd number.
    // Check via multiplication that it wasn't an odd number.
    constructor() payable {
        seller = payable(msg.sender);
        value = msg.value / 2;
        if ((2 * value) != msg.value)
            revert ValueNotEven();
    }

    /// Abort the purchase and reclaim the ether.
    /// Can only be called by the seller before
    /// the contract is locked.
    function abort()
        external
        onlySeller
        inState(State.Created)
    {
        emit Aborted();
        state = State.Inactive;
        // We use transfer here directly. It is
        // reentrancy-safe, because it is the
        // last call in this function and we
        // already changed the state.
        seller.transfer(address(this).balance);
    }

    /// Confirm the purchase as buyer.
    /// Transaction has to include `2 * value` ether.
    /// The ether will be locked until confirmReceived
    /// is called.
    function confirmPurchase()
        external
        inState(State.Created)
        condition(msg.value == (2 * value))
        payable
    {
        emit PurchaseConfirmed();
        buyer = payable(msg.sender);
        state = State.Locked;
    }

    /// Confirm that you (the buyer) received the item.
    /// This will release the locked ether.
    function confirmReceived()
        external
        onlyBuyer
        inState(State.Locked)
    {
        emit ItemReceived();
        // It is important to change the state first because
        // otherwise, the contracts called using `send` below
        // can call in again here.
        state = State.Release;

        buyer.transfer(value);
    }

    /// This function refunds the seller, i.e.
    /// pays back the locked funds of the seller.
    function refundSeller()
        external
        onlySeller
        inState(State.Release)
    {
        emit SellerRefunded();
        // It is important to change the state first because
        // otherwise, the contracts called using `send` below
        // can call in again here.
        state = State.Inactive;

        seller.transfer(3 * value);
    }
}

小额支付渠道

在本节中,我们将学习如何构建支付渠道的示例实现。它使用加密签名在同一方之间进行安全、即时和无需交易费用的重复 Ether 传输。例如,我们需要了解如何签名和验证签名,以及设置付款渠道。

创建和验证签名

假设Alice想要向Bob发送一些以太,即Alice是发送者,Bob是接收者。

Alice只需要将经过加密签名的邮件(例如通过电子邮件)发送给Bob,类似于写支票。

Alice和Bob使用签名来授权交易,这可以通过以太坊上的智能合约实现。Alice将构建一个简单的智能合约,允许她传输以太网络,但她不会自己调用函数来启动支付,而是让Bob这样做,因此支付交易费用。

本合同的工作内容如下:

  1. 爱丽丝部署了 ReceiverPays 合同,附加足够的 Ether 以支付将要支付的款项。

  2. 爱丽丝通过用她的私钥签署消息来授权付款。

  3. 爱丽丝把加密签名的信息发送给鲍勃。消息不需要保密(稍后解释),发送消息的机制也不重要。

  4. Bob通过将签署的消息提交给智能合同来申请付款,智能合同验证消息的真实性,然后释放资金。

创建签名

Alice不需要与以太坊网络交互来签署交易,过程完全离线。在本教程中,我们将使用 web3.jsMetaMask ,使用中描述的方法 EIP-762 ,因为它提供了许多其他安全好处。

/// Hashing first makes things easier
var hash = web3.utils.sha3("message to sign");
web3.eth.personal.sign(hash, web3.eth.defaultAccount, function () { console.log("Signed"); });

注解

这个 web3.eth.personal.sign 将消息的长度预先设置为已签名的数据。因为我们首先散列,所以消息的长度总是正好32个字节,因此这个长度前缀总是相同的。

签署什么

对于履行付款的合同,签署的信息必须包括:

  1. 收件人地址。

  2. 要转移的金额。

  3. 防止重播攻击。

重播攻击是指重新使用签名的消息来请求第二个操作的授权。为了避免重播攻击,我们使用与以太坊事务本身相同的技术,即所谓的nonce,即帐户发送的事务数。智能合约检查一个nonce是否被多次使用。

当所有者部署 ReceiverPays 智能合约,支付一些款项,然后销毁合约。稍后,他们决定部署 RecipientPays 再次使用智能协定,但新协定不知道以前部署中使用的nonce,因此攻击者可以再次使用旧消息。

Alice可以通过在消息中包含合同地址来防止这种攻击,并且只接受包含合同地址本身的消息。您可以在 claimPayment() 本节结束时完整合同的功能。

打包参数

既然我们已经确定了要在签名消息中包含哪些信息,那么就可以将消息放在一起、散列并签名了。为了简单起见,我们将数据连接起来。这个 ethereumjs-abi 库提供一个名为 soliditySHA3 模仿Solidity的行为 keccak256 函数应用于使用 abi.encodePacked .下面是一个javascript函数,它为 ReceiverPays 例子:

// recipient is the address that should be paid.
// amount, in wei, specifies how much ether should be sent.
// nonce can be any unique number to prevent replay attacks
// contractAddress is used to prevent cross-contract replay attacks
function signPayment(recipient, amount, nonce, contractAddress, callback) {
    var hash = "0x" + abi.soliditySHA3(
        ["address", "uint256", "uint256", "address"],
        [recipient, amount, nonce, contractAddress]
    ).toString("hex");

    web3.eth.personal.sign(hash, web3.eth.defaultAccount, callback);
}

在solidity中恢复消息签名者

一般来说,ECDSA签名由两个参数组成, rs .以太坊中的签名包含第三个名为 v ,您可以使用它来验证哪个帐户的私钥用于对消息进行签名,以及事务的发送者。Solidity提供内置功能 ecrecover 接受信息的同时 rsv 参数并返回用于对消息签名的地址。

提取签名参数

web3.js生成的签名是 rsv ,所以第一步是将这些参数分开。您可以在客户端执行此操作,但在智能合约中执行此操作意味着您只需发送一个签名参数而不是三个。将字节数组拆分为其组成部分是一个混乱的过程,因此我们使用 inline assembly 在…中完成工作 splitSignature 功能(本节末尾完整合同中的第三个功能)。

正在计算消息哈希

智能合约需要准确知道哪些参数已签名,因此它必须从这些参数中重新创建消息,并将其用于签名验证。功能 prefixedrecoverSigner 在里面做这个 claimPayment 功能。

全部合同

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract ReceiverPays {
    address owner = msg.sender;

    mapping(uint256 => bool) usedNonces;

    constructor() payable {}

    function claimPayment(uint256 amount, uint256 nonce, bytes memory signature) external {
        require(!usedNonces[nonce]);
        usedNonces[nonce] = true;

        // this recreates the message that was signed on the client
        bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this)));

        require(recoverSigner(message, signature) == owner);

        payable(msg.sender).transfer(amount);
    }

    /// destroy the contract and reclaim the leftover funds.
    function shutdown() external {
        require(msg.sender == owner);
        selfdestruct(payable(msg.sender));
    }

    /// signature methods.
    function splitSignature(bytes memory sig)
        internal
        pure
        returns (uint8 v, bytes32 r, bytes32 s)
    {
        require(sig.length == 65);

        assembly {
            // first 32 bytes, after the length prefix.
            r := mload(add(sig, 32))
            // second 32 bytes.
            s := mload(add(sig, 64))
            // final byte (first byte of the next 32 bytes).
            v := byte(0, mload(add(sig, 96)))
        }

        return (v, r, s);
    }

    function recoverSigner(bytes32 message, bytes memory sig)
        internal
        pure
        returns (address)
    {
        (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);

        return ecrecover(message, v, r, s);
    }

    /// builds a prefixed hash to mimic the behavior of eth_sign.
    function prefixed(bytes32 hash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }
}

编写简单的支付渠道

Alice现在构建了一个简单但完整的支付通道实现。支付渠道使用加密签名安全、即时、无需支付交易费用重复传输 Ether 。

什么是付款渠道?

支付渠道允许参与者在不使用交易的情况下重复传输 Ether 。这意味着您可以避免与交易相关的延迟和费用。我们将探索双方(Alice和Bob)之间简单的单向支付渠道。它包括三个步骤:

  1. 艾丽斯资助了一项与以太的智能合约。这将“打开”支付渠道。

  2. 艾丽丝在邮件上签名,说明 Ether 有多少欠收件人。对每个付款重复此步骤。

  3. Bob“关闭”支付通道,提取他的Ether部分,并将剩余部分发送回发送方。

注解

只有步骤1和步骤3需要以太坊交易,步骤2意味着发送方通过链外方法(例如电子邮件)向接收方发送加密签名的消息。这意味着只需要两个事务来支持任何数量的传输。

Bob保证会收到他的资金,因为智能合同托管了以太并兑现了有效的签名消息。智能合约还强制执行超时,因此即使收件人拒绝关闭频道,爱丽丝也保证最终能收回她的资金。这是由支付渠道的参与者决定保持多长时间开放的。对于短暂的交易,例如为每分钟的网络访问向网吧支付费用,支付通道可以在有限的持续时间内保持开放。另一方面,对于经常性的支付,例如支付给员工时薪,支付渠道可能会保持几个月或几年的畅通。

开通支付渠道

为了打开支付通道,Alice部署了智能合约,将要托管的以太网连接起来,并指定了预期的接收者和通道存在的最长持续时间。这就是功能 SimplePaymentChannel 在合同中,在本节末尾。

付款

Alice通过向Bob发送签名信息来付款。此步骤完全在以太坊网络之外执行。消息由发送方加密签名,然后直接传输给接收者。

每条消息包括以下信息:

  • 智能合约的地址,用于防止交叉合约重播攻击。

  • 迄今为止所欠收件人的 Ether 总量。

在一系列转账结束时,支付渠道只关闭一次。因此,发送的消息中只有一条被赎回。这就是为什么每条消息都指定了所欠乙醚的累计总金额,而不是单个小额支付的金额。接收者自然会选择赎回最近的一封邮件,因为那是总数最高的一封。不再需要每条消息的nonce,因为智能合约只处理单个消息。智能合约的地址仍然用于防止一个支付渠道的消息被另一个渠道使用。

下面是修改后的javascript代码,用于对上一节中的消息进行加密签名:

function constructPaymentMessage(contractAddress, amount) {
    return abi.soliditySHA3(
        ["address", "uint256"],
        [contractAddress, amount]
    );
}

function signMessage(message, callback) {
    web3.eth.personal.sign(
        "0x" + message.toString("hex"),
        web3.eth.defaultAccount,
        callback
    );
}

// contractAddress is used to prevent cross-contract replay attacks.
// amount, in wei, specifies how much Ether should be sent.

function signPayment(contractAddress, amount, callback) {
    var message = constructPaymentMessage(contractAddress, amount);
    signMessage(message, callback);
}

关闭支付渠道

当Bob准备好接收他的资金时,就可以通过调用 close 在智能合同上起作用。关闭频道会向收件人支付他们所欠的以太,并破坏合同,将剩余的以太送回给爱丽丝。要关闭频道,Bob需要提供一条由Alice签名的消息。

智能合约必须验证邮件是否包含来自发件人的有效签名。执行此验证的过程与收件人使用的过程相同。 Solidity 函数 isValidSignaturerecoverSigner 与上一节中的javascript对应项一样,后者的函数借鉴了 ReceiverPays 合同。

只有付款渠道接收者可以调用 close 函数,自然地传递最近的付款消息,因为该消息包含最高的总欠款。如果允许发送者调用此函数,那么他们可以提供一个金额较低的消息,并欺骗接收者。

函数验证签名消息是否与给定参数匹配。如果所有内容都签出,则收件人将被发送其 Ether 部分,而发送人将通过 selfdestruct .你可以看到 close 在整个合同中发挥作用。

频道过期

鲍勃可以随时关闭支付渠道,但如果他们做不到,爱丽丝需要一种方法来收回她的托管资金。一个 到期 时间是在合同部署时设置的。一旦到了那个时间,爱丽丝就可以打电话给 claimTimeout 来追回她的资金。您可以看到 claimTimeout 在完整合同中发挥作用。

调用此函数后,Bob将无法再接收任何以太网,因此在达到到期之前关闭通道非常重要。

全部合同

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract SimplePaymentChannel {
    address payable public sender;      // The account sending payments.
    address payable public recipient;   // The account receiving the payments.
    uint256 public expiration;  // Timeout in case the recipient never closes.

    constructor (address payable recipientAddress, uint256 duration)
        payable
    {
        sender = payable(msg.sender);
        recipient = recipientAddress;
        expiration = block.timestamp + duration;
    }

    /// the recipient can close the channel at any time by presenting a
    /// signed amount from the sender. the recipient will be sent that amount,
    /// and the remainder will go back to the sender
    function close(uint256 amount, bytes memory signature) external {
        require(msg.sender == recipient);
        require(isValidSignature(amount, signature));

        recipient.transfer(amount);
        selfdestruct(sender);
    }

    /// the sender can extend the expiration at any time
    function extend(uint256 newExpiration) external {
        require(msg.sender == sender);
        require(newExpiration > expiration);

        expiration = newExpiration;
    }

    /// if the timeout is reached without the recipient closing the channel,
    /// then the Ether is released back to the sender.
    function claimTimeout() external {
        require(block.timestamp >= expiration);
        selfdestruct(sender);
    }

    function isValidSignature(uint256 amount, bytes memory signature)
        internal
        view
        returns (bool)
    {
        bytes32 message = prefixed(keccak256(abi.encodePacked(this, amount)));

        // check that the signature is from the payment sender
        return recoverSigner(message, signature) == sender;
    }

    /// All functions below this are just taken from the chapter
    /// 'creating and verifying signatures' chapter.

    function splitSignature(bytes memory sig)
        internal
        pure
        returns (uint8 v, bytes32 r, bytes32 s)
    {
        require(sig.length == 65);

        assembly {
            // first 32 bytes, after the length prefix
            r := mload(add(sig, 32))
            // second 32 bytes
            s := mload(add(sig, 64))
            // final byte (first byte of the next 32 bytes)
            v := byte(0, mload(add(sig, 96)))
        }

        return (v, r, s);
    }

    function recoverSigner(bytes32 message, bytes memory sig)
        internal
        pure
        returns (address)
    {
        (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);

        return ecrecover(message, v, r, s);
    }

    /// builds a prefixed hash to mimic the behavior of eth_sign.
    function prefixed(bytes32 hash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }
}

注解

该函数 splitSignature 不使用所有安全检查。真正的实现应该使用经过更严格测试的库,比如openzepplin的库 version 这段代码的。

核实付款

与上一节不同,支付通道中的消息不会立即兑现。收件人跟踪最新消息,并在关闭支付通道时将其重新发送。这意味着接收者必须对每条消息进行自己的验证。否则,就无法保证收件人最终能够得到付款。

收件人应使用以下过程验证每封邮件:

  1. 验证消息中的合同地址是否与支付渠道匹配。

  2. 验证新总额是否为预期金额。

  3. 确认新的总量不超过 Ether 储存量。

  4. 验证签名是否有效并来自付款渠道发送方。

我们将使用 ethereumjs-util 库来编写此验证。最后一步可以通过多种方式完成,我们使用JavaScript。下面的代码借用了 constructPaymentMessage 函数从签名开始 JavaScript代码 上图:

// this mimics the prefixing behavior of the eth_sign JSON-RPC method.
function prefixed(hash) {
    return ethereumjs.ABI.soliditySHA3(
        ["string", "bytes32"],
        ["\x19Ethereum Signed Message:\n32", hash]
    );
}

function recoverSigner(message, signature) {
    var split = ethereumjs.Util.fromRpcSig(signature);
    var publicKey = ethereumjs.Util.ecrecover(message, split.v, split.r, split.s);
    var signer = ethereumjs.Util.pubToAddress(publicKey).toString("hex");
    return signer;
}

function isValidSignature(contractAddress, amount, signature, expectedSigner) {
    var message = prefixed(constructPaymentMessage(contractAddress, amount));
    var signer = recoverSigner(message, signature);
    return signer.toLowerCase() ==
        ethereumjs.Util.stripHexPrefix(expectedSigner).toLowerCase();
}

模块化合同

构建合同的模块化方法有助于降低复杂性和提高可读性,这有助于在开发和代码审查期间识别错误和漏洞。如果您单独指定和控制行为或每个模块,那么您必须考虑的交互仅是模块规范之间的交互,而不是合同中的每个其他移动部分。在下面的示例中,合同使用 move 方法 Balances library 检查地址之间发送的余额是否符合您的期望。这样的话, Balances 库提供了一个独立的组件,可以正确地跟踪帐户余额。很容易验证 Balances 库从不产生负余额或溢出,并且所有余额的总和在合同的整个生命周期中都是不变的。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;

library Balances {
    function move(mapping(address => uint256) storage balances, address from, address to, uint amount) internal {
        require(balances[from] >= amount);
        require(balances[to] + amount >= balances[to]);
        balances[from] -= amount;
        balances[to] += amount;
    }
}

contract Token {
    mapping(address => uint256) balances;
    using Balances for *;
    mapping(address => mapping (address => uint256)) allowed;

    event Transfer(address from, address to, uint amount);
    event Approval(address owner, address spender, uint amount);

    function transfer(address to, uint amount) external returns (bool success) {
        balances.move(msg.sender, to, amount);
        emit Transfer(msg.sender, to, amount);
        return true;

    }

    function transferFrom(address from, address to, uint amount) external returns (bool success) {
        require(allowed[from][msg.sender] >= amount);
        allowed[from][msg.sender] -= amount;
        balances.move(from, to, amount);
        emit Transfer(from, to, amount);
        return true;
    }

    function approve(address spender, uint tokens) external returns (bool success) {
        require(allowed[msg.sender][spender] == 0, "");
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender, spender, tokens);
        return true;
    }

    function balanceOf(address tokenOwner) external view returns (uint balance) {
        return balances[tokenOwner];
    }
}