以太坊源码分析(54)以太坊随机数生成方式

本文深入探讨以太坊的随机数生成方式,详细分析其在区块链网络中的作用和实现原理。通过阅读,你可以了解以太坊如何确保随机数的公平性和不可预测性,这对于智能合约和游戏应用至关重要。
摘要由CSDN通过智能技术生成
最近考虑一个基于以太坊的去中心化赌场的实现, 赌场如果需要实现,那么随机数是必须的。 然后研究了一下以太坊里面的随机数生成,
发现并不容易。


以太坊里面生成随机数的几种方式。


# 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值