通用模式¶

Withdrawal from Contracts¶

The recommended method of sending funds after an effectis using the withdrawal pattern. Although the most intuitivemethod of sending Ether, as a result of an effect, is adirect send call, this is not recommended as itintroduces a potential security risk. You may readmore about this on the 安全性考虑 page.

This is an example of the withdrawal pattern in practice ina contract where the goal is to send the most money to thecontract in order to become the “richest”, inspired byKing of the Ether.

In the following contract, if you are usurped as the richest,you will receive the funds of the person who has gone on tobecome the new richest.

  1. pragma solidity ^0.4.11;
  2.  
  3. contract WithdrawalContract {
  4. address public richest;
  5. uint public mostSent;
  6.  
  7. mapping (address => uint) pendingWithdrawals;
  8.  
  9. function WithdrawalContract() public payable {
  10. richest = msg.sender;
  11. mostSent = msg.value;
  12. }
  13.  
  14. function becomeRichest() public payable returns (bool) {
  15. if (msg.value > mostSent) {
  16. pendingWithdrawals[richest] += msg.value;
  17. richest = msg.sender;
  18. mostSent = msg.value;
  19. return true;
  20. } else {
  21. return false;
  22. }
  23. }
  24.  
  25. function withdraw() public {
  26. uint amount = pendingWithdrawals[msg.sender];
  27. // Remember to zero the pending refund before
  28. // sending to prevent re-entrancy attacks
  29. pendingWithdrawals[msg.sender] = 0;
  30. msg.sender.transfer(amount);
  31. }
  32. }

This is as opposed to the more intuitive sending pattern:

  1. pragma solidity ^0.4.11;
  2.  
  3. contract SendContract {
  4. address public richest;
  5. uint public mostSent;
  6.  
  7. function SendContract() public payable {
  8. richest = msg.sender;
  9. mostSent = msg.value;
  10. }
  11.  
  12. function becomeRichest() public payable returns (bool) {
  13. if (msg.value > mostSent) {
  14. // This line can cause problems (explained below).
  15. richest.transfer(msg.value);
  16. richest = msg.sender;
  17. mostSent = msg.value;
  18. return true;
  19. } else {
  20. return false;
  21. }
  22. }
  23. }

Notice that, in this example, an attacker could trap thecontract into an unusable state by causing richest to bethe address of a contract that has a fallback functionwhich fails (e.g. by using revert() or by justconsuming more than the 2300 gas stipend). That way,whenever transfer is called to deliver funds to the“poisoned” contract, it will fail and thus also becomeRichestwill fail, with the contract being stuck forever.

In contrast, if you use the “withdraw” pattern from the first example,the attacker can only cause his or her own withdraw to fail and not therest of the contract’s workings.

Restricting Access¶

Restricting access is a common pattern for contracts.Note that you can never restrict any human or computerfrom reading the content of your transactions oryour contract’s state. You can make it a bit harderby using encryption, but if your contract is supposedto read the data, so will everyone else.

You can restrict read access to your contract’s stateby other contracts. That is actually the defaultunless you declare make your state variables public.

Furthermore, you can restrict who can make modificationsto your contract’s state or call your contract’sfunctions and this is what this section is about.

The use of function modifiers makes theserestrictions highly readable.

  1. pragma solidity ^0.4.11;
  2.  
  3. contract AccessRestriction {
  4. // These will be assigned at the construction
  5. // phase, where `msg.sender` is the account
  6. // creating this contract.
  7. address public owner = msg.sender;
  8. uint public creationTime = now;
  9.  
  10. // Modifiers can be used to change
  11. // the body of a function.
  12. // If this modifier is used, it will
  13. // prepend a check that only passes
  14. // if the function is called from
  15. // a certain address.
  16. modifier onlyBy(address _account)
  17. {
  18. require(msg.sender == _account);
  19. // Do not forget the "_;"! It will
  20. // be replaced by the actual function
  21. // body when the modifier is used.
  22. _;
  23. }
  24.  
  25. /// Make `_newOwner` the new owner of this
  26. /// contract.
  27. function changeOwner(address _newOwner)
  28. public
  29. onlyBy(owner)
  30. {
  31. owner = _newOwner;
  32. }
  33.  
  34. modifier onlyAfter(uint _time) {
  35. require(now >= _time);
  36. _;
  37. }
  38.  
  39. /// Erase ownership information.
  40. /// May only be called 6 weeks after
  41. /// the contract has been created.
  42. function disown()
  43. public
  44. onlyBy(owner)
  45. onlyAfter(creationTime + 6 weeks)
  46. {
  47. delete owner;
  48. }
  49.  
  50. // This modifier requires a certain
  51. // fee being associated with a function call.
  52. // If the caller sent too much, he or she is
  53. // refunded, but only after the function body.
  54. // This was dangerous before Solidity version 0.4.0,
  55. // where it was possible to skip the part after `_;`.
  56. modifier costs(uint _amount) {
  57. require(msg.value >= _amount);
  58. _;
  59. if (msg.value > _amount)
  60. msg.sender.send(msg.value - _amount);
  61. }
  62.  
  63. function forceOwnerChange(address _newOwner)
  64. public
  65. costs(200 ether)
  66. {
  67. owner = _newOwner;
  68. // just some example condition
  69. if (uint(owner) & 0 == 1)
  70. // This did not refund for Solidity
  71. // before version 0.4.0.
  72. return;
  73. // refund overpaid fees
  74. }
  75. }

A more specialised way in which access to functioncalls can be restricted will be discussedin the next example.

State Machine¶

Contracts often act as a state machine, which meansthat they have certain stages in which they behavedifferently or in which different functions canbe called. A function call often ends a stageand transitions the contract into the next stage(especially if the contract models interaction).It is also common that some stages are automaticallyreached at a certain point in time.

An example for this is a blind auction contract whichstarts in the stage “accepting blinded bids”, thentransitions to “revealing bids” which is ended by“determine auction outcome”.

Function modifiers can be used in this situationto model the states and guard againstincorrect usage of the contract.

Example¶

In the following example,the modifier atStage ensures that the function canonly be called at a certain stage.

Automatic timed transitionsare handled by the modifier timeTransitions, whichshould be used for all functions.

Note

Modifier Order Matters.If atStage is combinedwith timedTransitions, make sure that you mentionit after the latter, so that the new stage istaken into account.

Finally, the modifier transitionNext can be usedto automatically go to the next stage when thefunction finishes.

Note

Modifier May be Skipped.This only applies to Solidity before version 0.4.0:Since modifiers are applied by simply replacingcode and not by using a function call,the code in the transitionNext modifiercan be skipped if the function itself usesreturn. If you want to do that, make sureto call nextStage manually from those functions.Starting with version 0.4.0, modifier codewill run even if the function explicitly returns.

  1. pragma solidity ^0.4.11;
  2.  
  3. contract StateMachine {
  4. enum Stages {
  5. AcceptingBlindedBids,
  6. RevealBids,
  7. AnotherStage,
  8. AreWeDoneYet,
  9. Finished
  10. }
  11.  
  12. // This is the current stage.
  13. Stages public stage = Stages.AcceptingBlindedBids;
  14.  
  15. uint public creationTime = now;
  16.  
  17. modifier atStage(Stages _stage) {
  18. require(stage == _stage);
  19. _;
  20. }
  21.  
  22. function nextStage() internal {
  23. stage = Stages(uint(stage) + 1);
  24. }
  25.  
  26. // Perform timed transitions. Be sure to mention
  27. // this modifier first, otherwise the guards
  28. // will not take the new stage into account.
  29. modifier timedTransitions() {
  30. if (stage == Stages.AcceptingBlindedBids &&
  31. now >= creationTime + 10 days)
  32. nextStage();
  33. if (stage == Stages.RevealBids &&
  34. now >= creationTime + 12 days)
  35. nextStage();
  36. // The other stages transition by transaction
  37. _;
  38. }
  39.  
  40. // Order of the modifiers matters here!
  41. function bid()
  42. public
  43. payable
  44. timedTransitions
  45. atStage(Stages.AcceptingBlindedBids)
  46. {
  47. // We will not implement that here
  48. }
  49.  
  50. function reveal()
  51. public
  52. timedTransitions
  53. atStage(Stages.RevealBids)
  54. {
  55. }
  56.  
  57. // This modifier goes to the next stage
  58. // after the function is done.
  59. modifier transitionNext()
  60. {
  61. _;
  62. nextStage();
  63. }
  64.  
  65. function g()
  66. public
  67. timedTransitions
  68. atStage(Stages.AnotherStage)
  69. transitionNext
  70. {
  71. }
  72.  
  73. function h()
  74. public
  75. timedTransitions
  76. atStage(Stages.AreWeDoneYet)
  77. transitionNext
  78. {
  79. }
  80.  
  81. function i()
  82. public
  83. timedTransitions
  84. atStage(Stages.Finished)
  85. {
  86. }
  87. }

原文: http://solidity.apachecn.org/cn/doc/v0.4.21/common-patterns.html