200行代码实现blockchain 区块链实例详解


Posted in Javascript onMarch 14, 2018

了解blockchain的概念很简单(区块链,交易链块):它是分布式的(即不是放置在同一台机器上,不同的网络设备上的)数据库支持主办记录日益增长的名单。但是,这也是容易混淆blockchain与我们试图帮他解决了目标 - 在人们心中的那一刻,这个词是相当强烈的交易,合同或智能cryptocurrency的概念有关。

只有在这里blockchain - 是不是一回事比特币,并理解链块的基本知识比它似乎更容易,尤其是在,它是基于源代码的情况下。在本文中,我们提出了建立与在JavaScript中200行代码的简单模型。这个项目,我们称之为NaiveChain的源代码,可以在GitHub上找到。第1部分和第2部分:如果您需要刷上它的功能,使用我们的备忘单,我们将使用标准的ECMAScript 6。
块结构

第一步 - 确定应包含块的元素。为简单起见,我们只包括最必要的:先前块的指数(指数),时间标记(时间戳),数据(数据),散列和散列,要录制,以保持电路的结构完整性。

200行代码实现blockchain 区块链实例详解

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。这种类型的散列是不相关的开采,因为在这种情况下,我们并没有用表现证明实施保护。

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); 
};

存储单元

使用blockchain 存储阵列。第一个块总是硬编码“创世纪块”。

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(typeof (newBlock.hash) + ' ' + typeof calculateHashForBlock(newBlock)); 
    console.log('invalid hash: ' + calculateHashForBlock(newBlock) + ' ' + newBlock.hash); 
    return false; 
  } 
  return true; 
};

选择链最长的

在电路块的顺序必须被明确指定,但是在发生冲突的情况下(例如,两个节点同时在同一生成的块和相同数量),我们选择电路,其中包含的块的数量较多。

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'); 
  } 
};

消息到其它网络节点

该网站的一个组成部分 - 与其他节点的数据交换。下列规则用于维护网络同步:
当一个节点产生新的单元,它会报告给网络;
当本机连接到新的盛宴,他要求有关最后生成的块信息;
当一个节点正面临着一个块,其中有一个指标比他还大,他增加了一个块到电路或请求的完整链条的信息。
自动搜索同龄人不执行,所有环节都手动添加。

单元的控制

用户应该能够以某种方式控制节点,通过将HTTP服务器解决。当与节点相互作用有以下功能:
打印所有单元的列表;
创建用户生成内容的新单元;
打印列表,或添加的节日。
互动的最直接的方式 - 通过卷曲:

200行代码实现blockchain 区块链实例详解

一个节点上的所有块#名单

curl http://localhost:3001/blocks

架构

值得注意的是,该网站是指两个Web服务器:HTTP进行用户控制的装置和向所述的WebSocket HTTP来安装节点之间的P2P连接。

如下为js 200行代码

<span style="font-family:Arial, Helvetica, sans-serif;">'use strict';</span> 
var CryptoJS = require("crypto-js"); 
var express = require("express"); 
var bodyParser = require('body-parser'); 
var WebSocket = require("ws"); 
var http_port = process.env.HTTP_PORT || 3001; 
var p2p_port = process.env.P2P_PORT || 6001; 
var initialPeers = process.env.PEERS ? process.env.PEERS.split(',') : []; 
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(); 
  } 
} 
var sockets = []; 
var MessageType = { 
  QUERY_LATEST: 0, 
  QUERY_ALL: 1, 
  RESPONSE_BLOCKCHAIN: 2 
}; 
var getGenesisBlock = () => { 
  return new Block(0, "0", 1465154705, "my genesis block!!", "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7"); 
}; 
var blockchain = [getGenesisBlock()]; 
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)); 
}; 
var initP2PServer = () => { 
  var server = new WebSocket.Server({port: p2p_port}); 
  server.on('connection', ws => initConnection(ws)); 
  console.log('listening websocket p2p port on: ' + p2p_port); 
}; 
var initConnection = (ws) => { 
  sockets.push(ws); 
  initMessageHandler(ws); 
  initErrorHandler(ws); 
  write(ws, queryChainLengthMsg()); 
}; 
var initMessageHandler = (ws) => { 
  ws.on('message', (data) => { 
    var message = JSON.parse(data); 
    console.log('Received message' + JSON.stringify(message)); 
    switch (message.type) { 
      case MessageType.QUERY_LATEST: 
        write(ws, responseLatestMsg()); 
        break; 
      case MessageType.QUERY_ALL: 
        write(ws, responseChainMsg()); 
        break; 
      case MessageType.RESPONSE_BLOCKCHAIN: 
        handleBlockchainResponse(message); 
        break; 
    } 
  }); 
}; 
var initErrorHandler = (ws) => { 
  var closeConnection = (ws) => { 
    console.log('connection failed to peer: ' + ws.url); 
    sockets.splice(sockets.indexOf(ws), 1); 
  }; 
  ws.on('close', () => closeConnection(ws)); 
  ws.on('error', () => closeConnection(ws)); 
}; 
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); 
}; 
var calculateHashForBlock = (block) => { 
  return calculateHash(block.index, block.previousHash, block.timestamp, block.data); 
}; 
var calculateHash = (index, previousHash, timestamp, data) => { 
  return CryptoJS.SHA256(index + previousHash + timestamp + data).toString(); 
}; 
var addBlock = (newBlock) => { 
  if (isValidNewBlock(newBlock, getLatestBlock())) { 
    blockchain.push(newBlock); 
  } 
}; 
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(typeof (newBlock.hash) + ' ' + typeof calculateHashForBlock(newBlock)); 
    console.log('invalid hash: ' + calculateHashForBlock(newBlock) + ' ' + newBlock.hash); 
    return false; 
  } 
  return true; 
}; 
var connectToPeers = (newPeers) => { 
  newPeers.forEach((peer) => { 
    var ws = new WebSocket(peer); 
    ws.on('open', () => initConnection(ws)); 
    ws.on('error', () => { 
      console.log('connection failed') 
    }); 
  }); 
}; 
var handleBlockchainResponse = (message) => { 
  var receivedBlocks = JSON.parse(message.data).sort((b1, b2) => (b1.index - b2.index)); 
  var latestBlockReceived = receivedBlocks[receivedBlocks.length - 1]; 
  var latestBlockHeld = getLatestBlock(); 
  if (latestBlockReceived.index > latestBlockHeld.index) { 
    console.log('blockchain possibly behind. We got: ' + latestBlockHeld.index + ' Peer got: ' + latestBlockReceived.index); 
    if (latestBlockHeld.hash === latestBlockReceived.previousHash) { 
      console.log("We can append the received block to our chain"); 
      blockchain.push(latestBlockReceived); 
      broadcast(responseLatestMsg()); 
    } else if (receivedBlocks.length === 1) { 
      console.log("We have to query the chain from our peer"); 
      broadcast(queryAllMsg()); 
    } else { 
      console.log("Received blockchain is longer than current blockchain"); 
      replaceChain(receivedBlocks); 
    } 
  } else { 
    console.log('received blockchain is not longer than received blockchain. Do nothing'); 
  } 
}; 
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'); 
  } 
}; 
var isValidChain = (blockchainToValidate) => { 
  if (JSON.stringify(blockchainToValidate[0]) !== JSON.stringify(getGenesisBlock())) { 
    return false; 
  } 
  var tempBlocks = [blockchainToValidate[0]]; 
  for (var i = 1; i < blockchainToValidate.length; i++) { 
    if (isValidNewBlock(blockchainToValidate[i], tempBlocks[i - 1])) { 
      tempBlocks.push(blockchainToValidate[i]); 
    } else { 
      return false; 
    } 
  } 
  return true; 
}; 
var getLatestBlock = () => blockchain[blockchain.length - 1]; 
var queryChainLengthMsg = () => ({'type': MessageType.QUERY_LATEST}); 
var queryAllMsg = () => ({'type': MessageType.QUERY_ALL}); 
var responseChainMsg = () =>({ 
  'type': MessageType.RESPONSE_BLOCKCHAIN, 'data': JSON.stringify(blockchain) 
}); 
var responseLatestMsg = () => ({ 
  'type': MessageType.RESPONSE_BLOCKCHAIN, 
  'data': JSON.stringify([getLatestBlock()]) 
}); 
var write = (ws, message) => ws.send(JSON.stringify(message)); 
var broadcast = (message) => sockets.forEach(socket => write(socket, message)); 
connectToPeers(initialPeers); 
initHttpServer(); 
initP2PServer();

总结

以上所述是小编给大家介绍的200行代码实现blockchain 区块链实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
JavaScript高级程序设计 阅读笔记(十四) js继承机制的实现
Aug 14 Javascript
基于ajax实现文件上传并显示进度条
Aug 03 Javascript
jquery常用函数与方法汇总
Sep 01 Javascript
js实现弹窗居中的简单实例
Oct 09 Javascript
ionic进入多级目录后隐藏底部导航栏(tabs)的完美解决方案
Nov 23 Javascript
Vue2.0用 watch 观察 prop 变化(不触发)
Sep 08 Javascript
Java设计中的Builder模式的介绍
Mar 22 Javascript
利用Angular2的Observables实现交互控制的方法
Dec 27 Javascript
js实现无限层级树形数据结构(创新算法)
Feb 27 Javascript
谈谈我在vue-cli3中用预渲染遇到的坑
Apr 22 Javascript
vue实现防抖的实例代码
Jan 11 Vue.js
详解TS数字分隔符和更严格的类属性检查
May 06 Javascript
vue使用iframe嵌入网页的示例代码
Jun 09 #Javascript
JavaScript实现区块链
Mar 14 #Javascript
iview table render集成switch开关的实例
Mar 14 #Javascript
解决Vue.js 2.0 有时双向绑定img src属性失败的问题
Mar 14 #Javascript
Vue.js 动态为img的src赋值方法
Mar 14 #Javascript
基于datepicker定义自己的angular时间组件的示例
Mar 14 #Javascript
vue 过滤器filter实例详解
Mar 14 #Javascript
You might like
《PHP边学边教》(01.开篇――准备工作)
2006/12/13 PHP
PHP错误提示的关闭方法详解
2013/06/23 PHP
php 获取页面中指定内容的实现类
2014/01/23 PHP
修改WordPress中文章编辑器的样式的方法详解
2015/12/15 PHP
php中Redis的应用--消息传递
2017/03/28 PHP
PHP示例演示发送邮件给某个邮箱
2019/04/03 PHP
js一般方法改写成面向对象方法的无限级折叠菜单示例代码
2013/07/04 Javascript
div模拟选择框示例代码
2013/11/03 Javascript
JQuery伸缩导航练习示例
2013/11/13 Javascript
js中settimeout方法加参数的使用实例
2014/02/27 Javascript
js拼接html注意问题示例探讨
2014/07/14 Javascript
jQuery实现页面顶部显示的进度条效果完整实例
2015/12/09 Javascript
D3.js实现直方图的方法详解
2016/09/25 Javascript
Bootstrap风格的WPF样式
2016/12/07 Javascript
vue+element实现批量删除功能的示例
2018/02/28 Javascript
vue2.0 获取从http接口中获取数据,组件开发,路由配置方式
2019/11/04 Javascript
Element Rate 评分的使用方法
2020/07/27 Javascript
JS如何实现在弹出窗口中加载页面
2020/12/03 Javascript
python实现sublime3的less编译插件示例
2014/04/27 Python
利用Pycharm断点调试Python程序的方法
2018/11/29 Python
Python求一批字符串的最长公共前缀算法示例
2019/03/02 Python
pyinstaller将含有多个py文件的python程序做成exe
2020/04/29 Python
基于python和flask实现http接口过程解析
2020/06/15 Python
Windows下PyCharm配置Anaconda环境(超详细教程)
2020/07/31 Python
HTML5中使用postMessage实现两个网页间传递数据
2016/06/22 HTML / CSS
北美大型运动类产品商城:Champs Sports
2017/01/12 全球购物
请用用Java代码写一个堆栈
2012/01/26 面试题
护士实习生自我鉴定范文
2013/12/10 职场文书
优秀小学生事迹材料
2014/12/26 职场文书
优胜劣汰,强者为王——读《鲁滨逊漂流记》有感
2019/08/15 职场文书
创业计划书之甜品店
2019/09/18 职场文书
Css预编语言及区别详解
2021/04/25 HTML / CSS
一文带你探究MySQL中的NULL
2021/11/11 MySQL
【js设计模式】SOLID五大设计原则
2022/03/24 Javascript
PC版《死亡搁浅导剪版》现已发售 展开全新的探险
2022/04/03 其他游戏
vue3种table表格选项个数的控制方法
2022/04/14 Vue.js