-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
34 lines (26 loc) · 867 Bytes
/
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
// returns an array of hashes of length: values.length / 2 + (values.length % 2)
function _derive (values, digestFn) {
var length = values.length
var results = []
for (var i = 0; i < length; i += 2) {
var left = values[i]
var right = i + 1 === length ? left : values[i + 1]
var data = Buffer.concat([left, right])
results.push(digestFn(data))
}
return results
}
// returns the merkle tree
function merkle (values, digestFn) {
if (!Array.isArray(values)) throw TypeError('Expected values Array')
if (typeof digestFn !== 'function') throw TypeError('Expected digest Function')
if (values.length === 1) return values.concat()
var levels = [values]
var level = values
do {
level = _derive(level, digestFn)
levels.push(level)
} while (level.length > 1)
return [].concat.apply([], levels)
}
module.exports = merkle