I am creating a token that requires a sufficiently random number for an internal lottery.

    uint randomX;

    function semirandomize(uint prevRandom, uint time) private view returns (uint) {

        uint timestamp = time * prevRandom;
        uint seed = uint256(keccak256(abi.encodePacked(
            timestamp + 
            block.prevrandao +
            block.gaslimit + 
            block.number +
            // TODO: add some additional entropy via block.blockhash
            ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (timestamp)) +
            ((uint256(keccak256(abi.encodePacked(_msgSender())))) / (timestamp))

        return seed;

    function _transfer(address from, address to, uint amount) private nonReentrant returns (bool) { 
        randomX = semirandomize(randomX, block.timestamp);
        // transfer logic


The random number is generated from the block.timestamp (plus some other data) of any transaction of the token by anyone, which gives a high degree of randomness. Every transaction rehashes the previous random value with the timestamp + metadata of the current transaction. This effectively makes the number impossible to manipulate except by block miners. It also inhibits transaction spamming to try to brute force a wanted number, as each new transaction will increase entropy by (some math function).


Generate a sufficient amount of entropy to require it to take more time for block miners to manipulate the number to their desired amount, than the amount of time it takes for the next blockhash to be generated on the chain, or make it substantially cost-ineffective for it to do so, to a range of say £100,000.


I am aware that any variable on the blockchain, even one marked as private, notably randomX is accessible by web3 to a savvy attacker. However due to my private implementation, being able to predict the number does not matter as much as being unable to manipulate it, although both being unpredictable is preferred.

I am also aware there are several other questions relating to random number generation on the Ethereum blockchain, however I believe the specificity and method of my approach are unique enough to warrant a separate question on the topic.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.