merkle: refactor loops.
This commit is contained in:
parent
a4a16f6ec0
commit
bd56c75d0d
@ -24,13 +24,14 @@ exports.createTree = function createTree(leaves) {
|
||||
let nodes = leaves;
|
||||
let size = leaves.length;
|
||||
let malleated = false;
|
||||
let i = 0;
|
||||
|
||||
if (size === 0) {
|
||||
nodes.push(Buffer.alloc(32));
|
||||
return [nodes, malleated];
|
||||
}
|
||||
|
||||
for (let i = 0; size > 1; size = (size + 1) >>> 1) {
|
||||
while (size > 1) {
|
||||
for (let j = 0; j < size; j += 2) {
|
||||
let k = Math.min(j + 1, size - 1);
|
||||
let left = nodes[i + j];
|
||||
@ -47,6 +48,8 @@ exports.createTree = function createTree(leaves) {
|
||||
nodes.push(hash);
|
||||
}
|
||||
i += size;
|
||||
size += 1;
|
||||
size >>>= 1;
|
||||
}
|
||||
|
||||
return [nodes, malleated];
|
||||
@ -65,7 +68,7 @@ exports.createRoot = function createRoot(leaves) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Collect a merkle branch at vector index.
|
||||
* Collect a merkle branch from vector index.
|
||||
* @param {Number} index
|
||||
* @param {Buffer[]} leaves
|
||||
* @returns {Buffer[]} branch
|
||||
@ -75,33 +78,36 @@ exports.createBranch = function createBranch(index, leaves) {
|
||||
let size = leaves.length;
|
||||
let [nodes] = exports.createTree(leaves);
|
||||
let branch = [];
|
||||
let i = 0;
|
||||
|
||||
for (let i = 0; size > 1; size = (size + 1) >>> 1) {
|
||||
while (size > 1) {
|
||||
let j = Math.min(index ^ 1, size - 1);
|
||||
branch.push(nodes[i + j]);
|
||||
index >>>= 1;
|
||||
i += size;
|
||||
size += 1;
|
||||
size >>>= 1;
|
||||
}
|
||||
|
||||
return branch;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check a merkle branch at vector index.
|
||||
* Derive merkle root from branch.
|
||||
* @param {Buffer} hash
|
||||
* @param {Buffer[]} branch
|
||||
* @param {Number} index
|
||||
* @returns {Buffer} Hash.
|
||||
* @returns {Buffer} root
|
||||
*/
|
||||
|
||||
exports.verifyBranch = function verifyBranch(hash, branch, index) {
|
||||
exports.deriveRoot = function deriveRoot(hash, branch, index) {
|
||||
let root = hash;
|
||||
|
||||
for (let otherside of branch) {
|
||||
for (let hash of branch) {
|
||||
if (index & 1)
|
||||
root = digest.root256(otherside, root);
|
||||
root = digest.root256(hash, root);
|
||||
else
|
||||
root = digest.root256(root, otherside);
|
||||
root = digest.root256(root, hash);
|
||||
|
||||
index >>>= 1;
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user