区块包含索引、时间戳、数据、前一区块哈希和自身哈希,通过SHA-256计算;2. 区块链由区块链接构成,首块为创世块;3. 验证链完整性需检查每块哈希及前后连接一致性。

要实现一个简单的区块链数据结构,核心是理解区块链的基本组成:区块、哈希计算和链式连接。下面用 JavaScript 实现一个基础版本,帮助你掌握其原理。
每个区块应包含索引、时间戳、数据、前一个区块的哈希值,以及自身哈希。使用 SHA-256 进行哈希计算,Node.js 环境下可用 crypto 模块,浏览器中可用 Web Crypto API。
示例代码:
class Block {
constructor(index, data, previousHash = '') {
this.index = index;
this.timestamp = Date.now();
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
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 myBlockchain = new Blockchain();
myBlockchain.addBlock(new Block(1, { amount: 100, to: 'Alice' }));
myBlockchain.addBlock(new Block(2, { amount: 50, to: 'Bob' }));
console.log(JSON.stringify(myBlockchain, null, 2));
console.log("区块链有效:", myBlockchain.isChainValid());
基本上就这些。这个实现虽然简单,但涵盖了区块链的核心机制:不可变性、链式结构和哈希验证。你可以在此基础上加入工作量证明(PoW)或点对点网络来增强功能。
以上就是如何利用 JavaScript 实现一个简单的区块链数据结构?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号