天天看點

Node實作簡易區塊鍊,助你了解區塊鍊運作原理

前言

正式了解比特币是在17年的時候,在那個閉着眼睛都能賺到錢的年代,我也跟絕大多數人一樣,進入了這場聲勢浩大的"賭博"。

“賭博”過程中讓我對區塊鍊産生了興趣,我很好奇,他們經常提到的挖礦是什麼?挖礦為啥就費電,費CPU?

所謂的挖礦

後來查資料才了解到,挖礦就是不斷的計算,并且是毫無道理的“瞎算”,隻要達到一個很“傻”的條件就表示你挖礦成功。

Node實作簡單的挖礦

const crypto = require('crypto');
//創世區塊 這是第一次挖礦生成的資料
const initBlock ={ 
    index: 0,
    nonce: 1307,
    data: '我是創世區塊',
    prevHash: 0,
    timestamp: 1551248147024,
    hash:
     '00e275e4946f0fdf672be32fd4dfeaae0b7efd8d9f377c48ac510efe79d6a814' 
    };
class Blockchain{
    constructor(){
        this.blockchain = [
            initBlock //預設有一個創世區塊
        ];
        this.data= [];
        this.difficulty = 2; //難度
        
    }
    //挖礦
    min(){
        const index = this.blockchain.length; //索引.也就是現在區塊的長度
        let nonce = 0; //随機數
        const data = this.data;
        const prevHash= this.getLastChain();// 上一個區塊的hash值
        let timestamp = new Date().getTime(); //時間戳
        let hash = this.computeHash(index,prevHash,timestamp,data, nonce);
        //判斷得到的hash的前 幾位 是否為 0~
        while(hash.slice(0, this.difficulty) !== "0".repeat( this.difficulty ))
        {
            nonce+=1;
            hash = this.computeHash(index,prevHash,timestamp,data, nonce);
            console.log(`正在進行第${nonce}次挖礦:${hash}`);
        }
        this.blockchain.push({
            index,
            nonce,
            data,
            prevHash,
            timestamp,
            hash
        })
        console.log(this.blockchain);
            
    }   
    //擷取最後一個區塊的資料
    getLastChain(){
        return this.blockchain[this.blockchain.length-1].hash;
    }
    //計算哈希
    computeHash(index, prevHash, timestamp, data, nonce){
        return crypto
                .createHash('sha256')
                .update( index + prevHash + timestamp + data + nonce)
                .digest('hex');
    }
}
var chain = new Blockchain();
chain.min();           

運作效果如下:

Node實作簡易區塊鍊,助你了解區塊鍊運作原理

難度越大,所需要的計算能力也就越高,是以也就越費電,雖然這并沒有必然的聯系,不過,目前來說确實如此

阿裡雲優惠劵福利領取

繼續閱讀