How can we generate multiple random number in ethereum?

后端 未结 4 1646
离开以前
离开以前 2020-12-19 11:49

I want my smart contract to return 7 or 8 UNIQUE random numbers ranging from 1 to 100 upon calling the contract. What can be the best approach to obtain suc

4条回答
  •  我在风中等你
    2020-12-19 12:08

    Use a Chainlink VRF.

    There are a number of issues with using the blockhash or similar as the method of random seeding. If an attacker knows the blockhash before your contract, they can use that information to gain a malicious advantage on whatever it is you're trying to do. An oracle can help here, but they are a central source of failure and must be able to prove they are random.

    You need to have an oracle network that can:

    1. Prove that the numbers generated are random.
    2. Have enough oracles/nodes that even if one fails/is corrupt, your smart contract will persist.

    At this time, the example below shows how to solve #1. You can solve #2 by pulling from a sufficient number of nodes who support the Chainlink VRF.

    For an exact implementation, see this answer from a similar question.

    You'll want to make a request to a node with a function that takes a seed generated by you:

     function rollDice(uint256 userProvidedSeed) public returns (bytes32 requestId) {
            require(LINK.balanceOf(address(this)) > fee, "Not enough LINK - fill contract with faucet");
            uint256 seed = uint256(keccak256(abi.encode(userProvidedSeed, blockhash(block.number)))); // Hash user seed and blockhash
            bytes32 _requestId = requestRandomness(keyHash, fee, seed);
            emit RequestRandomness(_requestId, keyHash, seed);
            return _requestId;
        }
    

    And when the value is returned, you'll mod it by 100 and add 1. You'll need to call this 7 or 8 times if you want 7 or 8 random numbers.

    function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
            uint256 d6Result = randomness.mod(100).add(1);
            emit RequestRandomnessFulfilled(requestId, randomness);
        }
    
    

提交回复
热议问题