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

只用200行Go代码写一个自己的区块链!

2018-1-31 11:50| 投稿: xiaotiger |来自: 互联网

摘要: 区块链是目前最热门的话题,广大读者都听说过比特币,或许还有智能合约,相信大家都非常想了解这一切是如何工作的。这篇文章就是帮助你使用 Go 语言来实现一个简单的区块链,用不到 200 行代码来揭示区块链的原理! ...

区块链是目前最热门的话题,广大读者都听说过比特币,或许还有智能合约,相信大家都非常想了解这一切是如何工作的。这篇文章就是帮助你使用 Go 语言来实现一个简单的区块链,用不到 200 行代码来揭示区块链的原理!高可用架构也会持续推出更多区块链方面文章,欢迎点击上方蓝色『高可用架构』关注。

“用不到200行 Go 代码就能实现一个自己的区块链!” 听起来有意思吗?有什么能比开发一个自己的区块链更好的学习实践方法呢?那我们就一起来实践下!

因为我们是一家从事医疗健康领域的科技公司,所以我们采用人类平静时的心跳数据(BPM心率)作为这篇文章中的示例数据。让我们先来统计一下你一分钟内的心跳数,然后记下来,这个数字可能会在接下来的内容中用到。

通过本文,你将可以做到:

  • 创建自己的区块链

  • 理解 hash 函数是如何保持区块链的完整性

  • 如何创造并添加新的块

  • 多个节点如何竞争生成块

  • 通过浏览器来查看整个链

  • 所有其他关于区块链的基础知识

但是,对于比如工作量证明算法(PoW)以及权益证明算法(PoS)这类的共识算法文章中将不会涉及。同时为了让你更清楚得查看区块链以及块的添加,我们将网络交互的过程简化了,关于 P2P 网络比如“全网广播”这个过程等内容将在下一篇文章中补上。

让我们开始吧!

设置

我们假设你已经具备一点 Go 语言的开发经验。在安装和配置 Go 开发环境后之后,我们还要获取以下一些依赖:

go get github.com/davecgh/go-spew/spew

spew 可以帮助我们在 console 中直接查看 struct 和 slice 这两种数据结构。

go get github.com/gorilla/mux

Gorilla 的 mux 包非常流行, 我们用它来写 web handler。

go get github.com/joho/godotenv

godotenv 可以帮助我们读取项目根目录中的 .env 配置文件,这样我们就不用将 http port 之类的配置硬编码进代码中了。比如像这样:

ADDR=8080

接下来,我们创建一个 main.go 文件。之后我们的大部分工作都围绕这个文件,让我开始编码吧!

导入依赖

我们将所有的依赖包以声明的方式导入进去:

package main

import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"time"

"github.com/davecgh/go-spew/spew"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
)

数据模型

接着我们来定义一个结构体,它代表组成区块链的每一个块的数据模型:

type Block struct {
Index int
Timestamp string
BPM int
Hash string
PrevHash string
}
  • Index 是这个块在整个链中的位置

  • Timestamp 显而易见就是块生成时的时间戳

  • Hash 是这个块通过 SHA256 算法生成的散列值

  • PrevHash 代表前一个块的 SHA256 散列值

  • BPM 每分钟心跳数,也就是心率。还记得文章开头说到的吗?

接着,我们再定义一个结构表示整个链,最简单的表示形式就是一个 Block 的 slice:

var Blockchain Block

我们使用散列算法(SHA256)来确定和维护链中块和块正确的顺序,确保每一个块的 PrevHash 值等于前一个块中的 Hash 值,这样就以正确的块顺序构建出链:

散列和生成块

我们为什么需要散列?主要是两个原因:

  • 在节省空间的前提下去唯一标识数据。散列是用整个块的数据计算得出,在我们的例子中,将整个块的数据通过 SHA256 计算成一个定长不可伪造的字符串。

  • 维持链的完整性。通过存储前一个块的散列值,我们就能够确保每个块在链中的正确顺序。任何对数据的篡改都将改变散列值,同时也就破坏了链。以我们从事的医疗健康领域为例,比如有一个恶意的第三方为了调整“人寿险”的价格,而修改了一个或若干个块中的代表不健康的 BPM 值,那么整个链都变得不可信了。

我们接着写一个函数,用来计算给定的数据的 SHA256 散列值:

func calculateHash(block Block) string {
record := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash
h := sha256.New
h.Write(byte(record))
hashed := h.Sum(nil)
return hex.EncodeToString(hashed)
}

这个 calculateHash 函数接受一个块,通过块中的 Index,Timestamp,BPM,以及 PrevHash 值来计算出 SHA256 散列值。接下来我们就能便携一个生成块的函数:

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

t := time.Now
newBlock.Index = oldBlock.Index + 1
newBlock.Timestamp = t.String
newBlock.BPM = BPM
newBlock.PrevHash = oldBlock.Hash
newBlock.Hash = calculateHash(newBlock)

return newBlock, nil
}

其中,Index 是从给定的前一块的 Index 递增得出,时间戳是直接通过 time.Now 函数来获得的,Hash 值通过前面的 calculateHash 函数计算得出,PrevHash 则是给定的前一个块的 Hash 值。

校验块

搞定了块的生成,接下来我们需要有函数帮我们判断一个块是否有被篡改。检查 Index 来看这个块是否正确得递增,检查 PrevHash 与前一个块的 Hash 是否一致,再来通过 calculateHash 检查当前块的 Hash 值是否正确。通过这几步我们就能写出一个校验函数:

func isBlockValid(newBlock, oldBlock Block) bool {
if oldBlock.Index+1 != newBlock.Index {
return false
}
if oldBlock.Hash != newBlock.PrevHash {
return false
}
if calculateHash(newBlock) != newBlock.Hash {
return false
}
return true
}

除了校验块以外,我们还会遇到一个问题:两个节点都生成块并添加到各自的链上,那我们应该以谁为准?这里的细节我们留到下一篇文章,这里先让我们记住一个原则:始终选择最长的链。

通常来说,更长的链表示它的数据(状态)是更新的,所以我们需要一个函数

能帮我们将本地的过期的链切换成最新的链:

func
小编推荐:欲学习电脑技术、系统维护、网络管理、编程开发和安全攻防等高端IT技术,请 点击这里 注册黑基账号,公开课频道价值万元IT培训教程免费学,让您少走弯路、事半功倍,好工作升职加薪!



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


鲜花

握手

雷人

路过

鸡蛋

相关阅读

发表评论

最新评论

引用 游客 2018-3-19 01:46
Good post. I learn something more challenging on different blogs everyday. It should always be stimulating to learn content from different writers and observe a little something from their store. I抎 choose to use some with the content material on my blog whether or not you don抰 mind. Natually I抣l provide you with a hyperlink on your web blog. Thanks for sharing.
yeezy shoes http://gtiny.me/yzyys
引用 游客 2018-3-18 05:28
My wife and i felt quite delighted that Raymond managed to finish up his researching out of the precious recommendations he was given using your web site. It's not at all simplistic just to happen to be ** a gift of guidelines which often the rest could have been trying to sell. We remember we've got you to thank because of that. The specific illustrations you've made, the easy web site menu, the friendships you will help create - it is most remarkable, and it's really assisting our son in a ...
引用 游客 2018-3-17 20:22
Aw, this was a really nice post. In thought I want to put in writing like this additionally ?taking time and actual effort to make a very good article?but what can I say?I procrastinate alot and on no account seem to get one thing done.
adidas yeezy http://ix.sk/ePn1z
引用 游客 2018-3-16 17:19
After examine a couple of of the blog posts in your web site now, and I really like your method of blogging. I bookmarked it to my bookmark web site checklist and will likely be checking again soon. Pls try my website online as nicely and let me know what you think.
yeezy boost 350 v2 http://ux.nu/TES4S
引用 游客 2018-3-12 20:15
I needed to create you the very small observation so as to say thanks a lot once again just for the amazing concepts you've provided above. This is quite particularly generous with people like you to present easily what exactly most of us might have sold as an e-book in ** some cash for their own end, notably now that you might well have tried it in the event you desired. Those tricks also served as a great way to understand that someone else have the identical interest just as mine to under ...
引用 游客 2018-3-12 15:46
There is noticeably a bundle to learn about this. I assume you made certain good factors in features also.
yeezy boost 350 v2 http://youl.ink/yzyv2
引用 游客 2018-3-11 08:32
Spot on with this write-up, I truly suppose this web site wants much more consideration. I抣l probably be once more to read far more, thanks for that info.
yeezy boost http://ux.nu/zYtKh
引用 游客 2018-3-10 06:14
Can I just say what a reduction to search out somebody who truly knows what theyre speaking about on the internet. You positively know how you can bring a difficulty to light and make it important. Extra individuals must learn this and perceive this facet of the story. I cant believe youre no more common because you definitely have the gift.
adidas yeezy http://lovebyt.es/adyzy
引用 游客 2018-3-9 07:08
Your home is valueble for me. Thanks!?
yeezy boost 350 v2 http://ux.nu/XLU2A
引用 游客 2018-3-8 07:40
There are some interesting closing dates in this article but I don抰 know if I see all of them center to heart. There's some validity but I will take maintain opinion until I look into it further. Good article , thanks and we would like more! Added to FeedBurner as effectively
yeezy boost http://ux.nu/dQ6ki
引用 游客 2018-3-8 01:06
I would like to get across my admiration for your kind-heartedness for those people who really need help on in this concern. Your special dedication to getting the solution up and down had become extremely important and has really made ladies much like me to arrive at their pursuits. Your amazing warm and friendly instruction implies so much to me and substantially more to my office colleagues. Thanks a lot; from everyone of us.
Adidas NMD R1 Primeknit Tri-Color NoirCore Rouge-Blanc http://www. ...
引用 游客 2018-3-7 06:43
It抯 exhausting to find knowledgeable people on this topic, but you sound like you realize what you抮e talking about! Thanks
nmd http://www.adidasnmds.com
引用 游客 2018-3-6 04:46
Good post. I study something more difficult on completely different blogs everyday. It would always be stimulating to learn content from other writers and observe a little bit something from their store. I抎 choose to make use of some with the content material on my weblog whether you don抰 mind. Natually I抣l give you a link on your net blog. Thanks for sharing.
nike dunk shoes http://www.nikedunks.us.org
引用 游客 2018-3-5 05:59
I discovered your weblog website on google and verify just a few of your early posts. Proceed to maintain up the very good operate. I simply additional up your RSS feed to my MSN Information Reader. Seeking forward to reading more from you afterward!?
NMD R1 Runner PK All Black White http://www.adidas-nmds.us.com/nmd-r1-runner-pk-all-black-white-p-370.html
引用 游客 2018-3-5 00:05
Youre so cool! I dont suppose Ive read anything like this before. So good to find any person with some original ideas on this subject. realy thank you for beginning this up. this website is one thing that's needed on the internet, somebody with a little bit originality. helpful job for bringing one thing new to the web!
air jordans http://www.cheap-airjordans.us.com
引用 游客 2018-3-3 20:03
Good post. I study something more difficult on totally different blogs everyday. It's going to all the time be stimulating to learn content material from different writers and observe a little bit one thing from their store. I抎 desire to make use of some with the content on my weblog whether you don抰 mind. Natually I抣l provide you with a hyperlink in your internet blog. Thanks for sharing.
under armour curry 3 http://www.curry3.in.net
引用 游客 2018-3-3 18:39
I wish to express some thanks to this writer just for bailing me out of such a incident. Just after exploring through the the net and seeing tips which were not beneficial, I figured my entire life was well over. Existing without the presence of answers to the issues you've resolved as a result of this review is a serious case, as well as the kind which could have adversely damaged my entire career if I had not noticed your web blog. Your good expertise and kindness in maneuvering all the pieces ...
引用 游客 2018-3-2 17:34
It抯 laborious to seek out educated folks on this matter, however you sound like you understand what you抮e speaking about! Thanks
yeezy boost http://www.yeezy-boost.us.com
引用 游客 2018-3-2 00:11
I together with my pals were found to be reading through the good information from your website while suddenly I got a terrible suspicion I never expressed respect to the site owner for those secrets. All of the boys are actually as a result happy to learn all of them and now have truly been using those things. Appreciation for being considerably accommodating and for finding this form of decent resources most people are really desperate to be aware of. Our own sincere apologies for not saying t ...
引用 游客 2018-3-1 12:33
A powerful share, I just given this onto a colleague who was doing a little bit evaluation on this. And he actually bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying more on this topic. If attainable, as you turn out to be experience, would you mind updating your weblog with extra details? It's highly useful for me. Huge thumb up ...

查看全部评论(53)


新出炉

返回顶部