What is a random number attack?
Many contracts directly use blockchain information such as timestamp, blockhash, etc. to generate random numbers within the contract. This can be easily manipulated by miners, as they can choose which transactions to include in a block. Hackers can manipulate the variables in the algorithm for generating random numbers to obtain favorable results once they know the algorithm.
Methods for generating secure random numbers:
Use decentralized random number generation services such as Chainlink VRF.
Move the random number generation process off-chain and use oracles to bring the results on-chain.
Use a multi-party commit-reveal mechanism, where multiple entities participate in generating the random number.
Introduce uncertainties such as user interactions to increase unpredictability.
Code example:
// Use Chainlink VRF
uint256 public randomResult;
function getRandomNumber() public returns (bytes32 requestId) {
return requestRandomness(keyHash, fee);
}
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = randomness;
}
// Commit-Reveal scheme
function commit(bytes32 hash) external;
function reveal(uint value) external;
function random() external view returns (uint) {
// Use commit and reveal values to generate random number
}