[Ethernaut]2-Fallout

题目一览

源码:

pragma solidity ^0.4.18;

import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';

contract Fallout is Ownable {
  
  using SafeMath for uint256;
  mapping (address => uint) allocations;

  /* constructor */
  function Fal1out() public payable {
    owner = msg.sender;
    allocations[owner] = msg.value;
  }

  function allocate() public payable {
    allocations[msg.sender] = allocations[msg.sender].add(msg.value);
  }

  function sendAllocation(address allocator) public {
    require(allocations[allocator] > 0);
    allocator.transfer(allocations[allocator]);
  }

  function collectAllocations() public onlyOwner {
    msg.sender.transfer(this.balance);
  }

  function allocatorBalance(address allocator) public view returns (uint) {
    return allocations[allocator];
  }
}

过关要求:

Claim ownership of the contract below to complete this level. 成为合约的所有者。

分析&求解

这题其实……先来学习一下Solidity的构造函数和析构函数吧。

其实和java有点类似,构造函数是类初始化时候执行,析构函数是销毁回收的时候执行。

构造函数的特点是,和合约名(”类名”)相同

比如下面这个例子:

pragma solidity ^0.4.13;
contract MyCoin{
    uint amount;
    address owner;
    
    function MyCoin() public{ //构造函数,和合约同名
        amount=90;
        owner=msg.sender;
    }
    
    function getBalance() public constant returns (uint){
        
        return amount;
        
    }
    
    function kill() public{  //析构函数,销毁时候执行
        if(owner==msg.sender){
            selfdestruct(owner);
        }
    }
}

那么来看这个题:

contract Fallout is Ownable {
  
  using SafeMath for uint256;
  mapping (address => uint) allocations;

  /* constructor */
  function Fal1out() public payable {
    owner = msg.sender;
    allocations[owner] = msg.value;
  }

这个带注释的函数,功能就是让执行者成为合约的所有者。

可以发现,合约名是Fallout,而这个函数名是Fal1out

所以说他压根不是构造函数,合约会使用默认的构造函数(感觉就是java)

又因为修饰符是public,是个人都能调……所以:

image-20200403204230740

可以看到owner已经是我们了:

image-20200403204409467

提交,过关:

image-20200403205718855

过关之后给了一个小故事,原来真有开发的犯过这个错误,改了合约名没改构造函数:

image-20200403205755166

猜你喜欢

转载自www.cnblogs.com/keelongz/p/12628929.html
2
>&2
α2
2-2