-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
51 lines (37 loc) · 1.24 KB
/
index.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
'use strict';
const
precon = require('@mintpond/mint-precon'),
buffers = require('@mintpond/mint-utils').buffers;
module.exports = {
/**
* A class to assist in pre-calculating merkle branches without a Bitcoin coinbase hash so that the merkle root can
* be calculated faster when a coinbase is ready to be added.
*/
TxMerkleTree: require('./libs/class.TxMerkleTree'),
/**
* Calculate the merkle root from an array of hash leaves.
*
* @param hashArr {Buffer[]}
* @returns Buffer
*/
rootFromHashArr: rootFromHashArr
};
function rootFromHashArr(hashArr) {
precon.arrayOfInstance(hashArr, Buffer, 'hashArr');
if (hashArr.length === 0)
return Buffer.alloc(32, 0);
let arr = hashArr;
let len = hashArr.length;
while (len > 1) {
const nextArr = [];
// hash serial pairs and push result into array for next iteration
for (let i = 0; i < len; i += 2) {
const pairArr = [arr[i], arr[i + 1] || arr[len - 1]/*duplicate last item if len is uneven*/];
const hashed = buffers.sha256d(Buffer.concat(pairArr));
nextArr.push(hashed);
}
arr = nextArr;
len = nextArr.length;
}
return arr[0];
}