MCPcopy
hub / github.com/FuelLabs/fuels-ts / constructTree

Function constructTree

packages/merkle/src/binary/binaryMerkleTree.ts:26–68  ·  view source on GitHub ↗
(data: string[])

Source from the content-addressed store, hash-verified

24 * Construct tree
25 */
26export function constructTree(data: string[]): Node[] {
27 const nodes = [];
28 for (let i = 0; i < data.length; i += 1) {
29 const hashed = hashLeaf(data[i]);
30 const leaf = new Node(-1, -1, -1, hashed, data[i]);
31 leaf.index = i;
32 nodes.push(leaf);
33 }
34
35 const nodesList = [...nodes];
36 let pNodes = [...nodes];
37
38 let size = (nodes.length + 1) >> 1;
39 let odd = nodes.length & 1;
40 // eslint-disable-next-line no-constant-condition
41 while (true) {
42 let i = 0;
43 for (; i < size - odd; i += 1) {
44 const j = i << 1;
45 const hashed = hashNode(pNodes[j].hash, pNodes[j + 1].hash);
46 nodes[i] = new Node(pNodes[j].index, pNodes[j + 1].index, -1, hashed, '');
47 const nextIndex = nodesList.length;
48 nodes[i].index = nextIndex;
49
50 nodesList[pNodes[j].index].parent = nextIndex;
51 nodesList[pNodes[j + 1].index].parent = nextIndex;
52 nodesList.push(nodes[i]);
53 }
54
55 if (size === 1) {
56 break;
57 }
58
59 if (odd === 1) {
60 nodes[i] = pNodes[i << 1];
61 }
62
63 odd = size & 1;
64 size = (size + 1) >> 1;
65 pNodes = [...nodes];
66 }
67 return nodesList;
68}
69
70/**
71 * Compute the merkle root

Callers 1

Calls 3

pushMethod · 0.80
hashLeafFunction · 0.70
hashNodeFunction · 0.70

Tested by

no test coverage detected