當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
【JavaScript代码】使用JavaScript实现简单的区块链(签名+工作量证明机制)
生活随笔
收集整理的這篇文章主要介紹了
【JavaScript代码】使用JavaScript实现简单的区块链(签名+工作量证明机制)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
//區(qū)塊鏈 block chain
//data 之前區(qū)塊的哈希值 當(dāng)前區(qū)塊的哈希值:是由存儲(chǔ)在區(qū)塊里的信息算出來(lái)的(data + 之前區(qū)塊的哈希值)const sha256 = require('./crypto-js/sha256')//區(qū)塊
class Block{constructor(data){this.data = datathis.previousHash = ''this.nonce = 1this.hash = this.computeHash()}computeHash(){return sha256(this.data + this.previousHash + this.nonce).toString()}// 計(jì)算符合區(qū)塊鏈難度的hash值mine(difficulty){while(true){this.hash = this.computeHash()if(this.hash.substring(0, difficulty) !== this.getAnswer(difficulty)){this.nonce++}else{break}}}getAnswer(difficulty){// 開(kāi)頭前n位為0的hashlet answer = ''while(difficulty-- !== 0){answer += '0'}return answer}
}//區(qū)塊 的 鏈
//生成祖先區(qū)塊
class Chain{constructor(){this.chain = [this.bigBang()]this.difficulty = 4}bigBang(){const genesisBlock = new Block('祖先區(qū)塊')return genesisBlock}//獲取最新一個(gè)區(qū)塊getLatestBlock(){return this.chain[this.chain.length-1]}//添加新區(qū)塊addBlockToChain(newBlock){// 1、data 2、previousHashnewBlock.previousHash = this.getLatestBlock().hashnewBlock.hash = newBlock.computeHash()// 進(jìn)行挖礦newBlock.mine(this.difficulty)this.chain.push(newBlock)}//區(qū)塊鏈驗(yàn)證 當(dāng)前數(shù)據(jù)是否被篡改 當(dāng)前區(qū)塊的previousHash是否等于它的previous的hash值validateChain(){// 驗(yàn)證祖先區(qū)塊數(shù)據(jù)是否被篡改if(this.chain.length===1){if(this.chain[0].hash !== this.chain[0].computeHash()){return false}return true}// 驗(yàn)證其他區(qū)塊for(let i = 1, len = this.chain.length-1; i <= len; i++){const blockToValidate = this.chain[i]// 驗(yàn)證數(shù)據(jù)是否被篡改if(blockToValidate.hash !== blockToValidate.computeHash()){console.log("數(shù)據(jù)被篡改!")return false}// 驗(yàn)證hash值if(blockToValidate.previousHash !== this.chain[i-1].hash){console.log("前后區(qū)塊斷裂!")return false}}return true}}const zzBlock = new Block('轉(zhuǎn)賬1000')
const zzBlock2 = new Block('轉(zhuǎn)賬3210')
const zzBlock3 = new Block('轉(zhuǎn)賬210')
const blockChain = new Chain()
blockChain.addBlockToChain(zzBlock)
blockChain.addBlockToChain(zzBlock2)
blockChain.addBlockToChain(zzBlock3)
console.log(blockChain.chain.length)//嘗試篡改數(shù)據(jù)
blockChain.chain[1].data = '轉(zhuǎn)賬10W'
blockChain.chain[1].mine(4)
console.log(blockChain)
console.log(blockChain.validateChain())
總結(jié)
以上是生活随笔為你收集整理的【JavaScript代码】使用JavaScript实现简单的区块链(签名+工作量证明机制)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Java后台】Java执行Python
- 下一篇: 【SpringBoot集成Elastic