我仅用50 行 JavaScript 代码从头构建区块链,向你介绍区块链的工作原理
点击上方 前端阳光,关注公众号
回复加群,加入技术交流群交流群

数据:这可以是交易数据之类的任何东西。
哈希值:这基本上是块的 ID。
前一个哈希值:这会跟踪前一个块 ID。现在,你只需要知道我们使用这个值在当前块和前一个块之间形成一个链。我将在本文后面解释为什么这个值很重要。
时间戳:这告诉我们区块何时被创建。
工作量证明:这是一个数字,显示了找到当前块的哈希值的努力。如果你听说过挖矿,这个值代表机器计算哈希值需要多长时间(以数字的形式)。








const hash = require("crypto-js/sha256");class Block {constructor(previousHash, data) {this.data = data;this.hash = this.calculateHash();this.previousHash = previousHash;this.timeStamp = new Date();this.proofOfWork = 0;}calculateHash() {return hash(this.previousHash +JSON.stringify(this.data) +this.timeStamp +this.proofOfWork).toString();}mine(difficulty) {while (!this.hash.startsWith("0".repeat(difficulty))) {this.proofOfWork++;this.hash = this.calculateHash();}}}class Blockchain {constructor() {let genesisBlock = new Block("0", { isGenesis: true });this.chain = [genesisBlock];}addBlock(data) {let lastBlock = this.chain[this.chain.length - 1];let newBlock = new Block(lastBlock.hash, data);newBlock.mine(2); // find a hash for new blockthis.chain.push(newBlock);}isValid() {for (let i = 1; i < this.chain.length; i++) {const currentBlock = this.chain[i];const previousBlock = this.chain[i - 1];if (currentBlock.hash != currentBlock.calculateHash()) return false;if (currentBlock.previousHash != previousBlock.hash) return false;}return true;}}
看,没有点击诱饵!它正好有 50 行
喜欢的话,请记得关注我,点赞我,非常感谢。
英文 | https://medium.com/geekculture/blockchain-explained-in-50-lines-of-code-1dbf4eda0201
翻译 | 杨小爱
我组建了技术交流群,里面有很多 大佬,欢迎进来交流、学习、共建。回复加群即可。
“分享、点赞、在看” 支持一波👍
评论
