Skip to content

Commit 27bde74

Browse files
Update merkleTree.js
1 parent 1fc8c92 commit 27bde74

File tree

1 file changed

+33
-43
lines changed

1 file changed

+33
-43
lines changed

lib/merkleTree.js

+33-43
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,48 @@
1-
/*
2-
3-
Ported from https://github.com/slush0/stratum-mining/blob/master/lib/merkletree.py
4-
5-
*/
6-
71
var util = require('./util.js');
82

93
var MerkleTree = module.exports = function MerkleTree(data){
4+
this.data = data.filter(element => element != null);
5+
this.steps = calculateSteps(this.data);
6+
};
107

11-
function merkleJoin(h1, h2){
12-
var joined = Buffer.concat([h1, h2]);
13-
var dhashed = util.sha256d(joined);
14-
return dhashed;
8+
function merkleJoin(h1, h2){
9+
if (h1 === null || h2 === null) {
10+
throw new Error('Merkle join received null input');
1511
}
12+
var joined = Buffer.concat([h1, h2]);
13+
var dhashed = util.sha256d(joined);
14+
return dhashed;
15+
}
1616

17-
function calculateSteps(data){
18-
var L = data;
19-
var steps = [];
20-
var PreL = [null];
21-
var StartL = 2;
22-
var Ll = L.length;
23-
24-
if (Ll > 1){
25-
while (true){
17+
function calculateSteps(data){
18+
var L = data;
19+
var steps = [];
20+
var Ll = L.length;
2621

27-
if (Ll === 1)
28-
break;
22+
if (Ll > 1){
23+
while (true){
24+
if (Ll === 1) break;
2925

30-
steps.push(L[1]);
26+
steps.push(L[1]);
3127

32-
if (Ll % 2)
33-
L.push(L[L.length - 1]);
28+
if (Ll % 2) L.push(L[L.length - 1]);
3429

35-
var Ld = [];
36-
var r = util.range(StartL, Ll, 2);
37-
r.forEach(function(i){
30+
var Ld = [];
31+
for (var i = 0; i < L.length; i += 2) {
32+
if (i + 1 < L.length) {
3833
Ld.push(merkleJoin(L[i], L[i + 1]));
39-
});
40-
L = PreL.concat(Ld);
41-
Ll = L.length;
34+
}
4235
}
36+
L = Ld;
37+
Ll = L.length;
4338
}
44-
return steps;
4539
}
46-
47-
this.data = data;
48-
this.steps = calculateSteps(data);
49-
40+
return steps;
5041
}
51-
MerkleTree.prototype = {
52-
withFirst: function(f){
53-
this.steps.forEach(function(s){
54-
f = util.sha256d(Buffer.concat([f, s]));
55-
});
56-
return f;
57-
}
58-
};
42+
43+
MerkleTree.prototype.withFirst = function(f){
44+
this.steps.forEach(function(s){
45+
f = util.sha256d(Buffer.concat([f, s]));
46+
});
47+
return f;
48+
};

0 commit comments

Comments
 (0)