Recently, we have considered an ethereum-based decentralized Du-field implementation. If Du-field needs to be implemented, the random number is required. Then I studied the random number generation in ethereum and found that it was not easy.
Several methods for generating random numbers in eth.
Oraclize
Zoolize is positioned as a data Porter for decentralized applications. It serves as a reliable link between Web APIs and dapp. With mongolize,
There is no need to establish an extra trust chain because our behavior has been forcibly encrypted for verification. Mongolize is a proven and honest Oracle service,
Allows smart contracts to access the Internet. Oraclize is platform independent and provides a virtual interface for all mainstream smart contract capability platforms. As you can imagine,
By investing tens of thousands of meaningful data into the blockchain, the smart contract industry can become more prosperous and more valuable.
For details about how to use oraclize, refer to the [Code] below.
(Github.com/javaslize/ethereum-examples/blob/master/solidity/random-performance/randomexample.sol)
Call the oraclize_newrandomdsquery method in the update method to call the Oracle smart contract code,
Oracle generates the corresponding data based on the request, and then passes the result through callback _ callback.
???? /
???? Oraclize random-datasource example
????
???? This contract uses the random-datasource to securely generate off-chain n random bytes
????/
????
???? Pragma solidity ^ 0.4.11;
????
???? Import "github.com/oraclize/ethereum-api/oraclizeapi.sol ";
????
???? Contract randomexample is using‑lize {
????
???? Event newrandomnumber_bytes (bytes );
???? Event newrandomnumber_uint (uint );
????
???? Function randomexample (){
???? Define lize_setproof (prooftype_ledger); // sets the ledger authenticity proof in the constructor
???? Update (); // Let's ask for n random bytes immediately when the contract is created!
???? }
????
???? // The callback function is called by limit lize when the result is ready
???? // The specified lize_randomds_proofverify modifier prevents an invalid proof to execute this function code:
???? // The proof validity is fully verified on-chain
???? FunctionCallback (bytes32 _ queryid, string _ result, bytes _ proof)
???? {
???? // If we reach this point successfully, it means that the attached authenticity proof has passed!
???? If (msg. Sender! = Required lize_cbaddress () Throw;
????
???? If (inclulize_randomds_proofverifyReturncode (_ queryid, _ result, _ proof )! = 0 ){
???? // The proof verification has failed, do we need to take any action here? (Depends on the Use Case)
???? } Else {
???? // The proof verification has passed
???? // Now that we know that the random number was safely generated, let's use it ..
????
???? Newrandomnumber_bytes (bytes (_ result); // This is the resulting random number (bytes)
????
???? // For simplicity of use, let's also convert the random bytes to uint if we need
???? Uint maxrange = 2 *(87); // This is the highest uint we want to get. it shoshould never be greater than 2 ^ (8 * n), where N is the number of random bytes we had asked the datasource to return
???? Uint randomnumber = uint (sha3 (_ result) % maxrange; // This is an efficient way to get the uint out in the [0, maxrange] range
????
???? Newrandomnumber_uint (randomnumber); // This is the resulting random number (uint)
???? }
???? }
????
???? Function Update () payable {
???? Uint n = 7; // number of random bytes we want the datasource to return
???? Uint delay = 0; // number of seconds to wait before the execution takes place
???? Uint callbackgas = 200000; // amount of gas we want need lize to set for the callback function
???? Bytes32 queryid = fig (delay, N, callbackgas); // This function internally generates the correct limit lize_query and returns its queryid
???? }
????
????}
Consider a smart contract that provides du.
The user calls the du interface, which stores user requests and then calls the Oracle Random Number Generation Service.
Then, the Oracle callback service is used to determine whether the random number is greater than a certain value. If so, the user succeeds. Otherwise, the user fails.
This is a typical Oracle use case.
Randao: A Dao working as RNG of ethereum
Randao is a decentralized organization that generates ethereum random numbers,
Random Number in programming is very important!
RNG in a deterministic system is very difficult
Miners can't be trusted!
Random numbers are very important in programming.
RNG is very difficult in a deterministic system.
Cannot trust miners
Solution
Solutions
A Dao (decentralised autonomous organization) that anyone can participate in, and the random number is generated by all participating ants together! First of all, we need to create a randao contract in the blockchain, which defines the participation rules. Then the basic process of generating a random number can be divided into three phases:
A Dao (decentralized anonymous organization) allows anyone to join. a random number is generated by all the participants. First, we need to create a randao smart contract on the blockchain, and the contract defines the rules for participation. The basic process of generating a random number can be divided into the following three steps:
The first phase: collecting valid sha3 (s)
Anyone who want to maid in the random number generation needs to send a transaction to the Contract C with m eth as pledge in a specified time period (E. g, 6 block period, approximately 72 s), accompanied by the result of sha3 (s), S is the secret number respective picked by particle ant.
Step 1: collect valid sha3 (s)
Participants involved in random number generation must first send m eth as collateral to smart Contract C in a specified time interval (for example, the interval of 6 blocks, about 72 seconds, send a sha3 (s) value to smart Contract C. S is a number only known to the participants.
The second phase: collecting valid s
After the first phase, anyone who submitted sha3 (s) successfully needs to send a transaction with the secret number S in the first stage to Contract C within a specified time period. contract C will check if S is valid by running sha3 against S and comparing the result with previous committed data. valid s will be saved to the collection of seeds to finally generate the random number.
Step 2: collect valid s
At the end of step 1, the participants who submitted sha3 (s) must send s to smart Contract C within the specified time range. smart Contract C checks whether sha3 (s) is the same as the value submitted earlier. The same s will be saved to the seed set to generate a random number.
The third phase: Calculating a random number, refund pledged ETH and bonus
- After all secret numbers have been successfully collected, Contract C will calculate the random number from the function f (S1, S2 ,..., SN), the result will be written to the storage of C, and the result will be sent to all other contracts that requested the random number before.
- Contract C will send back the pledge to the participant in the first phase, and the profit is divided into equal parts and sent to all participant ants as an additional bonus. the profit comes from the fees that is paid by other contracts that consume the random number.
Step 3: Calculate the random number, return the mortgage and bonus
- After all the secret numbers s are successfully collected, smart Contract C uses the function f (S1, S2 ,..., SN) to calculate the random number. the random number result will be written to the smart contract storage, and the result will be sent to all other smart contracts that previously requested the random number.
- Smart Contract C will return the first phase of the mortgage to the participants, and then the bonus will be evenly distributed to all the participants. The bonus comes from other smart contracts with random request values.
Additional rules
In order to ensure the RNG can't be manipulated, as well as for safety and efficiency, the Contract C has the following additional rules:
-
The first phase, if two or more of the same sha3 (s) are submitted in sequence, only the first one is accepted.
-
The first phase, there is a requirement for minimum number of maid, if it fails to collect enough sha3 (s) within the time period, then RNG at this block height will fail.
- If a participant ant submits the sha3 (s) and it is accepted by Contract C, he must reveal the S in the second phase.
???? -If the participant ant fails to reveal s in the second phase, then the m eth sent in the first phase will be confiscated without providing a return.
???? -If one or more s isn' t revealed in the second phase, RNG at this block height will fail. confiscated eths will be divided equally and send to other participant ipants who revealed s at the second phase. the fees paid by other contracts will be refunded.
Supplementary Rules
To prevent RNG from being manipulated, and to ensure security and efficiency, smart Contract C has the following supplementary rules:
- In step 1, if two or more identical sha3 (s) are submitted, only the first one will be accepted.
- In step 1, there is a minimum requirement for participants. If a sufficient number of sha3 (s) values are not collected within the specified time range, RNG will fail in the height of the block.
- If the participant submits sha3 (s), the participant must submit s in step 2.
???? -If the Participant does not submit s in step 2, the m eth provided in phase 1 will be confiscated and no reward will be given.
???? -If one or more s are not submitted in step 2, RNG fails to be submitted at the height of the block. The confiscated ETH will be distributed equally to other participants who submitted S.
Fees for other contracts that apply for random numbers will be refunded.
Incentive
The RNG cycle is very short, and cocould be for example 20 cycles in one hour, if one cycle's profit is 0.001%, the monthly rate of return is up to 0.00001202430 = 0.144. Targeting to 14.4% monthly rate of return, and RNG has n maid on average, the running costs of contract is n3500Gasprice + ccost. (ccost is gas consumed by contract internally, including computing and storage, etc .) assuming each random numbers has r time requests on average, the call price is P Eth, the income is RP. So each maid will get (RP-1500nGasprice-ccost)/n from one time participant. the current gasprice is 10 Szabo, and estimate of contract consumption is 1500n gas, so estimate of net income is (RP/n-0.03) eth. assuming each RNG has 10 participant, and the pledge is 1000eth, the minimum required income is 0.4 Eth, which over 0.001% profit in this case. so if the RNG is requested only once, the service price is 0.4 Eth, and if it is requested 10 times, the price is just 0.04 ETH for each request.
Blockchain tutorial ethereum source code analysis ethereum Random Number Generation Method 1