兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx

上传人:b****3 文档编号:4118104 上传时间:2022-11-28 格式:DOCX 页数:9 大小:23.31KB
下载 相关 举报
兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx_第1页
第1页 / 共9页
兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx_第2页
第2页 / 共9页
兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx_第3页
第3页 / 共9页
兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx_第4页
第4页 / 共9页
兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx_第5页
第5页 / 共9页
点击查看更多>>
下载资源
资源描述

兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx

《兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx》由会员分享,可在线阅读,更多相关《兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx(9页珍藏版)》请在冰豆网上搜索。

兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式.docx

兄弟连Go语言培训以太坊源码分析55以太坊随机数生成方式

兄弟连Go语言+区块链技术培训以太坊源码分析(55)以太坊随机数生成方式

最近考虑一个基于以太坊的去中心化赌场的实现,赌场如果需要实现,那么随机数是必须的。

然后研究了一下以太坊里面的随机数生成,

发现并不容易。

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

#oraclize

Oraclize定位为去中心化应用的数据搬运工,他作为WebAPIs和DApp的可靠链接。

有了Oraclize,

就不需要建立额外的信任链,因为我们的行为已经被强制加密验证。

Oraclize是一个可证明的诚实的预言机服务,

可以让智能合约可以访问互联网。

Oraclize是平台无关的,为所有主流的智能合约能力平台提供一种虚拟的接口。

可以想像,

通过这个投入成千上万的有意义的数据到区块链中,可以使得智能合约产业更繁荣和更多有价值的应用呈现更大的生命力。

Oraclize的使用方式可以参考下面的[代码]

在update方法里面调用oraclize_newRandomDSQuery方法来调用Oracle的智能合约的代码,

Oracle根据请求来生成对应的数据,然后把结果通过回调__callback来传入。

    /*

    Oraclizerandom-datasourceexample

    

    Thiscontractusestherandom-datasourcetosecurelygenerateoff-chainNrandombytes

    */

    

    pragmasolidity^0.4.11;

    

    import"

    

    contractRandomExampleisusingOraclize{

    

    eventnewRandomNumber_bytes(bytes);

    eventnewRandomNumber_uint(uint);

    

    functionRandomExample(){

    oraclize_setProof(proofType_Ledger);//setstheLedgerauthenticityproofintheconstructor

    update();//let'saskforNrandombytesimmediatelywhenthecontractiscreated!

    }

    

    //thecallbackfunctioniscalledbyOraclizewhentheresultisready

    //theoraclize_randomDS_proofVerifymodifierpreventsaninvalidprooftoexecutethisfunctioncode:

    //theproofvalidityisfullyverifiedon-chain

    function__callback(bytes32_queryId,string_result,bytes_proof)

    {

    //ifwereachthispointsuccessfully,itmeansthattheattachedauthenticityproofhaspassed!

    if(msg.sender!

=oraclize_cbAddress())throw;

    

    if(oraclize_randomDS_proofVerify__returnCode(_queryId,_result,_proof)!

=0){

    //theproofverificationhasfailed,doweneedtotakeanyactionhere?

(dependsontheusecase)

    }else{

    //theproofverificationhaspassed

    //nowthatweknowthattherandomnumberwassafelygenerated,let'suseit..

    

    newRandomNumber_bytes(bytes(_result));//thisistheresultingrandomnumber(bytes)

    

    //forsimplicityofuse,let'salsoconverttherandombytestouintifweneed

    uintmaxRange=2**(8*7);//thisisthehighestuintwewanttoget.Itshouldneverbegreaterthan2^(8*N),whereNisthenumberofrandombyteswehadaskedthedatasourcetoreturn

    uintrandomNumber=uint(sha3(_result))%maxRange;//thisisanefficientwaytogettheuintoutinthe[0,maxRange]range

    

    newRandomNumber_uint(randomNumber);//thisistheresultingrandomnumber(uint)

    }

    }

    

    functionupdate()payable{

    uintN=7;//numberofrandombyteswewantthedatasourcetoreturn

    uintdelay=0;//numberofsecondstowaitbeforetheexecutiontakesplace

    uintcallbackGas=200000;//amountofgaswewantOraclizetosetforthecallbackfunction

    bytes32queryId=oraclize_newRandomDSQuery(delay,N,callbackGas);//thisfunctioninternallygeneratesthecorrectoraclize_queryandreturnsitsqueryId

    }

    

    }

考虑一个提供打赌的智能合约。

用户调用打赌的接口,这个接口会把用户的请求存储起来,然后调用Oracle随机数生成服务。

然后通过Oracle回调服务,判断随机数是否大于某个值,如果成立,那么用户成功,否则用户失败。

这就是典型的Oracle的使用案例。

#RANDAO:

ADAOworkingasRNGofEthereum

[randao](

**Randomnumberinprogrammingisveryimportant!

**

**RNGinadeterministicsystemisverydifficult**

**Minerscan'tbetrusted!

**

随机数在编程中是非常重要的。

RNG在一个确定性的系统中是非常难的。

不能相信矿工

##解决方案

Solutions

ADAO(decentralisedautonomousorganisation)thatanyonecanparticipatein,andtherandomnumberisgeneratedbyallparticipantstogether!

Firstofall,weneedtocreateaRANDAOcontractintheblockchain,whichdefinestheparticipationrules.Thenthebasicprocessofgeneratingarandomnumbercanbedividedintothreephases:

一个DAO(去中心化的匿名组织)允许任何人加入,随机数是被所有的参与者一起合作生成的。

首先,我们需要在区块链上创建一个RANDAO的智能合约,合约定义了参与规则。

然后生成随机数的基本过程可以分为下面三个步骤:

**Thefirstphase:

collectingvalidsha3(s)**

AnyonewhowanttoparticipateintherandomnumbergenerationneedstosendatransactiontothecontractCwithmETHaspledgeinaspecifiedtimeperiod(e.g,6blockperiod,approximately72s),accompaniedbytheresultofsha3(s),sisthesecretnumberrespectivepickedbyparticipant.

**第一步:

收集有效的sha3(s)**

参与随机数生成的参与者首先需要在一个指定的时间区间(比如,6个区块的区间,大约72秒)发送mETH作为抵押到智能合约C,同时发送一个sha3(s)的值到智能合约C,s是一个只有参与者自己知道的数字.

**Thesecondphase:

collectingvalids**

Afterthefirstphase,anyonewhosubmittedsha3(s)successfullyneedstosendatransactionwiththesecretnumbersinthefirststagetocontractCwithinaspecifiedtimeperiod.ContractCwillcheckifsisvalidbyrunningsha3againstsandcomparingtheresultwithpreviouscommitteddata.Validswillbesavedtothecollectionofseedstofinallygeneratetherandomnumber.

**第二步:

收集有效的s**

在第一步结束后,那些提交了sha3(s)的参与者需要在指定的时间区间内发送s到智能合约C.智能合约C会检查sha3(s)和之前提交的值是否相同。

相同的s会被保存到种子集合用来最终生成随机数。

**Thethirdphase:

calculatingarandomnumber,refundpledgedETHandbonus**

-Afterallsecretnumbershavebeensuccessfullycollected,contractCwillcalculatetherandomnumberfromthefunctionf(s1,s2,...,sn),theresultwillbewrittentothestorageofC,andtheresultwillbesenttoallothercontractsthatrequestedtherandomnumberbefore.

-ContractCwillsendbackthepledgetotheparticipantsinthefirstphase,andtheprofitisdividedintoequalpartsandsenttoallparticipantsasanadditionalbonus.Theprofitcomesfromthefeesthatispaidbyothercontractsthatconsumetherandomnumber.

**第三步:

计算随机数,退回抵押和奖金**

-在所有的秘密数字s被成功收集后,智能合约C会使用函数f(s1,s2,...,sn)来计算随机数,随机数的结果会写入智能合约的存储,而且结果会被发送到所有之前请求随机数的其他智能合约上面。

-智能合约C会把第一阶段的抵押返回给参与者,然后奖金会被分成同等分发送给所有的参与者。

奖金来源于请求随机值的其他智能合约。

##Additionalrules

InordertoensuretheRNGcan'tbemanipulated,aswellasforsafetyandefficiency,thecontractChasthefollowingadditionalrules:

-Thefirstphase,iftwoormoreofthesamesha3(s)aresubmittedinsequence,onlythefirstoneisaccepted.

-Thefirstphase,thereisarequirementforminimumnumberofparticipants,ifitfailstocollectenoughsha3(s)withinthetimeperiod,thenRNGatthisblockheightwillfail.

-Ifaparticipantsubmitsthesha3(s)anditisacceptedbycontractC,hemustrevealthesinthesecondphase.

    -Iftheparticipantfailstorevealsinthesecondphase,thenthemETHsentinthefirstphasewillbeconfiscatedwithoutprovidingareturn.

    -Ifoneormoresisn'trevealedinthesecondphase,RNGatthisblockheightwillfail.ConfiscatedETHswillbedividedequallyandsendtootherparticipantswhorevealedsatthesecondphase.Thefeespaidbyothercontractswillberefunded.

补充规则

为了确保RNG不能被操控,以及为了安全和效率,智能合约C有以下的补充规则:

-在第一步中,如果有两个或更多个的同样的sha3(s)被提交上来,那么只有第一个会被接受。

-在第一步中,对于参与者有最低要求,如果在指定的时间区间内没有收集到足够多的sha3(s)的值,那么RNG在这个区块高度会失败。

-如果参与者提交了sha3(s),那么他必须在第二步提交s

    -如果参与者在第二步没有提交s,那么第一阶段提供的mETH会被没收而且没有奖励。

    -如果一个或者多个s没有在第二步被提交,RNG在这个区块高度会失败。

没收的ETH会被分成同等分发送给提交了s的其他参与者。

其他申请随机数的其他合约的费用会被退回。

##Incentive

TheRNGcycleisveryshort,andcouldbeforexample20cyclesinonehour,ifonecycle'sprofitis0.001%,themonthlyrateofreturnisupto0.00001*20*24*30=0.144.Targetingto14.4%monthlyrateofreturn,andRNGhasnparticipantsonaverage,therunningcostsofcontractisn*3*500*gasPrice+Ccost.(Ccostisgasconsumedbycontractinternally,includingcomputingandstorage,etc.)Assumingeachrandomnumbershasrtimerequestsonaverage,thecallpriceispETH,theincomeisr*p.Soeachparticipantwillget(rp-1500n*gasPrice-Ccost)/nfromonetimeparticipation.ThecurrentgasPriceis10szabo,andestimateofcontractconsumptionis1500ngas,soestimateofnetincomeis(rp/n-0.03)ETH.AssumingeachRNGhas10participation,andthepledgeis1000ETH,theminimumrequiredincomeis0.4ETH,whichover0.001%profitinthiscase.SoiftheRNGisrequestedonlyonce,theservicepriceis0.4ETH,andifitisrequested10times,thepriceisjust0.04ETHforeachrequest.

激励

RNG的周期非常短,例如一个小时20个生成周期,如果没有周期的利润是0.001%,一个月的盈利会达到0.00001*20*24*30=0.144。

为了达到14.4%每个月的盈利,并且RNG平均有n个参与者,运行智能合约C的费用为n*3*500*gasPrice+Ccost.(CCost是合约内部的gas消费,包括计算和存储)假设每个随机值平均有r个请求,每个请求的费用是pETH,那么收入是r*p.所以每个参与者每一次参与会收到rp-1500n*gasPrice-Ccost)/n。

当前的gasPrice是10szabo,合约的消费大概是1500ngas,所以大概的净收入是(rp/n-0.03)ETH.假设每个RNG有10个参与者,并且抵押是1000ETH,所以如果RNG如果只请求一次,那么一次的费用是0.4ETH,如果请求是10次,那么一次请求的价格会被降到0.04ETH

TheRANDAOactsasaninfrastructureintheEthereumsystem.Itiscalledbyothercontracts.Contractsfordifferentpurposesrequiredifferentrandomnumbers:

someneedhighsecurity,suchaslottery;someneedsteadyresponsesandtherequestshouldberespondedimmediately,thesecontractsarenormallylow-value;someneedacallback,theywanttoreceiveanotificationwithrandomnumberswhennumbersareready.

Obviouslyit'simpossibletomeetdifferentrequirementsinvariousscenarioswithonlyoneRNGcontract,soalotofcontractswillbecreatedwithdifferentinitialparameters,butthebasicrulesarethesame.

RANDAO作为以太坊系统的基础设施。

被其他的合约调用。

不同的合约因为有不同的目的所以需要不同的随机值:

有些需要高度加密的,比如说抽奖;有些需要稳定的回应,并且要求立即作出回应,这些合约本身的价值不高;有些需要回调函数,当随机值已经生成的时候需要接收到通知。

很明显通过单一的RNG合约不可能满足所有的不同的请求,所以使用了不同的初始值创建了很多智能合约,不过他们基本的规则是相同的。

Forexample,ifweneedhighsecurity,wecansubstantiallyincreasethepledgeofthefirstphase.Thus,thecostofleadingtofailureofRNGprocessbynotrevealingsisgreatlyincreased.Andforthecontractswithoutmuchinterestinvolved,theminimumnumberofparticipantsandthepledgecanbelower.

Let'slookatanexampleofadAppbettingonoddorevennumbers,we'llshowhowtoadjustthecontract'sp

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 法律文书 > 起诉状

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1