-
Notifications
You must be signed in to change notification settings - Fork 5
/
MerkelTree.js
60 lines (47 loc) · 1.49 KB
/
MerkelTree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const sha256 = require("./helper");
class MerkelTree {
// root stores all the layers
constructor() {
this.root = [];
}
// Creates all the layers of thr tree for the given transaction list
createTree(transactionList) {
this.root.unshift(transactionList);
this.root.unshift(transactionList.map(t => t.hash));
while (this.root[0].length > 1) {
let temp = [];
for (let index = 0; index < this.root[0].length; index += 2) {
if (index < this.root[0].length - 1 && index % 2 == 0)
temp.push(sha256(this.root[0][index] + this.root[0][index + 1]));
else temp.push(this.root[0][index]);
}
this.root.unshift(temp);
}
}
// Checks if the transaction is valid or not
verify(transaction) {
let position = this.root.slice(-1)[0].findIndex(t => t.hash == transaction.hash);
console.log("Element found at: " + position);
if (position) {
let verifyHash = transaction.getHash();
for (let index = this.root.length - 2; index > 0; index--) {
let neighbour = null;
if (position % 2 == 0) {
neighbour = this.root[index][position + 1];
position = Math.floor((position) / 2)
verifyHash = sha256(verifyHash + neighbour);
}
else {
neighbour = this.root[index][position - 1];
position = Math.floor((position - 1) / 2)
verifyHash = sha256(neighbour + verifyHash);
}
}
console.log(verifyHash == this.root[0][0] ? "Valid" : "Not Valid");
}
else {
console.log("Data not found with the id");
}
}
}
module.exports = MerkelTree;