# JavaScript怎么開發區塊鏈
## 引言
區塊鏈技術作為分布式賬本的核心實現,近年來在金融、供應鏈、數字身份等領域展現出巨大潛力。雖然傳統區塊鏈開發多使用Go、Rust等系統級語言,但JavaScript憑借其全棧能力和豐富的生態,同樣能構建功能完整的區塊鏈系統。本文將深入講解如何使用JavaScript從零開發一個簡易區塊鏈。
## 一、區塊鏈基礎概念回顧
### 1.1 區塊鏈核心組成
- **區塊(Block)**: 存儲交易數據的基本單位
- **鏈(Chain)**: 通過哈希值連接的區塊序列
- **共識機制**: POW/POS等決策機制
- **P2P網絡**: 節點間的去中心化通信
### 1.2 關鍵技術特征
- 哈希加密(SHA-256)
- 非對稱加密(ECDSA)
- 默克爾樹(Merkle Tree)
- 工作量證明(Proof of Work)
## 二、開發環境準備
### 2.1 工具棧選擇
```bash
# 推薦技術棧
Node.js (v18+) # 運行時環境
TypeScript (可選) # 類型檢查
crypto-js # 加密庫
ws # WebSocket網絡庫
Jest # 單元測試
// package.json核心配置
{
"name": "js-blockchain",
"type": "module",
"dependencies": {
"crypto-js": "^4.1.1",
"ws": "^8.13.0"
}
}
import SHA256 from '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; // POW計數器
}
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(`Block mined: ${this.hash}`);
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 4; // 挖礦難度
this.pendingTransactions = [];
this.miningReward = 100; // 挖礦獎勵
}
createGenesisBlock() {
return new Block(0, "01/01/2023", "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);
}
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()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
class Transaction {
constructor(fromAddress, toAddress, amount) {
this.fromAddress = fromAddress;
this.toAddress = toAddress;
this.amount = amount;
}
}
const EC = require('elliptic').ec;
const ec = new EC('secp256k1'); // 比特幣使用的曲線
class Wallet {
constructor() {
this.keyPair = ec.genKeyPair();
this.publicKey = this.keyPair.getPublic('hex');
this.privateKey = this.keyPair.getPrivate('hex');
}
signTransaction(transaction) {
const hashTx = SHA256(JSON.stringify(transaction)).toString();
const signature = this.keyPair.sign(hashTx, 'base64');
return signature.toDER('hex');
}
static verifySignature(publicKey, signature, transaction) {
const key = ec.keyFromPublic(publicKey, 'hex');
const hashTx = SHA256(JSON.stringify(transaction)).toString();
return key.verify(hashTx, signature);
}
}
import { WebSocketServer } from 'ws';
class P2PServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen(port) {
const server = new WebSocketServer({ port });
server.on('connection', (socket) => this.connectSocket(socket));
console.log(`Listening for peer-to-peer connections on: ${port}`);
}
connectSocket(socket) {
this.sockets.push(socket);
this.messageHandler(socket);
this.sendChain(socket);
}
messageHandler(socket) {
socket.on('message', (message) => {
const data = JSON.parse(message);
switch(data.type) {
case 'CHN':
this.blockchain.replaceChain(data.chain);
break;
case 'TRANSACTION':
this.blockchain.addTransaction(data.transaction);
break;
}
});
}
syncChains() {
this.sockets.forEach(socket => this.sendChain(socket));
}
}
// 在Blockchain類中添加方法
minePendingTransactions(miningRewardAddress) {
const rewardTx = new Transaction(
null,
miningRewardAddress,
this.miningReward
);
this.pendingTransactions.push(rewardTx);
let block = new Block(
Date.now(),
this.pendingTransactions,
this.getLatestBlock().hash
);
block.mineBlock(this.difficulty);
console.log('Block successfully mined!');
this.chain.push(block);
this.pendingTransactions = [];
}
replaceChain(newChain) {
if (newChain.length <= this.chain.length) {
console.log('Received chain is not longer than current chain.');
return;
} else if (!this.isChainValid(newChain)) {
console.log('Received chain is invalid.');
return;
}
console.log('Replacing current chain with new chain.');
this.chain = newChain;
}
describe('Blockchain', () => {
let blockchain;
beforeEach(() => {
blockchain = new Blockchain();
});
it('starts with genesis block', () => {
expect(blockchain.chain[0].data).toEqual('Genesis block');
});
it('validates a valid chain', () => {
blockchain.addBlock({ data: 'Test' });
expect(blockchain.isChainValid()).toBe(true);
});
});
class SmartContract {
constructor(code) {
this.code = code;
this.state = {};
}
execute(transaction) {
// 安全沙箱執行
try {
const func = new Function('tx', 'state', this.code);
func(transaction, this.state);
} catch (error) {
console.error('Contract execution failed:', error);
}
}
}
import express from 'express';
const app = express();
app.use(express.json());
app.get('/blocks', (req, res) => {
res.json(blockchain.chain);
});
app.post('/transact', (req, res) => {
const { sender, recipient, amount } = req.body;
const transaction = new Transaction(sender, recipient, amount);
blockchain.addTransaction(transaction);
res.sendStatus(200);
});
js-blockchain/
├── src/
│ ├── block.js # 區塊實現
│ ├── blockchain.js # 鏈邏輯
│ ├── transaction.js # 交易系統
│ ├── wallet.js # 錢包功能
│ ├── p2p-server.js # 網絡層
│ └── app.js # 主入口
├── tests/ # 單元測試
├── package.json
└── README.md
通過本文的實踐,我們使用JavaScript實現了一個具備基礎功能的區塊鏈系統。盡管生產級區塊鏈需要考慮更多復雜因素(如分片、側鏈、跨鏈等),但這個實現已經包含了區塊鏈的核心技術要素。建議進一步學習:
提示:完整項目代碼可參考 GitHub示例倉庫
”`
注:本文實際約3700字,可根據需要補充以下內容擴展: 1. 更詳細的Merkle Tree實現 2. 實際網絡同步的代碼示例 3. 性能測試數據對比 4. 瀏覽器端運行的適配方案
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。