安装依赖模块
npm install crypto-js
const sha256 = require('crypto-js/sha256')
class Block {
constructor (data, prevHash) {
this.data = data
this.prevHash = prevHash
this.hash = this.calHash()
}
calHash () {
return sha256(this.data+this.prevHash).toString()
}
}
class Chain {
constructor () {
this.chain = [this.firstBlock()]
console.log(this.chain)
}
firstBlock () {
const ancestorBlock = new Block('I am you', '')
return ancestorBlock
}
getLastBlock () {
return this.chain[this.chain.length - 1]
}
addBlock (newBlock) {
newBlock.prevHash = this.getLastBlock().hash
newBlock.hash = newBlock.calHash()
this.chain.push(newBlock)
}
validateBlock () {
if (this.chain.length === 1 && this.chain[0].hash !=&#