200行代码实现区块链

原文 A blockchain in 200 lines of code
译者:若愚,来自饥人谷, 更多好文,关注饥人谷公众号

区块链的基本概念非常简单:一个分布式数据库维持不断增长的有序记录列表。然而当我们谈论区块链时,我们也会谈论我们用区块链所要解决的问题,这二者通常很容易弄混淆。流行的基于区块链的项目如比特币以太坊就是这种情况 。术语“区块链”通常与交易智能合约加密货币等概念紧密相关。

这使得理解区块链是一项必然要艰巨的任务。特别是源码级别的理解。在这里,我将介绍一个使用200行代码实现的超级简单的区块链——NaiveChain

块结构

第一个逻辑步骤是确定块结构。为了让事情尽可能简单,我们只包含最必要的:索引(index),时间戳(timestamp),数据(data),哈希(hash)和上一个哈希(previousHash)。

当前块中必须找到上一个块的散列以保持链的完整性

class Block {
    constructor(index, previousHash, timestamp, data, hash) {
        this.index = index;
        this.previousHash = previousHash.toString();
        this.timestamp = timestamp;
        this.data = data;
        this.hash = hash.toString();
    }
}

块哈希

该块需要被哈希运算以保持数据的完整性。SHA-256被用来做哈希算法处理块的内容。需要注意的是这个哈希与“挖矿” 无关,因为没有解决工作量证明(Proof Of Work )的问题。

var calculateHash = (index, previousHash, timestamp, data) => {
    return CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
};

创建块

要创建一个块,我们必须知道上一个块的哈希,并创建剩余的所需内容(=索引,哈希,数据和时间戳)。块数据是由终端用户提供。

var generateNextBlock = (blockData) => {
    var previousBlock = getLatestBlock();
    var nextIndex = previousBlock.index + 1;
    var nextTimestamp = new Date().getTime() / 1000;
    var nextHash = calculateHash(nextIndex, previousBlock.hash, nextTimestamp, blockData);
    return new Block(nextIndex, previousBlock.hash, nextTimestamp, blockData, nextHash);
};

存储块

内存中的Javascript数组用于存储区块链。区块链的第一个区块也叫“创世纪块(译者著:genesis-block,区块链中的第一个块)”,它是直接写死的。

var getGenesisBlock = () => {
    return new Block(0, "0", 1465154705, "my genesis block!!", "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7");
};

var blockchain = [getGenesisBlock()];

验证块的完整性

在任何时候,我们必须能够验证块或区块链的完整性。特别是当我们从其他节点接收到新块时,并且必须决定是否接受它们。

var isValidNewBlock = (newBlock, previousBlock) => {
    if (previousBlock.index + 1 !== newBlock.index) {
        console.log('invalid index');
        return false;
    } else if (previousBlock.hash !== newBlock.previousHash) {
        console.log('invalid previoushash');
        return false;
    } else if (calculateHashForBlock(newBlock) !== newBlock.hash) {
        console.log('invalid hash: ' + calculateHashForBlock(newBlock) + ' ' + newBlock.hash);
        return false;
    }
    return true;
};

选择最长的链

任意时间,链中应始终只有一组块。如果发生冲突(例如下图中两个节点都生成id 为72的块),我们选择具有最长块数的链。

var replaceChain = (newBlocks) => {
    if (isValidChain(newBlocks) && newBlocks.length > blockchain.length) {
        console.log('Received blockchain is valid. Replacing current blockchain with received blockchain');
        blockchain = newBlocks;
        broadcast(responseLatestMsg());
    } else {
        console.log('Received blockchain invalid');
    }
};

与其他节点通信

一个节点的最重要的职能是与其他节点共享和同步区块链。以下规则用来保持网络同步。

  • 当一个节点产生一个新块时,它将它广播到网络
  • 当一个节点连接到一个新的节点时,它将查询最新的块
  • 当一个节点遇到一个索引大于当前已知块的块时,它会将该块添加到当前链中,或者查询完整的区块链。

当节点遵守所描述的协议时的典型通信场景

我们暂未实现节点自动发现,必须手动添加对等点的位置(=URLs)。

控制节点

用户必须能够以某种方式控制节点。这是通过设置HTTP服务器完成的。

var initHttpServer = () => {
    var app = express();
    app.use(bodyParser.json());

    app.get('/blocks', (req, res) => res.send(JSON.stringify(blockchain)));
    app.post('/mineBlock', (req, res) => {
        var newBlock = generateNextBlock(req.body.data);
        addBlock(newBlock);
        broadcast(responseLatestMsg());
        console.log('block added: ' + JSON.stringify(newBlock));
        res.send();
    });
    app.get('/peers', (req, res) => {
        res.send(sockets.map(s => s._socket.remoteAddress + ':' + s._socket.remotePort));
    });
    app.post('/addPeer', (req, res) => {
        connectToPeers([req.body.peer]);
        res.send();
    });
    app.listen(http_port, () => console.log('Listening http on port: ' + http_port));
};

如上所示,用户能够通过以下方式与节点交互:

  • 列出所有的块
  • 用用户给出的内容创建一个新块
  • 列出或添加节点

控制节点最直接的方法是使用Curl:

#get all blocks from the node
curl http://localhost:3001/blocks

架构

值得注意的是,一个节点实际上暴露了两个Web服务器:一个用于控制节点(HTTP服务器),一个用于节点之间的点对点通信(Websocket HTTP服务器)。

NaiveChain的主要组件

结论

NaiveChain是为演示和学习目的而创建的。因为它不具有“挖矿”算法(PoS 或者 PoW),不能在公共网络中使用。尽管如此,它仍然实现了功能区块链的基本功能。

可以在这里查看源码以获取更多技术细节。

如果您想更多地了解区块链,我建议你看看Naivecoin: a tutorial for building a cryptocurrency系列教程。在这个教程里,我们将详细讨论更多概念,如采矿(PoW,工作量证明)、交易和钱包。

147 thoughts on “200行代码实现区块链”

  1. My wife and i felt quite excited when Emmanuel managed to deal with his reports while using the ideas he was given in your web site. It is now and again perplexing just to choose to be releasing information and facts that the rest may have been selling. We really recognize we now have the writer to be grateful to because of that. All of the explanations you’ve made, the easy blog menu, the relationships you will give support to promote – it’s everything powerful, and it is helping our son in addition to our family understand this concept is amusing, which is rather indispensable. Thanks for all!

  2. I have to get across my appreciation for your kindness in support of those people that actually need assistance with this important content. Your very own dedication to passing the solution around had become astonishingly practical and have in most cases allowed people like me to arrive at their dreams. Your entire interesting help and advice indicates a whole lot a person like me and substantially more to my office colleagues. Thank you; from each one of us.

  3. I together with my buddies were found to be taking note of the best recommendations from your site and immediately got a horrible suspicion I had not expressed respect to the web blog owner for those strategies. All of the women were absolutely excited to learn them and now have seriously been taking advantage of those things. I appreciate you for being really thoughtful as well as for having varieties of superb useful guides most people are really wanting to be aware of. Our own sincere regret for not expressing gratitude to sooner.

  4. I as well as my pals were checking the best recommendations on your web site and so quickly came up with a terrible suspicion I never thanked the web blog owner for them. Most of the guys happened to be certainly very interested to read through all of them and have in reality been tapping into these things. Many thanks for simply being really accommodating and then for having varieties of outstanding subjects millions of individuals are really desirous to know about. My personal honest apologies for not saying thanks to sooner.

  5. It抯 arduous to search out knowledgeable people on this matter, but you sound like you understand what you抮e talking about! Thanks

  6. Pingback: nike vapormax
  7. Pingback: jordan shoes
  8. Can I just say what a relief to search out someone who really is aware of what theyre talking about on the internet. You positively know how you can bring an issue to light and make it important. More folks must read this and understand this side of the story. I cant consider youre not more widespread because you undoubtedly have the gift.

  9. Hiya! I just want to give a huge thumbs up for the great data you could have here on this post. I shall be coming again to your weblog for extra soon.

  10. I simply wished to thank you so much yet again. I’m not certain the things I would have carried out in the absence of the actual smart ideas discussed by you over that field. Completely was the distressing condition for me, but taking a look at a professional approach you handled that forced me to cry with delight. I will be happy for the information and even pray you realize what an amazing job you’re doing educating other individuals thru your blog. I know that you haven’t got to know all of us.

  11. Pingback: golden goose
  12. Pingback: bape hoodie
  13. Pingback: golden goose
  14. Good post. I learn one thing tougher on totally different blogs everyday. It should all the time be stimulating to read content material from other writers and practice a little one thing from their store. I抎 prefer to use some with the content material on my weblog whether or not you don抰 mind. Natually I抣l offer you a hyperlink in your web blog. Thanks for sharing.

  15. Pingback: golden goose
  16. Pingback: supreme new york
  17. Pingback: supreme hoodie
  18. I抎 need to examine with you here. Which isn’t something I often do! I take pleasure in studying a publish that may make people think. Also, thanks for permitting me to comment!

  19. Pingback: yeezy shoes
  20. Pingback: louboutins
  21. Pingback: yeezy shoes
  22. I want to express some thanks to the writer just for bailing me out of this particular setting. Just after exploring throughout the world wide web and seeing tricks that were not beneficial, I thought my life was over. Existing without the presence of answers to the problems you’ve fixed by way of your site is a critical case, as well as those which may have in a wrong way affected my career if I hadn’t discovered your web blog. Your own personal knowledge and kindness in maneuvering all things was priceless. I’m not sure what I would have done if I hadn’t encountered such a stuff like this. I can at this point look ahead to my future. Thanks a lot so much for the specialized and results-oriented guide. I won’t be reluctant to propose your web site to anyone who would need guidance about this area.

  23. Pingback: kobe sneakers
  24. Pingback: paul george shoes
  25. Pingback: kyrie 6
  26. Pingback: birkin bag
  27. Pingback: hermes birkin
  28. Pingback: jordan shoes
  29. Pingback: nike x off white
  30. I simply wanted to post a small remark to be able to say thanks to you for some of the lovely techniques you are giving at this website. My considerable internet look up has at the end of the day been compensated with good quality ideas to go over with my close friends. I would claim that we site visitors actually are definitely blessed to live in a fine community with many brilliant professionals with insightful solutions. I feel pretty lucky to have discovered your site and look forward to really more fabulous minutes reading here. Thank you once again for a lot of things.

  31. Pingback: curry shoes
  32. Pingback: supreme hoodie
  33. I precisely wished to thank you so much yet again. I’m not certain what I might have undertaken in the absence of the actual smart ideas shown by you relating to this situation. It previously was a scary setting for me personally, nevertheless encountering the very expert strategy you treated that forced me to jump over delight. I will be grateful for the advice as well as pray you know what a powerful job that you’re accomplishing educating others thru a web site. I am certain you have never got to know all of us.

  34. Pingback: nike air max
  35. Pingback: birkin bag
  36. Pingback: mbt
  37. Pingback: vans outlet
  38. Thanks for all of the efforts on this web site. Debby takes pleasure in engaging in investigations and it’s easy to see why. I notice all about the dynamic manner you make very useful suggestions via your website and recommend response from other people on that content then our simple princess is without a doubt discovering a lot of things. Take advantage of the remaining portion of the new year. You are always performing a splendid job.

  39. Pingback: adidas gazelle
  40. Pingback: supreme clothing
  41. Pingback: supreme clothing
  42. Pingback: kate spade outlet
  43. I intended to put you one tiny observation in order to give thanks once again considering the lovely views you’ve shown above. This is quite pretty open-handed of people like you to supply freely exactly what numerous people could have offered for sale as an e book in making some dough for their own end, particularly now that you could possibly have tried it if you ever desired. Those tactics as well acted to become a easy way to realize that someone else have a similar fervor just as my very own to grasp a whole lot more with regard to this issue. Certainly there are lots of more pleasurable moments ahead for many who take a look at your blog.

  44. Pingback: timberland outlet
  45. Pingback: moncler jackets
  46. Pingback: supreme clothing
  47. My husband and i felt absolutely contented that Jordan managed to round up his investigations while using the precious recommendations he gained from your own blog. It is now and again perplexing to simply choose to be making a gift of helpful hints which many people might have been trying to sell. And we understand we’ve got you to be grateful to because of that. The most important explanations you’ve made, the easy site navigation, the relationships you help to create – it’s got all sensational, and it is assisting our son in addition to our family imagine that that subject is fun, which is rather vital. Thank you for all!

  48. Pingback: ferragamo belts
  49. Pingback: yeezy shoes
  50. Pingback: fila shoes
  51. Pingback: timberland outlet
  52. Pingback: vapormax
  53. Pingback: off white
  54. Pingback: jordan shoes
  55. Pingback: kd shoes
  56. Pingback: lebron 17 shoes
  57. I precisely had to thank you very much once more. I do not know the things that I would’ve achieved without the actual advice shown by you concerning that concern. It absolutely was the horrifying matter in my opinion, however , being able to see a new skilled form you processed the issue took me to jump with joy. I will be happy for this information and then hope you are aware of a great job that you are putting in educating the rest by way of your web site. More than likely you haven’t met any of us.

  58. Pingback: supreme shirts
  59. Pingback: kyrie shoes
  60. I precisely needed to thank you very much yet again. I’m not certain the things that I could possibly have achieved in the absence of the actual basics provided by you relating to such subject matter. Completely was a horrifying matter in my opinion, nevertheless observing the very specialised technique you handled it made me to weep with joy. I am just happy for this help and thus sincerely hope you find out what a powerful job your are doing educating some other people through the use of your webblog. Most probably you have never encountered any of us.

  61. Pingback: retro jordans
  62. Pingback: nike air max 270
  63. Pingback: jordan 6
  64. I precisely wished to thank you so much once more. I am not sure the things I would’ve carried out without these techniques contributed by you regarding that subject. Previously it was a very alarming crisis for me, however , looking at a skilled technique you resolved that took me to weep for gladness. Now i am grateful for this help and as well , hope that you find out what an amazing job you were accomplishing teaching men and women thru a blog. Most probably you haven’t encountered any of us.

  65. Pingback: hermes belt
  66. Pingback: ultra boost
  67. Pingback: ferragamo belt
  68. I must express my appreciation to the writer for rescuing me from this predicament. As a result of researching through the internet and obtaining solutions which were not productive, I thought my entire life was well over. Living without the answers to the difficulties you have sorted out all through your report is a critical case, as well as ones that would have in a negative way damaged my career if I had not discovered your website. Your ability and kindness in maneuvering every item was tremendous. I’m not sure what I would’ve done if I had not come upon such a point like this. I can also at this time relish my future. Thanks so much for your specialized and amazing guide. I won’t think twice to endorse the sites to anyone who requires guide about this subject matter.

  69. Pingback: kd shoes
  70. I wanted to put you a little bit of word to be able to say thanks a lot yet again regarding the marvelous information you have documented in this article. It’s simply wonderfully generous of people like you giving openly what exactly some people could possibly have offered for an electronic book to earn some bucks on their own, chiefly given that you might have tried it in case you wanted. These secrets in addition worked like a easy way to know that many people have the identical keenness really like mine to see a whole lot more concerning this condition. I am certain there are millions of more enjoyable situations in the future for many who start reading your website.

  71. Pingback: hermes
  72. Pingback: cheap jordans
  73. Pingback: adidas nmd r1
  74. I am glad for writing to make you understand what a beneficial experience my cousin’s daughter undergone checking your blog. She figured out plenty of pieces, not to mention what it’s like to possess a very effective helping heart to make other individuals without hassle thoroughly grasp specified very confusing topics. You truly surpassed our own expectations. Thank you for giving such warm and friendly, safe, explanatory and as well as easy tips on this topic to Jane.

  75. Pingback: canada goose
  76. Pingback: nike shox for men
  77. Pingback: balenciaga
  78. Pingback: golden goose
  79. I intended to write you one very small remark to help say thanks over again regarding the awesome opinions you have provided on this website. This has been extremely generous of you to make publicly exactly what many individuals would have offered for sale for an e-book to earn some cash for themselves, most importantly considering that you could have tried it in the event you considered necessary. The techniques also worked like a easy way to be aware that most people have a similar passion similar to mine to figure out significantly more related to this problem. I’m sure there are thousands of more fun opportunities in the future for those who scan your blog.

  80. Pingback: supreme
  81. Pingback: converse
  82. Pingback: goyard bags
  83. Pingback: yeezy shoes
  84. Pingback: supreme clothing
  85. Pingback: yeezy supply
  86. Pingback: hermes belts
  87. Pingback: longchamp handbags
  88. Pingback: adidas superstar
  89. Pingback: adidas flux
  90. Pingback: jordan shoes
  91. Pingback: yeezy boost
  92. Pingback: jordan retro
  93. Pingback: off white jordan 1
  94. Pingback: goyard handbags
  95. Pingback: westbrook shoes
  96. Pingback: curry 5 shoes
  97. Pingback: yeezy boost
  98. Pingback: ralph lauren uk
  99. Pingback: jordan shoes
  100. Pingback: air max 2017
  101. Pingback: curry 4 shoes
  102. Thanks for your own hard work on this website. Debby take interest in managing internet research and it’s really obvious why. A lot of people know all regarding the lively method you create both interesting and useful ideas via the web blog and as well welcome participation from other people on the point plus our own child is certainly understanding a lot of things. Take advantage of the remaining portion of the year. You are always conducting a great job.

  103. Pingback: nike air max
  104. Pingback: vapormax
  105. Pingback: yeezy supply
  106. Pingback: curry shoes
  107. I simply wanted to write a small word so as to thank you for some of the fabulous information you are writing at this site. My long internet look up has at the end of the day been rewarded with good quality suggestions to talk about with my great friends. I would declare that many of us website visitors are unquestionably lucky to dwell in a useful community with many brilliant professionals with useful tips and hints. I feel rather lucky to have used your entire site and look forward to so many more brilliant times reading here. Thanks once more for a lot of things.

  108. Pingback: air max 95
  109. Pingback: supreme outlet
  110. Pingback: goyard bags
  111. Pingback: nike air max
  112. Pingback: kyrie 5
  113. I want to express appreciation to you just for bailing me out of this type of incident. Because of looking throughout the online world and getting tricks which are not helpful, I believed my entire life was well over. Existing without the strategies to the problems you have sorted out as a result of your entire posting is a crucial case, as well as ones that could have adversely affected my career if I hadn’t encountered the website. Your knowledge and kindness in controlling a lot of stuff was very useful. I am not sure what I would’ve done if I had not come across such a step like this. I am able to at this moment relish my future. Thanks so much for the professional and effective guide. I won’t be reluctant to endorse your web site to anyone who needs and wants guidance about this subject.

  114. Pingback: off white jordan 1
  115. Pingback: yeezy shoes
  116. Pingback: jordan 4
  117. Pingback: irving shoes
  118. Pingback: air jordan
  119. Pingback: air jordan
  120. I’m just commenting to let you understand of the really good experience my friend’s girl undergone viewing your web site. She came to find a lot of things, not to mention how it is like to possess a great coaching mindset to get other individuals smoothly know precisely a variety of specialized things. You undoubtedly surpassed people’s desires. Many thanks for delivering those beneficial, healthy, revealing and even cool tips on this topic to Julie.

  121. Pingback: psyhelp_on_line
  122. I precisely wanted to appreciate you once more. I’m not certain the things I might have carried out without the advice discussed by you directly on this situation. It was before an absolute hard circumstance for me, but discovering this expert way you resolved it took me to leap with happiness. I’m grateful for this advice and trust you are aware of an amazing job you’re undertaking training the rest through the use of your web site. Most probably you have never come across any of us.

  123. Pingback: coronavirus
  124. Pingback: PSYCHOSOCIAL
  125. Thanks for all of the hard work on this web page. My mother really likes participating in research and it’s really obvious why. Almost all know all of the compelling form you convey simple secrets via the web site and therefore attract response from others about this article plus my simple princess is being taught a whole lot. Take pleasure in the rest of the year. You are conducting a fabulous job.

  126. I in addition to my friends happened to be reviewing the excellent tips and hints from your web blog while instantly developed a horrible suspicion I never thanked you for those techniques. These people appeared to be for this reason warmed to study them and have now quite simply been using these things. Appreciation for turning out to be indeed thoughtful and for getting such wonderful resources millions of individuals are really desirous to discover. My personal honest regret for not expressing appreciation to you sooner.

发表评论

电子邮件地址不会被公开。