forked from nfgenes/merkletree_generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateHashArrayFile.js
101 lines (88 loc) · 2.75 KB
/
generateHashArrayFile.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const keccak256 = require('keccak256');
const fs = require('fs');
const { MerkleTree } = require('merkletreejs')
const geneList = require('./NFgenesList.json');
const leavesHashArray = [];
let layerCount;
let treeDepth;
let leafCount;
let tree;
const generateLeavesHashArray = () => {
/**
* Iterate through the json array source data and keccak256
* hash each gene object into a hexadecimal string.
*
* Store this new json array in the 'leavesHashArray' variable
*/
try {
for (i = 0; i < geneList.length; i++) {
let currentLeaf;
let currentValue;
currentLeaf = geneList[i];
currentValue = '0x' + keccak256(JSON.stringify(geneList[i])).toString('hex');
console.log(`Generating keccak256 hash for ${currentLeaf}`);
leavesHashArray.push(currentValue);
}
} catch (e) {
console.log(e);
}
}
/**
* TO DO: Add a check for a generated tree that is unbalanced. At a minimum
* give a notice of unbalaned tree and perhaps add functionality to auto-balance.
*/
const generateMerkleLeaves = () => {
/**
* Creates a new json file with the array of hashed gene objects
*/
fs.writeFileSync('MerkleLeaves.json', JSON.stringify(leavesHashArray), err => {
if (err) {
throw err;
}
console.log('Hashed array saved to MerkleLeaves.json');
});
}
const generateMerkleTree = () => {
/**
* Creates a new file called 'MerkleTree' that contains
* the generated Merkle tree from the 'MerkleLeaves.json' file
*/
tree = new MerkleTree(leavesHashArray, keccak256, {sortPairs: true});
console.log('Tree:\n', tree.toString());
fs.writeFileSync('MerkleTree.txt', tree.toString(), err => {
if (err) {
throw err;
}
console.log(`Merkle tree generated.`);
});
layerCount = tree.getLayerCount();
treeDepth = tree.getDepth();
leafCount = tree. getLeafCount();
}
const generateMerkleRoot = () => {
/**
* Create text file called 'MerkleTreeRoot' that contains
* the Merkle tree root hash.
*/
fs.writeFileSync('MerkleTreeRoot.txt', tree.getHexRoot(), err => {
if (err) {
throw err;
}
console.log(`Merkle Tree root hash is\n ...${tree.getHexRoot()} \n ...Saving to MerkleTreeRoot.txt`);
});
}
const runLogs = () => {
// Log some information
console.log(`Layer Count: ${layerCount}`);
console.log(`Leaf Count: ${leafCount}`);
console.log(`Depth ${treeDepth}`);
}
const runSync = () => {
generateLeavesHashArray();
generateMerkleLeaves();
generateMerkleTree();
generateMerkleRoot();
runLogs();
console.log('...Everything is Merkled');
}
runSync();