Javascript實現Proof-of-Work區塊鏈(教學二)

從[教學一]學會了區塊鏈的基本原理,知道區塊鏈是如何運作的。那這次在簡單的區塊鏈上作出一些修改,實現工作量証明系统 Proof-of-Work system(POW)。只要在計算Hash值時,在處理流程上加入「difficulty 難度」和「nonce 迭代次數」。

difficulty值作用是提高滿足條件的hash值的難度,在範例中「difficulty 難度」為4,即計算出來的hash值的前導必須為0000。

nonce值作用是一直迭代,直到hash值找到滿足defficulty所指定的前導0數量。找到nonce值來滿足條件的hash值的過程,稱之為挖礦。在範例中第1個Block的nonce值為1216,即nonce值經歷了1216次迭代才找到第1個Block。

隨著難度的增加,可能的有效散列數減少。找到較少可能的有效散列,需要更多的處理能力和時間才能找到有效的散列,這就是POW。

const SHA256 = require('crypto-js/sha256');

/*
 * 區塊
 */
class Block {
    constructor(index, timestamp, data, previousHash = '') {
        this.index = index;
        this.timestamp = timestamp;
        this.data = data;
        this.previousHash = previousHash;
        this.hash = this.calculateHash();
        this.nonce = 0;
    }

    /*
     * 計算區塊的hash
     */
    calculateHash() {
        return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();
    }

    mineBlock(difficulty) {
        while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")){
            this.nonce++;
            this.hash = this.calculateHash();
        }
        console.log("----" + this.nonce);
    }
}

/*
 * 區塊鏈
 */
class Blockchain {
    constructor() {
        this.chain = [this.createGenesisBlock()];
        this.difficulty = 4;
    }

    /*
     * 建立第一個區塊
     */
    createGenesisBlock() {
        return new Block(0, "2018-03-19", "Genesis block", "0");
    }

    /*
     * 取得最新的一個區塊
     */
    getLatestBlock() {
        return this.chain[this.chain.length - 1];
    }

    /*
     * 加入一個區塊
     */
    addBlock(newBlock) {
        newBlock.previousHash = this.getLatestBlock().hash;
        newBlock.mineBlock(this.difficulty);
        this.chain.push(newBlock);
    }
}

let testCoin = new Blockchain();

console.log('Mining block 1...');
testCoin.addBlock(new Block(1, "2018-03-19", { id: 1 }));

console.log('Mining block 2...');
testCoin.addBlock(new Block(2, "2018-03-20", { id: 2 }));

相關文章:

簡單Javascript製作區塊鏈(教學一)

Javascript實現區塊鏈挖礦獎勵和交易(教學三)

2 Replies to “Javascript實現Proof-of-Work區塊鏈(教學二)”

  1. Pingback: Javascript實現區塊鏈挖礦獎勵和交易(教學三) | Alvin's Blog 部落格

  2. Pingback: 簡單Javascript製作區塊鏈(教學一) | Alvin's Blog 部落格

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

驗證碼 * Time limit is exhausted. Please reload CAPTCHA.

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料