最近考虑一个基于以太坊的去中心化赌场的实现, 赌场如果需要实现,那么随机数是必须的。 然后研究了一下以太坊里面的随机数生成,
发现并不容易。
以太坊里面生成随机数的几种方式。
# oraclize
Oraclize定位为去中心化应用的数据搬运工,他作为Web APIs和DApp的可靠链接。有了Oraclize,
就不需要建立额外的信任链,因为我们的行为已经被强制加密验证。Oraclize是一个可证明的诚实的预言机服务,
可以让智能合约可以访问互联网。Oraclize是平台无关的,为所有主流的智能合约能力平台提供一种虚拟的接口。可以想像,
通过这个投入成千上万的有意义的数据到区块链中,可以使得智能合约产业更繁荣和更多有价值的应用呈现更大的生命力。
Oraclize的使用方式可以参考下面的[代码]
(https://github.com/oraclize/ethereum-examples/blob/master/solidity/random-datasource/randomExample.sol)
在update方法里面调用oraclize_newRandomDSQuery方法来调用Oracle的智能合约的代码,
Oracle根据请求来生成对应的数据, 然后把结果通过回调__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 usingOraclize {
event newRandomNumber_bytes(bytes);
event newRandomNumber_uint(uint);
function RandomExample() {
oraclize_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 Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof)
{
// if we reach this point successfully, it means that the attached authenticity proof has passed!
if (msg.sender != oraclize_cbAddress()) throw;
if (oraclize_randomDS_proofVerify__returnCode(_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..
newRandomN