iT邦幫忙

1

實作輕量級區塊鏈 (一):定義區塊與區塊鏈資料結構

  • 分享至 

  • xImage
  •  

經過前三天密碼學與共識機制的理論洗禮,今天我們終於要打開編輯器,正式進入寫 Code 的階段了。

為了讓大家能以最直覺的方式理解區塊鏈的底層運作,我選擇使用 JavaScript 來實作我的輕量級區塊鏈。今天我的目標很明確:定義出「區塊(Block)」以及「區塊鏈(Blockchain)」的基本資料結構。

定義區塊 (Block) 的結構
一個區塊就像是一個封裝好的包裹,裡面裝載著各種重要的屬性。在 JavaScript 中,我們可以利用 class 來定義這個資料結構。
為了計算 Hash 值,我們需要先安裝並引入 crypto-js 套件。
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();
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
在這裡你可以看到,我們將前幾天學到的 Hash 觀念具體實作了出來。只要 data 甚至 timestamp 有一絲絲改變,calculateHash() 算出來的結果就會截然不同。

定義區塊鏈 (Blockchain) 的結構
單一區塊是沒有意義的,我們需要一個管理這些區塊的類別,也就是區塊鏈本身。它本質上就是一個陣列(Array),並加上了一些維護這個陣列安全性的方法。
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}

createGenesisBlock() {
    return new Block(0, "2026-09-21", "這是創世區塊", "0");
}
getLatestBlock() {
    return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
    this.chain.push(newBlock);
}
isChainValid() {
    for (let i = 1; i < this.chain.length; i++) {
        const currentBlock = this.chain[i];
        const previousBlock = this.chain[i - 1];
        if (currentBlock.hash !== currentBlock.calculateHash()) {
            console.log(`區塊 ${i} 的資料遭篡改!`);
            return false;
        }
        if (currentBlock.previousHash !== previousBlock.hash) {
            console.log(`區塊 ${i} 與前一個區塊的鏈結斷裂!`);
            return false;
        }
    }
    return true;
}

}
測試我們的輕量級區塊鏈
程式碼寫完了,讓我們來實際跑跑看,驗證資料的不可篡改性:
let myIoTChain = new Blockchain();

console.log("正在打包區塊 1...");
myIoTChain.addBlock(new Block(1, "2026-09-22", { temperature: 25, humidity: 60 }));

console.log("正在打包區塊 2...");
myIoTChain.addBlock(new Block(2, "2026-09-23", { temperature: 26, humidity: 65 }));

// 檢查目前區塊鏈是否有效? (預期:true)
console.log("區塊鏈是否有效?", myIoTChain.isChainValid());

// 模擬駭客攻擊:試圖修改區塊 1 的感測資料
console.log("--- 駭客試圖竄改感測資料 ---");
myIoTChain.chain[1].data = { temperature: 100, humidity: 10 };

// 再次檢查區塊鏈是否有效? (預期:false)
console.log("區塊鏈是否有效?", myIoTChain.isChainValid());

一旦惡意節點去修改了陣列裡的資料,isChainValid() 這個方法就會立刻抓出破綻,這就是區塊鏈確保資料安全的最底層邏輯。

今天我成功用 JavaScript 把區塊鏈的基本骨架給搭建出來了!
目前我 addBlock() 的速度是瞬間完成的。在真實的分散式網路中,如果不限制產塊速度,整個網路很快就會被垃圾區塊塞爆。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言