1
- /*
2
-
3
- Ported from https://github.com/slush0/stratum-mining/blob/master/lib/merkletree.py
4
-
5
- */
6
-
7
1
var util = require ( './util.js' ) ;
8
2
9
3
var MerkleTree = module . exports = function MerkleTree ( data ) {
4
+ this . data = data . filter ( element => element != null ) ;
5
+ this . steps = calculateSteps ( this . data ) ;
6
+ } ;
10
7
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' ) ;
15
11
}
12
+ var joined = Buffer . concat ( [ h1 , h2 ] ) ;
13
+ var dhashed = util . sha256d ( joined ) ;
14
+ return dhashed ;
15
+ }
16
16
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 ;
26
21
27
- if ( Ll === 1 )
28
- break ;
22
+ if ( Ll > 1 ) {
23
+ while ( true ) {
24
+ if ( Ll === 1 ) break ;
29
25
30
- steps . push ( L [ 1 ] ) ;
26
+ steps . push ( L [ 1 ] ) ;
31
27
32
- if ( Ll % 2 )
33
- L . push ( L [ L . length - 1 ] ) ;
28
+ if ( Ll % 2 ) L . push ( L [ L . length - 1 ] ) ;
34
29
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 ) {
38
33
Ld . push ( merkleJoin ( L [ i ] , L [ i + 1 ] ) ) ;
39
- } ) ;
40
- L = PreL . concat ( Ld ) ;
41
- Ll = L . length ;
34
+ }
42
35
}
36
+ L = Ld ;
37
+ Ll = L . length ;
43
38
}
44
- return steps ;
45
39
}
46
-
47
- this . data = data ;
48
- this . steps = calculateSteps ( data ) ;
49
-
40
+ return steps ;
50
41
}
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