《200行代码实现blockchain区块链实例详解》
区块链作为分布式账本技术的核心,其去中心化、不可篡改的特性正改变着金融、供应链、版权管理等领域。本文将以JavaScript为工具,通过200行代码实现一个简化版区块链系统,涵盖区块结构、哈希加密、工作量证明(PoW)和简单交易验证等核心功能。代码将分为模块化设计,便于理解每个组件的作用。
一、区块链基础组件设计
1.1 区块(Block)结构
每个区块包含索引、时间戳、交易数据、前一个区块的哈希值和当前区块的哈希值。哈希值通过SHA-256算法生成,确保数据不可篡改。
class Block {
constructor(index, timestamp, transactions, previousHash = '') {
this.index = index;
this.timestamp = timestamp;
this.transactions = transactions;
this.previousHash = previousHash;
this.hash = this.calculateHash();
this.nonce = 0; // 用于工作量证明的随机数
}
calculateHash() {
const data = `${this.index}${this.timestamp}${JSON.stringify(this.transactions)}${this.previousHash}${this.nonce}`;
return CryptoJS.SHA256(data).toString();
}
}
1.2 区块链(Blockchain)类
区块链类管理区块的创建、验证和链的完整性检查。
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 4; // 工作量证明难度
this.pendingTransactions = []; // 待处理交易
this.miningReward = 100; // 挖矿奖励
}
createGenesisBlock() {
return new Block(0, Date.now(), [], '0');
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addTransaction(transaction) {
this.pendingTransactions.push(transaction);
}
mineBlock(minerAddress) {
const latestBlock = this.getLatestBlock();
const newBlock = new Block(
latestBlock.index + 1,
Date.now(),
[...this.pendingTransactions, { from: 'network', to: minerAddress, amount: this.miningReward }],
latestBlock.hash
);
newBlock.mineBlock(this.difficulty); // 执行工作量证明
this.chain.push(newBlock);
this.pendingTransactions = [];
return newBlock;
}
}
二、核心算法实现
2.1 工作量证明(PoW)
通过调整nonce值使区块哈希满足前导零数量要求,模拟计算密集型任务。
Block.prototype.mineBlock = function(difficulty) {
while (!this.hash.startsWith('0'.repeat(difficulty))) {
this.nonce++;
this.hash = this.calculateHash();
}
};
2.2 区块链有效性验证
检查每个区块的哈希是否正确,以及前一个区块哈希是否匹配。
Blockchain.prototype.isChainValid = function() {
for (let i = 1; i
三、交易与钱包系统
3.1 交易结构
简化交易模型包含发送方、接收方和金额。
class Transaction {
constructor(fromAddress, toAddress, amount) {
this.fromAddress = fromAddress;
this.toAddress = toAddress;
this.amount = amount;
}
}
3.2 钱包余额管理
通过遍历区块链中的交易计算地址余额。
Blockchain.prototype.getBalanceOfAddress = function(address) {
let balance = 0;
for (const block of this.chain) {
for (const trans of block.transactions) {
if (trans.fromAddress === address) balance -= trans.amount;
if (trans.toAddress === address) balance += trans.amount;
}
}
return balance;
};
四、完整代码实现
整合上述组件,实现一个可运行的区块链系统。
// 引入CryptoJS库(需提前安装)
const CryptoJS = require('crypto-js');
class Block { /* 同上 */ }
class Blockchain { /* 同上 */ }
class Transaction { /* 同上 */ }
// 创建区块链实例
const myBlockchain = new Blockchain();
// 添加交易
myBlockchain.addTransaction(new Transaction('Alice', 'Bob', 50));
myBlockchain.addTransaction(new Transaction('Bob', 'Charlie', 30));
// 挖矿并获得奖励
console.log('开始挖矿...');
const newBlock = myBlockchain.mineBlock('MinerAddress');
console.log('新区块已挖出:', newBlock);
// 验证区块链
console.log('区块链是否有效:', myBlockchain.isChainValid() ? '是' : '否');
// 查询余额
console.log('Alice的余额:', myBlockchain.getBalanceOfAddress('Alice'));
console.log('Miner的余额:', myBlockchain.getBalanceOfAddress('MinerAddress'));
五、代码优化与扩展
5.1 异步挖矿优化
使用Promise模拟异步挖矿过程,避免阻塞主线程。
Blockchain.prototype.mineBlockAsync = function(minerAddress) {
return new Promise((resolve) => {
setTimeout(() => {
const block = this.mineBlock(minerAddress);
resolve(block);
}, 1000); // 模拟延迟
});
};
5.2 交易签名验证(简化版)
通过私钥签名验证交易合法性(实际应用需使用椭圆曲线加密)。
class SimpleWallet {
constructor() {
this.privateKey = Math.random().toString(36).substring(2);
this.publicKey = 'public_' + this.privateKey; // 简化模型
}
signTransaction(transaction) {
return `${transaction.fromAddress}:${transaction.amount}:${this.privateKey}`;
}
}
六、实际应用场景
6.1 供应链溯源
将商品流转信息记录到区块链,确保数据不可篡改。
const supplyChainBlockchain = new Blockchain();
supplyChainBlockchain.addTransaction({
from: 'Factory',
to: 'Warehouse',
productId: 'P123',
timestamp: Date.now()
});
6.2 版权登记
艺术家将作品哈希值存入区块链,证明原创性。
function registerCopyright(blockchain, artist, workHash) {
blockchain.addTransaction(new Transaction(artist, 'CopyrightRegistry', workHash));
blockchain.mineBlock('RegistryNode');
}
七、性能优化方向
7.1 轻量级节点设计
仅存储区块头信息,通过SPV(简单支付验证)验证交易。
class LightNode {
constructor(fullNodeUrl) {
this.headers = [];
this.fullNodeUrl = fullNodeUrl;
}
async syncHeaders() {
// 从全节点获取区块头
}
}
7.2 共识算法升级
将PoW替换为PoS(权益证明)或DPoS(委托权益证明)。
class PoSBlockchain extends Blockchain {
mineBlock(stakerAddress) {
// 根据持币量选择出块者
}
}
八、完整示例运行
安装依赖后运行以下代码:
npm install crypto-js
node blockchain.js
输出示例:
开始挖矿...
新区块已挖出: Block {
index: 1,
timestamp: 1625097600000,
transactions: [...],
hash: '0000a1b2c3...',
nonce: 12345
}
区块链是否有效: 是
Alice的余额: -50
Miner的余额: 100
关键词与简介
关键词:区块链、JavaScript、工作量证明、哈希加密、去中心化、交易验证、SPV、PoS共识
简介:本文通过200行JavaScript代码实现了一个包含区块结构、哈希加密、工作量证明和交易系统的简化版区块链,详细解析了区块链的核心原理,并提供了供应链溯源、版权登记等实际应用场景的代码示例,适合开发者快速理解区块链技术实现。