用js写一个merkle树
时间: 2024-01-04 12:02:35 浏览: 66
好的,下面是一个简单的 Merkle 树实现的 JavaScript 代码:
```javascript
// MerkleTree class
class MerkleTree {
constructor(transactions) {
this.transactions = transactions;
this.tree = [];
this.build();
}
// build the Merkle tree from the transactions
build() {
for (let t of this.transactions) {
this.tree.push(this.hash(t));
}
let i = 0;
while (this.tree.length > 1) {
let temp = [];
for (i = 0; i < this.tree.length; i += 2) {
if (i + 1 == this.tree.length) {
temp.push(this.tree[i]);
} else {
temp.push(this.hash(this.tree[i], this.tree[i + 1]));
}
}
this.tree = temp;
}
}
// calculate the hash of two nodes
hash(left, right = "") {
return crypto.createHash('sha256').update(left + right).digest('hex');
}
// get the Merkle root
getRoot() {
return this.tree[0];
}
// validate a transaction
validate(transaction) {
let index = this.transactions.indexOf(transaction);
if (index == -1) {
return false;
}
let proof = this.getProof(index);
let root = this.getRoot();
for (let p of proof) {
if (index % 2 == 0) {
root = this.hash(p, root);
} else {
root = this.hash(root, p);
}
index = Math.floor(index / 2);
}
return root == proof[0];
}
// get the proof of a transaction
getProof(index) {
let proof = [];
while (index > 0) {
let sibling = (index % 2 == 0) ? this.tree[index - 1] : this.tree[index + 1];
proof.push(sibling);
index = Math.floor((index - 1) / 2);
}
return proof;
}
}
```
这个 Merkle 树类可以接受一个交易数组作为输入,然后使用 SHA256 来计算交易的哈希值,在循环中构建 Merkle 树。它还提供了一些方法,如 getRoot() 来获取 Merkle 根节点,validate(transaction) 来验证一个交易是否有效,getProof(index) 来获取一个交易的证明路径等。
阅读全文