答案:用JavaScript实现区块链需定义区块与链结构。1. 区块类含索引、时间戳、数据、前哈希与自身哈希,通过SHA-256计算哈希值;2. 区块链类维护区块数组,包含创世块,新增区块时链接前一区块哈希;3. 验证链的完整性,检查每个区块哈希与前块哈希是否匹配;4. 测试显示添加交易区块及篡改检测功能,确保不可变性。

想用JavaScript做一个简单的区块链模拟器?其实不难。核心是理解区块链的基本结构:每个区块包含数据、时间戳、上一个区块的哈希,以及自身的哈希值。通过哈希链接,形成一条不可篡改的链。
定义区块结构
每个区块应包含以下信息:
-
index:区块在链中的位置
-
timestamp:创建时间
-
data:任意数据(比如交易记录)
-
previousHash:前一个区块的哈希值
-
hash:当前区块的哈希值
使用JavaScript类来表示区块:
class Block {
constructor(index, data, previousHash = '') {
this.index = index;
this.timestamp = new Date().toISOString();
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
}
calculateHash() {
const crypto = require('crypto');
return crypto
.createHash('sha256')
.update(this.index + this.timestamp + JSON.stringify(this.data) + this.previousHash)
.digest('hex');
}
}
创建区块链类
区块链本质上是一个区块数组,从“创世区块”开始。新块必须指向链中最后一个块的哈希。
立即学习“Java免费学习笔记(深入)”;
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, "创世区块", "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()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
测试你的区块链
现在可以实例化并添加一些区块验证功能:
const myCoin = new Blockchain();
myCoin.addBlock(new Block(1, { amount: 100, sender: "Alice", receiver: "Bob" }));
myCoin.addBlock(new Block(2, { amount: 50, sender: "Bob", receiver: "Charlie" }));
console.log(JSON.stringify(myCoin, null, 2));
console.log("区块链有效吗?", myCoin.isChainValid());
尝试手动修改某个区块的data或hash,再运行isChainValid(),会返回false,说明篡改被检测到了。
基本上就这些。这个模拟器展示了区块链的核心原理:链式结构、哈希指针和完整性校验。虽然没有共识机制或P2P网络,但足够帮你理解底层逻辑。
以上就是如何利用JavaScript构建一个简单的区块链模拟器?的详细内容,更多请关注php中文网其它相关文章!