ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ project မှာ Basic chapter မှာသင်ခဲ့တဲ့ block, hashing, immutability concept တွေကို တကယ်လက်တွေ့ code ရေးပြီး ချိတ်ဆက်ကြည့်မှာဖြစ်ပါတယ်။ Bitcoin, Ethereum လို real blockchain တွေမှာ block တစ်ခုချင်းစီရဲ့ hash ကို နောက် block ရဲ့ previousHash field ထဲမှာ ထည့်ထားပြီး chain အဖြစ် ချိတ်ဆက်ထားတာပါ။ ဒီ mechanism ကို နားလည်ဖို့ Node.js built-in crypto module နဲ့ SHA256 hash ကို တိုက်ရိုက်တွက်ချက်ပြီး ကိုယ်ပိုင် Block class ရေးကြည့်မှာဖြစ်ပါတယ်။ ဒီအပိုင်းမှာ Block class တည်ဆောက်ခြင်းနဲ့ Blockchain class ရဲ့ genesis block စတင်ခြင်းအထိပဲ ဖြစ်ပါတယ်၊ transaction နဲ့ mining ကို နောက်အပိုင်းမှာ ဆက်ထည့်ပါမယ်။
လက်တွေ့ ဆောက်ကြည့်မယ်
Project folder အသစ်တစ်ခုဖွင့်ပြီး blockchain.js ဖိုင်တစ်ခုဆောက်ပါ။ crypto module ကို built-in အနေနဲ့ require လုပ်ပါ (npm install မလိုပါ)။ Block class မှာ index, timestamp, data, previousHash, hash field တွေထည့်ပြီး calculateHash() method ထဲမှာ index+previousHash+timestamp+JSON.stringify(data) ကို SHA256 နဲ့ hash လုပ်ပါ။ Blockchain class မှာ chain array ကို createGenesisBlock() နဲ့ initialize လုပ်ပြီး getLatestBlock() method ကို ထည့်ထားပါ။ အဆုံးမှာ console.log(JSON.stringify(myChain, null, 2)) နဲ့ genesis block ကို print ကြည့်ပါ။
Code နမူနာ
const crypto = require('crypto');
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 crypto
.createHash('sha256')
.update(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data))
.digest('hex');
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, Date.now(), 'Genesis Block', '0');
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
}
const myChain = new Blockchain();
console.log(JSON.stringify(myChain, null, 2));
node blockchain.js run လိုက်ရင် terminal ပေါ်မှာ chain array ထဲမှာ genesis block တစ်ခုနဲ့ hex string ပုံစံ hash value ကို JSON format နဲ့ print ထုတ်ပြပါလိမ့်မယ်။၅ မိနစ် စမ်းကြည့်
Genesis block ရဲ့ data field ကို 'Genesis Block' ကနေ 'genesis block' (စာလုံးအသေးလေး တစ်လုံးပြောင်း) ပြောင်းပြီး run ကြည့်ပါ — hash value တစ်ခုလုံး လုံးဝပြောင်းသွားတာကို 5 မိနစ်အတွင်း သတိထားကြည့်ပါ။
သတိလေးတစ်ချက်
ဒါက learning purpose အတွက် simulation ပဲဖြစ်ပါတယ်၊ real blockchain က distributed node များစွာအပေါ် consensus ယူပြီးမှ block confirm လုပ်တာမို့ ဒီ single-file version ကို production မှာ မသုံးသင့်ပါဘူး။