# Guess New Random Number
Again, can you guess a random number? Be smart this time.
You might want to write a smart contract to defeat this level, and don't forget to withdraw the money back to your account! Note that all transactions in a block share the information (metadata) of the current block.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
contract GuessNewRandomNumber {
address player;
constructor(address _player) payable {
require(msg.value == 1 gwei);
require(_player != address(0));
}
function solved() public view returns (bool) {
return address(this).balance == 0 && address(player).balance == 0;
}
function guess(uint n) public payable {
require(msg.value == 1 gwei);
player = msg.sender;
uint answer = uint(keccak256(
abi.encodePacked(blockhash(block.number - 1), block.timestamp)));
if (n == answer) {
payable(msg.sender).transfer(2 gwei);
}
}
}
TIP
You have heard that blockhash()
and block.timestamp
is not
a secure source of randomness (opens new window)!
You can solve 1-3 challenges from etherhack (opens new window) with a similar technique.