-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
test.js
98 lines (86 loc) · 1.89 KB
/
test.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
const tape = require('tape')
const crypto = require('crypto')
const MerkleTreeStream = require('./')
tape('hashes', function (t) {
const stream = new MerkleTreeStream({
leaf: function (leaf) {
return hash([leaf.data])
},
parent: function (a, b) {
return hash([a.hash, b.hash])
}
})
stream.write('a')
stream.write('b')
stream.end()
const expected = [{
index: 0,
parent: 1,
hash: hash(['a']),
size: 1,
data: Buffer.from('a')
}, {
index: 2,
parent: 1,
hash: hash(['b']),
size: 1,
data: Buffer.from('b')
}, {
index: 1,
parent: 3,
size: 2,
hash: hash([hash(['a']), hash(['b'])]),
data: null
}]
stream.on('data', function (data) {
t.same(data, expected.shift(), 'hashes data')
})
stream.on('end', function () {
t.same(expected.length, 0, 'no more data')
t.end()
})
})
tape('one root on power of two', function (t) {
const stream = new MerkleTreeStream({
leaf: function (leaf) {
return hash([leaf.data])
},
parent: function (a, b) {
return hash([a.hash, b.hash])
}
})
stream.write('a')
stream.write('b')
stream.write('c')
stream.write('d')
stream.end()
stream.resume()
stream.on('end', function () {
t.same(stream.roots.length, 1, 'one root')
t.end()
})
})
tape('multiple roots if not power of two', function (t) {
const stream = new MerkleTreeStream({
leaf: function (leaf) {
return hash([leaf.data])
},
parent: function (a, b) {
return hash([a.hash, b.hash])
}
})
stream.write('a')
stream.write('b')
stream.write('c')
stream.end()
stream.resume()
stream.on('end', function () {
t.ok(stream.roots.length > 1, 'more than one root')
t.end()
})
})
function hash (list) {
const sha = crypto.createHash('sha256')
for (let i = 0; i < list.length; i++) sha.update(list[i])
return sha.digest()
}