I have been researching this topic lately and most of the resources are saying that it's impossible to generate a random number on-chain. However, I have come across a post saying that this function can generate a unpredictable number. Is there any way to predict this function?
function rand() public view returns(uint256) {
uint256 seed = uint256(keccak256(abi.encodePacked(
block.timestamp + block.difficulty +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) +
block.gaslimit +
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) +
block.number
)));
return (seed - ((seed / 1000) * 1000));
}
Is there any way to predict this function?
A miner can publish their block number
with a timestamp
that fits together with other criteria:
difficulty
is given for some timecoinbase
is given for even longer period of timemsg.sender
(the real transaction sender and signer) can be one of the miner's addressesThere's no way how to generate truly indeterminable random number on-chain. But you can use an oracle that returns an off-chain generated "random" number.