//data之前区块哈希
//自己哈希:自算(data + 之前区块哈希)
const sha256=require('crypto-js/sha256')
class Block{
constructor(data,previousHash){
this.data=data
this.previousHash=previousHash
this.hash=this.computerHash()
}
//返回自己计算的哈希值
computerHash(){
return sha256(this.data+this.previousHash).toString()}
}
//const block = new Block('','123')
//console.log(block)
![](https://i-blog.csdnimg.cn/blog_migrate/9457983d75a1f155e2dde4ed8e2b4fd4.png)
//链
class Chain{
constructor(){
this.chain =[this.bigBang()]
}
//创世区块
bigBang(){
const genesisBlock = new Block('I an genesisBlock','')
return genesisBlock}
//找到最近一个block的哈希
getLatestBlock(){
return this.chain[this.chain.length-1]}
//添加区块到区块链上
addBlockToChain(block){
//找到最近一个block的哈希
newBlock.previousHash = this.getLatestBlock().hash
newBlock.hash = newBlock.computeHash();
this.chain.push(newBlock)}
}
//创建区块链
const luotuoChain = new Chain()
const block1=new Block('10','')
luotuoChain.addBlockToChain(block1)
console.log(luotuoChain)
//验证当前区块链是否合法,通过判断前一个区块的哈希值
//通过计算每个区块的哈希值对比验证当前区块的真实性
//验证当前区块的previousHash != previous区块的hash
validateChain(){
if (this.chain.length===1){
if(this.chain[0].hash !== this.chain[0].computeHash() ){
return false
}
return true
}
for(let i = 1;i <= this.chain.length-1;i++){
//拿到第二个块往后检查
const blockToValidate = this.chain[i]
if(blockToValidate.hash !== blockToValidate.computeHash()){
console.log("Error!篡改")
return false
}
const previousBlock = this.chain[i-1]
if(blockToValidate.previousHash !== previousBlock.hash) {
console.log("Error!断链")
return false
}
}
}
//创建区块链
const luotuoChain = new Chain()
const block1=new Block('10','')
luotuoChain.addBlockToChain(block1)
console.log(luotuoChain)
console.log(luotuoChain.validateChain())
//篡改区块
luotuoChain.chain[1].data = "100000"
console.log(luotuoChain.validateChain())
luotuoChain.chain[1].hash=luotuoChain.chain[1].computeHash()
![](https://i-blog.csdnimg.cn/blog_migrate/8a6e0bbde3c047ea123991177381ac05.png)
![](https://i-blog.csdnimg.cn/blog_migrate/ec295c06cb19b4c8c142fd5b73cc5877.png)
经供参考!