黑基网 首页 学院 编程开发 查看内容

只用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-2-21 11:28
When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any method you'll be able to remove me from that service? Thanks!
jordan 4 http://www.jordan4.us.com
引用 游客 2018-2-20 11:43
Good day! I simply want to give a huge thumbs up for the good data you could have here on this post. I can be coming back to your blog for extra soon.
adidas outlet http://www.adidasoutletonline.com
引用 游客 2018-2-20 04:29
I not to mention my friends were found to be reading the good information from your website and then quickly I got an awful feeling I never expressed respect to the web site owner for them. Those boys came totally stimulated to read through all of them and have in effect pretty much been enjoying these things. We appreciate you being very kind and then for picking variety of high-quality themes most people are really needing to know about. Our own sincere apologies for not expressing appreciatio ...
引用 游客 2018-2-20 03:56
There is noticeably a bundle to know about this. I assume you made certain nice factors in options also.
Adidas NMD XR1 Camouflage Main Blue http://www.adidas-nmds.us.com/adidas-nmd-xr1-camouflage-main-blue-p-510.html
引用 游客 2018-2-19 11:06
When I initially commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there any method you may remove me from that service? Thanks!
golden goose sneakers http://www.goldengoose-snearkers.com
引用 游客 2018-2-18 10:51
This actually answered my problem, thanks!
cartier love bracelet http://www.cartierbracelet.us
引用 游客 2018-2-17 13:31
Spot on with this write-up, I truly assume this website wants much more consideration. I抣l in all probability be once more to read far more, thanks for that info.
cheap jordans http://www.authenticjordanscheap.us.com
引用 游客 2018-2-16 23:53
I simply needed to thank you very much once more. I do not know the things I could possibly have accomplished in the absence of the actual opinions documented by you regarding such concern. It was before a difficult case for me personally, but understanding your specialised way you handled that forced me to weep over delight. Extremely thankful for your work as well as wish you realize what an amazing job that you are carrying out training the rest by way of your webblog. More than likely you ha ...
引用 游客 2018-2-16 16:50
When I initially commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any way you possibly can take away me from that service? Thanks!
nike lebron 14 http://www.lebron14.us.com
引用 游客 2018-2-15 22:13
Spot on with this write-up, I really think this website needs rather more consideration. I抣l most likely be again to read rather more, thanks for that info.
true religion outlet http://www.truereligion-outlets.us.com
引用 游客 2018-2-15 13:35
I needed to put you one very small remark to help say thank you the moment again relating to the remarkable advice you have contributed here. It has been simply tremendously generous of you to deliver openly exactly what most of us could possibly have supplied as an electronic book in order to make some dough for their own end, principally since you might have tried it if you wanted. These principles additionally served like a great way to be sure that someone else have the same dream like my ow ...
引用 游客 2018-2-15 02:48
An impressive share, I simply given this onto a colleague who was doing somewhat evaluation on this. And he in reality bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying more on this topic. If potential, as you develop into expertise, would you thoughts updating your blog with extra details? It is extremely useful for me. Big  ...
引用 游客 2018-2-14 06:34
There's noticeably a bundle to know about this. I assume you made sure nice points in options also.
links of london http://www.linksoflondonus.com
引用 游客 2018-2-14 05:20
I intended to compose you one bit of remark to say thank you once again for the awesome ideas you have provided above. It was  incredibly generous with you to provide freely all that a lot of people could have offered for sale for an e book to end up ** some profit for themselves, notably seeing that you could possibly have done it in case you considered necessary. The principles in addition served to be the good way to be sure that most people have the identical passion the same as my own t ...
引用 游客 2018-2-13 08:34
The subsequent time I learn a blog, I hope that it doesnt disappoint me as much as this one. I mean, I do know it was my choice to read, but I truly thought youd have something attention-grabbing to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.
louboutin shoes uk http://www.louboutinshoes.uk
引用 游客 2018-2-12 17:54
Thank you for your whole efforts on this site. Ellie enjoys carrying out investigations and it's easy to understand why. We notice all of the compelling mode you deliver both useful and interesting tips and hints through the website and inspire response from some others on the concern so our own girl has been becoming educated a lot of things. Take advantage of the rest of the new year. Your performing a stunning job.
yeezy boost http://ux.nu/dQ6ki
引用 游客 2018-2-12 11:54
very nice put up, i actually love this web site, carry on it
cheap jordans http://www.retro-jordans.us.com
引用 游客 2018-2-11 18:17
Your home is valueble for me. Thanks!?
longchamps http://www.longchamp-bags.us.org
引用 游客 2018-2-11 12:14
I and also my friends ended up reading through the great pointers on your website then unexpectedly I got a terrible suspicion I never thanked you for those secrets. Most of the women are actually absolutely passionate to read all of them and now have undoubtedly been having fun with them. Many thanks for simply being well considerate and for utilizing such notable areas millions of individuals are really desirous to understand about. My honest regret for not expressing appreciation to  sooner.
...
引用 游客 2018-2-10 20:18
Can I simply say what a relief to find somebody who truly knows what theyre speaking about on the internet. You positively know easy methods to carry a problem to gentle and make it important. Extra individuals have to learn this and perceive this side of the story. I cant believe youre not more in style because you positively have the gift.
supreme clothing http://www.supremeclothing.us

查看全部评论(23)


新出炉

返回顶部