//區塊鏈 block chain
//data 之前區塊的哈希值 當前區塊的哈希值:是由存盤在區塊里的資訊算出來的(data + 之前區塊的哈希值)
const sha256 = require('./crypto-js/sha256')
//區塊
class Block{
constructor(data){
this.data = data
this.previousHash = ''
this.nonce = 1
this.hash = this.computeHash()
}
computeHash(){
return sha256(this.data + this.previousHash + this.nonce).toString()
}
// 計算符合區塊鏈難度的hash值
mine(difficulty){
while(true){
this.hash = this.computeHash()
if(this.hash.substring(0, difficulty) !== this.getAnswer(difficulty)){
this.nonce++
}else{
break
}
}
}
getAnswer(difficulty){
// 開頭前n位為0的hash
let answer = ''
while(difficulty-- !== 0){
answer += '0'
}
return answer
}
}
//區塊 的 鏈
//生成祖先區塊
class Chain{
constructor(){
this.chain = [this.bigBang()]
this.difficulty = 4
}
bigBang(){
const genesisBlock = new Block('祖先區塊')
return genesisBlock
}
//獲取最新一個區塊
getLatestBlock(){
return this.chain[this.chain.length-1]
}
//添加新區塊
addBlockToChain(newBlock){
// 1、data 2、previousHash
newBlock.previousHash = this.getLatestBlock().hash
newBlock.hash = newBlock.computeHash()
// 進行挖礦
newBlock.mine(this.difficulty)
this.chain.push(newBlock)
}
//區塊鏈驗證 當前資料是否被篡改 當前區塊的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, len = this.chain.length-1; i <= len; i++){
const blockToValidate = this.chain[i]
// 驗證資料是否被篡改
if(blockToValidate.hash !== blockToValidate.computeHash()){
console.log("資料被篡改!")
return false
}
// 驗證hash值
if(blockToValidate.previousHash !== this.chain[i-1].hash){
console.log("前后區塊斷裂!")
return false
}
}
return true
}
}
const zzBlock = new Block('轉賬1000')
const zzBlock2 = new Block('轉賬3210')
const zzBlock3 = new Block('轉賬210')
const blockChain = new Chain()
blockChain.addBlockToChain(zzBlock)
blockChain.addBlockToChain(zzBlock2)
blockChain.addBlockToChain(zzBlock3)
console.log(blockChain.chain.length)
//嘗試篡改資料
blockChain.chain[1].data = '轉賬10W'
blockChain.chain[1].mine(4)
console.log(blockChain)
console.log(blockChain.validateChain())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/291551.html
標籤:區塊鏈
上一篇:什么是區塊鏈存盤?
