答案:用JavaScript构建简单区块链需定义区块结构和链式连接逻辑。1. 创建含索引、时间戳、数据、前后哈希的Block类,用SHA-256计算哈希;2. 实现Blockchain类,包含创世块、添加区块及验证链有效性方法;3. 示例中添加区块并验证完整性,篡改数据后链失效,体现不可篡改性。

用JavaScript构建一个简单的区块链模拟并不复杂。核心是理解区块链的基本结构:每个区块包含数据、时间戳、自身哈希和前一个区块的哈希。通过哈希连接,形成不可篡改的链式结构。
每个区块应包含索引、时间戳、数据、前一个区块的哈希值和当前区块的哈希值。使用SHA-256算法生成哈希。
npm install crypto-js
立即学习“Java免费学习笔记(深入)”;
创建一个Block类:
// 引入SHA256
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();
}
}
区块链是一个区块的集合,从创世区块开始。添加新区块时需验证其有效性。
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, "01/01/2024", "Genesis Block", "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;
}
}
创建实例并添加几个区块测试功能。
let myBlockchain = new Blockchain();
myBlockchain.addBlock(new Block(1, Date.now(), { amount: 4 }));
myBlockchain.addBlock(new Block(2, Date.now(), { amount: 8 }));
console.log(JSON.stringify(myBlockchain, null, 2));
console.log("区块链有效吗?", myBlockchain.isChainValid());
尝试修改某个区块的数据,再验证链的有效性。
// 篡改第二个区块
myBlockchain.chain[1].data = { amount: 100 };
myBlockchain.chain[1].hash = myBlockchain.chain[1].calculateHash(); // 手动更新哈希
console.log("篡改后有效吗?", myBlockchain.isChainValid()); // 输出 false
基本上就这些。这个简单模拟展示了区块链的核心原理:链式结构、哈希关联和完整性校验。不复杂但容易忽略细节,比如哈希重新计算和前后连接逻辑。
以上就是如何用JavaScript构建一个简单的区块链模拟?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号