黑基网 首页 IT教程 编程开发 查看内容

200行Go代码实现区块链——挖矿算法

2018-3-8 12:53| 投稿: xiaotiger |来自: 互联网

摘要: 大家都无不惊呼比特币、以太坊及其他加密电子货币的持续狂热,特别是对于刚接触这个领域的新手,不断得听到张三李四通过 GPU “挖矿”而聚集价值数万乃至数百万加密电子货币。那么“挖矿”到底是什么? 它是如何工作 ...

大家都无不惊呼比特币、以太坊及其他加密电子货币的持续狂热,特别是对于刚接触这个领域的新手,不断得听到张三李四通过 GPU “挖矿”而聚集价值数万乃至数百万加密电子货币。那么“挖矿”到底是什么? 它是如何工作的? 相信对于程序员来说,没有什么比自己动手实践一遍“挖矿”算法更好的学习办法了。

在这篇文章中,让我们一起逐个解读每一个问题,并最终编写出自己的“挖矿”算法。这个算法称为工作证明算法(Proof-of-Work)[3],它是比特币和以太坊这两种最流行的加密货币的基础。

什么是“挖矿”?

加密电子货币因为稀缺才具有价值。以现在的比特币为例,如果任何人任何时候都可以随意“制造”比特币,那么作为电子货币它会变得毫无价值。比特币通过算法来控制产出的速率并在大约122年内达到最大量。这种随着时间推移缓慢、稳定并逐步产出的方式有效避免了通货膨胀。

比特币的产出是通过给予“获胜矿工”奖励来实现,为了获取比特币奖励矿工之间会进行竞争。这个过程之所以被称为“挖矿”,是因为它类似于“Gold Rush”[4]时每个黄金矿工通过辛苦劳作并最终(希望)找到一点黄金。

“挖矿”是如何工作的?

如果 Google 一下这个问题,你会得到大量的结果。简单来说,“挖矿”就是“解决一个数学难题”的过程。我们先来了解一些密码学和哈希算法的知识。

密码学简要介绍

单向加密以人类可读的文本(明文)作为输入,比如“Hello world”这个字符串,再通过一个数学函数产生出难以辨认的输出(密文)。 这类函数或算法的性质和复杂性各不相同。 算法越复杂,逆向工程就越困难。

以流行的 SHA-256 算法为例。 通过这个网站[5]可以让你计算任意给定输入的输出,也就是 SHA-256 哈希值。比如让我们输入“Hello world”,看看得到了什么:

通过不断尝试计算“Hello world”的哈希值。你会发现每次的结果都完全相同。 这个过程称为幂等性。

加密算法一个最基本的特性是,非常难以通过反向工程来求解输入,但是非常容易验证输出。比如上面的例子,你可以很容易验证给定输入“Hello world”的SHA-256哈希值是否正确,但很难通过给定的哈希值判断它的输入是什么。这就是为什么将这种类型的算法称为单向加密。

比特币使用 Double SHA-256,它将 SHA-256 求得的哈希值作为输入再次计算 SHA-256 哈希值。 为了简化,我们只使用一次SHA-256。

挖矿

回到加密电子货币中,比特币就是通过让参与者利用这样的加密算法求解出符合特定条件的哈希值来实现“挖矿”过程。具体来说,比特币要求参与者通过 double SHA-256 算法计算出“前导0”超过若干位的哈希值,第一个求解出来的参与者就是“获胜的矿工”。

比如,我们求“886”这个字符串的 SHA-256 哈希值:

可以看到,是一个“前导0”为3位的哈希值(前三位是0)。

回忆我们前面说到的“单向加密”的特点:

任何人都可以很容易地验证“886”是否产生3位“前导0”的哈希值。但为了找到这样一个能产生3位“前导0”的输入(就是这里的“886”),我们做了大量繁琐的计算工作:从一个很大的数字和字母集合中逐个计算它们的哈希值并判断是否满足上述条件。如果我是第一个找到“886”的人,那其他人通过验证就能判断我做了这样大量繁琐的工作。在比特币、以太坊中这样的过程就称为工作证明算法。

“如果我运气非常好,第一次尝试就找到了一个符合条件的(输入)值呢?” —— 这是非常不可能的,你可以试试随意输入一些字母和数字。

比特币中实际的算法和约束要比上说要求复杂,当然也更难(要求更多位的“前导0”)。同时它也可以动态调整难度,目标是确保每隔10分钟产出一次比特币,不管参与“挖矿”的人多还是少。

差不多可以动手了

了解了足够的背景知识,接着我们就用 Go 语言来编码实践下工作量证明(Proof-of-Work)算法。

建议你阅读之前的《用200行Go代码实现自己的区块链》系列文章,因为下面工作证明算法部分会涉及之前的代码。

Proof-of-work

创建新块并加入到链上之前需要完成“工作量证明”过程。我们先写一个简单的函数来检查给定的哈希值是否满足要求。

  • 哈希值必须具有给定位的“前导0”

  • “前导0”的位数是由难度(difficulty)决定的

  • 可以动态调整难度(difficulty)来确保 Proof-of-Work 更难解

下面就是 isHashValid这个函数:

func isHashValid(hash string, difficulty int) bool {
prefix := strings.Repeat("0", difficulty)
return strings.HasPrefix(hash, prefix)
}

Go 语言的 strings包中提供了方便的RepeatHasPrefix函数。我们定prefix变量,它代表“前导0”,接着检查哈希值是否具有满足条件的“前导0”,然后返回TrueFalse

我们修改之前生成块的generateBlock函数:

func generateBlock(oldBlock Block, BPM int) Block {
var newBlock Block

t := time.Now

newBlock.Index = oldBlock.Index + 1
newBlock.Timestamp = t.String
newBlock.BPM = BPM
newBlock.PrevHash = oldBlock.Hash
newBlock.Difficulty = difficulty

for i := 0; ; i++ {
hex := fmt.Sprintf("%x", i)
newBlock.Nonce = hex
if !isHashValid(calculateHash(newBlock), newBlock.Difficulty) {
fmt.Println(calculateHash(newBlock), " do more work!")
time.Sleep(time.Second)
continue
} else {
fmt.Println(calculateHash(newBlock), " work done!")
newBlock.Hash = calculateHash(newBlock)
break
}

}
return newBlock
}

创建一个新块 newBlock,里面的PrevHash包含前一个块的哈希值,Timestamp是时间戳,BPM是心率数据,Difficulty就是前面提到的难度,它的值决定了“前导0”的位数。

这里的 for循环很重要:

  • 获得 i的十六进制表示 ,将Nonce设置为这个值,并传入calculateHash计算哈希值。之后通过上面的isHashValid函数判断是否满足难度要求,如果不满足就重复尝试。

  • 这个计算过程会一直持续,知道求得了满足要求的 Nonce值,之后通过handleWriteBlock函数将新块加入到链上。

篇幅有限,我们已经将完整代码发布在 Github上,可以从这里[6]获得。

跑起来看看

启动程序:

go run main.go

在浏览器中访问 http://localhost:8080

接着通过 Postman 来发送一个包含心率数据的POST请求。

接着我们观察命令行窗口,不断得计算哈希值,如果不满足难度要求就继续重试,直到找到满足要求的哈希值及 Nonce

可以看到最后一个哈希值满足我们设定的难度要求(1位“前导0”)。我们再来刷新下浏览器:

可以看到第二个块创建成功并加到链上了,其中Nonce就是通过Proof-of-Work计算出来满足难度要求的值。

下一步

到这里要先祝贺你,上面的内容很有价值。尽管我们的示例中使用了非常低的难度,但本质上,工作证明算法就是比特币、以太坊等区块链的重要组成。

对于下一步应该深入区块链的哪个方向,我们推荐可以学习如何通过 IPFS [7]存取大文件并与区块链打通。

此外相比 Proof-of-Work,Proof-of-Stake 算法[8]正越来越受到关注和青睐,你也可以学习如何将本文的 PoW 算法改为实现 PoS 算法。

参考链接

[3] https://en.bitcoin.it/wiki/Proof_of_work

[4] https://zh.wikipedia.org/zh-cn/%E6%B7%98%E9%87%91%E6%BD%AE

[5] http://www.xorbin.com/tools/sha256-hash-calculator

[6] https://github.com/mycoralhealth/blockchain-tutorial/blob/master/proof-work/main.go

[7] https://github.com/ipfs/ipfs

[8] https://en.bitcoin.it/wiki/Proof_of_Stake

, groupId: 6530122227294142979, itemId: 6530122227294142979, type: 2, subInfo: { isOriginal: false, source: 高可用架构, time: 2018-03-07 16:49:12 }, tagInfo: { tags: [{"name":"Go语言"},{"name":"数字货币"},{"name":"比特币"},{"name":"程序员"},{"name":"GPU"}], groupId: 6530122227294142979, itemId: 6530122227294142979, repin: 0, }, has_extern_link: 0 }, commentInfo: { groupId: 6530122227294142979, itemId: 6530122227294142979, comments_count: 15, ban_comment: 0 }, mediaInfo: { uid: 5858481053, name: 高可用架构, avatar: //p1.pstatp.com/large/11401/5158861846, openUrl: /c/user/5858481053/, follow: false }, pgcInfo: {"media_info":{"open_url":"/c/user/5858481053/","avatar_url":"https://p1.pstatp.com/large/11401/5158861846","media_id":5858481053,"name":"高可用架构","user_verified":false},"articles":[{"item_id":"6530122227294142979","url":"/item/6530122227294142979","title":"200行Go代码实现区块链——挖矿算法"},{"item_id":"6527936902044058115","url":"/item/6527936902044058115","title":"区块链傻瓜书:EOS与以太坊对比"},{"item_id":"6527700933588025869","url":"/item/6527700933588025869","title":"TON:一个多链多币的宏伟蓝图"},{"item_id":"6527278547336167939","url":"/item/6527278547336167939","title":"美拍直播首屏耗时减少50%以上的优化实践"}]}, feedInfo: { url: /api/pc/feed/, category: __all__, initList: [{"comments_count":108,"media_avatar_url":"//p9.pstatp.com/large/2c6c0004f1317234de20","is_feed_ad":false,"is_diversion_page":false,"title":"全国通缉|以下90后女子涉及案情重大,知情即报警","single_mode":true,"gallary_image_count":1,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530379214506426893/","source":"中山网警","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":0,"image_url":"//p9.pstatp.com/list/190x124/6c350003093696c5ff99","group_id":"6530379214506426893","is_related":true,"media_url":"/c/user/5771849617/"},{"comments_count":71,"media_avatar_url":"//p8.pstatp.com/large/4700000217be57734e08","is_feed_ad":false,"is_diversion_page":false,"title":"当一个女生问“你在干嘛”的回答技巧","single_mode":true,"gallary_image_count":5,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6527936474132775432/","source":"情圣都是大背头","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":5,"image_url":"//p3.pstatp.com/list/190x124/pgc-image/1519903535087940b884040","group_id":"6527936474132775432","is_related":true,"media_url":"/c/user/70776741123/"},{"comments_count":140,"media_avatar_url":"//p2.pstatp.com/large/41100083a7ca7958545","is_feed_ad":false,"is_diversion_page":false,"title":"红极一时的打星,两度离婚后负债累累,暴毙家中数日无人管","single_mode":true,"gallary_image_count":13,"middle_mode":true,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530100241931174408/","source":"阳光八卦君","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":27,"image_url":"//p3.pstatp.com/list/190x124/6c370000c39949a0f4ce","group_id":"6530100241931174408","is_related":true,"media_url":"/c/user/6369728762/"},{"comments_count":26,"media_avatar_url":"//p1.pstatp.com/large/123400104fe52f80a45c","is_feed_ad":false,"is_diversion_page":false,"title":"张国立为邓婕补办婚礼,邓婕感动落泪,揭开两人为何没有孩子","single_mode":true,"gallary_image_count":8,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6529805405655138823/","source":"娱乐而已的","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":119,"image_url":"//p9.pstatp.com/list/190x124/6c2c000643b62bb76a55","group_id":"6529805405655138823","is_related":true,"media_url":"/c/user/51598714121/"},{"comments_count":45,"media_avatar_url":"//p7.pstatp.com/large/382c000f20ed158b9baa","is_feed_ad":false,"is_diversion_page":false,"title":"儿子多年未归老人抱怨,她在儿媳房间找针线,拉开抽屉她泪如雨下","single_mode":true,"gallary_image_count":3,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530143298856681997/","source":"小瞄一眼","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":11,"image_url":"//p3.pstatp.com/list/190x124/6c3700017abeaf47cbf4","group_id":"6530143298856681997","is_related":true,"media_url":"/c/user/63634120887/"},{"comments_count":23,"media_avatar_url":"//p8.pstatp.com/large/1dcd0002ad7052805d1c","is_feed_ad":false,"is_diversion_page":false,"title":"法国将自愿性行为最低年龄设为15岁,其他各国的合法年龄是几岁?","single_mode":true,"gallary_image_count":4,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530220300469010951/","source":"iWeekly","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":28,"image_url":"//p1.pstatp.com/list/190x124/6c3400037425b1d25e45","group_id":"6530220300469010951","is_related":true,"media_url":"/c/user/3083144690/"},{"comments_count":185,"media_avatar_url":"//p3.pstatp.com/large/1643/3664816546","is_feed_ad":false,"is_diversion_page":false,"title":"一洗澡就痒是怎么回事?专家提醒:或离不开这两种原因","single_mode":true,"gallary_image_count":3,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6529273869230932493/","source":"家庭医生在线","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":33,"image_url":"//p1.pstatp.com/list/190x124/66c60005f1039820251a","group_id":"6529273869230932493","is_related":true,"media_url":"/c/user/3672368498/"},{"comments_count":61,"media_avatar_url":"//p6.pstatp.com/large/437f00016953ab3bcb2e","is_feed_ad":false,"is_diversion_page":false,"title":"一张图告诉你北京月入2万高逼格程序员上下班都在做什么","single_mode":true,"gallary_image_count":1,"middle_mode":true,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6505746565720703491/","source":"超脑智能","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":0,"image_url":"//p9.pstatp.com/list/190x124/53f30002562d0142af74","group_id":"6505746565720703491","is_related":true,"media_url":"/c/user/56694986859/"},{"comments_count":86,"media_avatar_url":"//p1.pstatp.com/large/12330008d131336a7a72","is_feed_ad":false,"is_diversion_page":false,"title":"工作中领导说做你就做?说不做你就不做?看看老油条是怎么做的!","single_mode":true,"gallary_image_count":4,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530189757048160781/","source":"微言职场","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":1,"image_url":"//p1.pstatp.com/list/190x124/6c350002559779d2474e","group_id":"6530189757048160781","is_related":true,"media_url":"/c/user/52914216910/"},{"comments_count":260,"media_avatar_url":"//p3.pstatp.com/large/ef600112027c38b89ca","is_feed_ad":false,"is_diversion_page":false,"title":"吴宗宪烧饼店关门 感叹:哪个老板受得了一例一休","single_mode":true,"gallary_image_count":1,"middle_mode":true,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530170798634697219/","source":"北青网","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":11,"image_url":"//p1.pstatp.com/list/190x124/65c2000c7dd080ee83a2","group_id":"6530170798634697219","is_related":true,"media_url":"/c/user/52255723016/"},{"comments_count":92,"media_avatar_url":"//p3.pstatp.com/large/12320011f741437a9838","is_feed_ad":false,"is_diversion_page":false,"title":"既然近视可以做激光手术,那为什么很多做手术的医生却戴眼镜?","single_mode":true,"gallary_image_count":1,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530367669365899783/","source":"医患家","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":0,"image_url":"//p3.pstatp.com/list/190x124/6c29000437628407d8b8","group_id":"6530367669365899783","is_related":true,"media_url":"/c/user/53070025997/"},{"comments_count":911,"media_avatar_url":"//p5a.pstatp.com/large/3832001d6176c8b270c9","is_feed_ad":false,"is_diversion_page":false,"title":"看懂这些动图原理,你就是老司机,不服来战,,,","single_mode":true,"gallary_image_count":22,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6528597366793044494/","source":"爱学习的汽车人","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":0,"image_url":"//p1.pstatp.com/list/190x124/66c300058dfdd2e17e16","group_id":"6528597366793044494","is_related":true,"media_url":"/c/user/4568622897/"},{"comments_count":9,"media_avatar_url":"//p1.pstatp.com/large/ef300169eec322349a7","is_feed_ad":false,"is_diversion_page":false,"title":"农村宅基地新规,要知道这3点要了解,要不然宅基地就不是你的了","single_mode":true,"gallary_image_count":3,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530371077309202947/","source":"骏景农业","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":28,"image_url":"//p9.pstatp.com/list/190x124/6c350002f035c0936c96","group_id":"6530371077309202947","is_related":true,"media_url":"/c/user/52460115391/"},{"comments_count":102,"media_avatar_url":"//p1.pstatp.com/large/ef7000aff59ead6c674","is_feed_ad":false,"is_diversion_page":false,"title":"离37岁还有一个月,我被公司辞退了","single_mode":true,"gallary_image_count":1,"middle_mode":true,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6516281044285522446/","source":"首席人才官","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":30,"image_url":"//p9.pstatp.com/list/190x124/5b5a0003053f03ebd82a","group_id":"6516281044285522446","is_related":true,"media_url":"/c/user/5573457307/"},{"comments_count":61,"media_avatar_url":"//p3.pstatp.com/large/1dce0006d50dd75e6368","is_feed_ad":false,"is_diversion_page":false,"title":"2018年,在职场上最具含金量的10个证书!你准备考哪个?","single_mode":true,"gallary_image_count":10,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6509374172454453773/","source":"媛来思语","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":5,"image_url":"//p1.pstatp.com/list/190x124/568d000389818aa05900","group_id":"6509374172454453773","is_related":true,"media_url":"/c/user/59392920394/"},{"comments_count":161,"media_avatar_url":"//p1.pstatp.com/large/ef3000fb8bdbee380fe","is_feed_ad":false,"is_diversion_page":false,"title":"农村宅基地最全知识!看完没人再敢坑你!","single_mode":true,"gallary_image_count":7,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6499808943869526542/","source":"冬枣网","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":37,"image_url":"//p3.pstatp.com/list/190x124/4e6e00023341f4a1c164","group_id":"6499808943869526542","is_related":true,"media_url":"/c/user/51005698202/"},{"comments_count":3,"media_avatar_url":"//p3.pstatp.com/large/bc2000374269918957f","is_feed_ad":false,"is_diversion_page":false,"title":"被总理@4次!这个专业要火,新机遇来了!","single_mode":true,"gallary_image_count":10,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530113663288738311/","source":"经济日报","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":0,"image_url":"//p3.pstatp.com/list/190x124/65c4000b2b9f3cf2b8f7","group_id":"6530113663288738311","is_related":true,"media_url":"/c/user/50098460684/"},{"comments_count":19,"media_avatar_url":"//p2.pstatp.com/large/4ad4000f0430e71576b1","is_feed_ad":false,"is_diversion_page":false,"title":"鬼谷子谋略:职场,你的工作满足两个条件,工资低一点都别辞职!","single_mode":true,"gallary_image_count":4,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6497547411546702349/","source":"萍行职场","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":3,"image_url":"//p1.pstatp.com/list/190x124/4b0000019a77a9bd508a","group_id":"6497547411546702349","is_related":true,"media_url":"/c/user/15624790233/"},{"comments_count":18,"media_avatar_url":"//p1.pstatp.com/large/6cb0003068f5da06941","is_feed_ad":false,"is_diversion_page":false,"title":"母亲猝死墙壁里藏2万现金腐烂 银行员工化腐朽变现金","single_mode":true,"gallary_image_count":9,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6530364894837998094/","source":"看看新闻","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":55,"image_url":"//p3.pstatp.com/list/190x124/65c600015f940d343afc","group_id":"6530364894837998094","is_related":true,"media_url":"/c/user/5839829632/"},{"comments_count":29,"media_avatar_url":"//p3.pstatp.com/large/3c7f00025b2d680aa52d","is_feed_ad":false,"is_diversion_page":false,"title":"三国历史上他的牌最好!天下三次送到手上,他却连裤子都输掉!","single_mode":true,"gallary_image_count":6,"middle_mode":false,"has_video":false,"video_duration_str":null,"source_url":"https://www.toutiao.com/group/6528948845861143043/","source":"老魏说历史","more_mode":null,"article_genre":"article","has_gallery":false,"video_play_count":5,"image_url":"//p3.pstatp.com/list/190x124/66c700037724121cd7f4","group_id":"6528948845861143043","is_related":true,"media_url":"/c/user/59898168021/"}] }, shareInfo: { shareUrl: https://m.toutiao.com/item/6530122227294142979/, abstract: 在本系列前两篇文章中,我们向大家展示了如何通过精炼的Go代码实现一个简单的区块链。包括生成块,验证块数据,广播通信等等,这一篇让我们聚焦在如何实现PoW算法。
小编推荐:欲学习电脑技术、系统维护、网络管理、编程开发和安全攻防等高端IT技术,请 点击这里 注册黑基账号,公开课频道价值万元IT培训教程免费学,让您少走弯路、事半功倍,好工作升职加薪!



免责声明:本文由投稿者转载自互联网,版权归原作者所有,文中所述不代表本站观点,若有侵权或转载等不当之处请联系我们处理,让我们一起为维护良好的互联网秩序而努力!联系方式见网站首页右下角。


鲜花

握手

雷人

路过

鸡蛋

相关阅读

发表评论

最新评论


新出炉

返回顶部