-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
37 lines (30 loc) · 930 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
35
36
37
const assert = require('assert')
const Buffer = require('safe-buffer').Buffer
const Keccak = require('keccakjs')
// NOTE: it only supports 48 bit lengths
function swarmHashBlock (data, totalLength) {
var hash = new Keccak(256)
var tmp = Buffer.alloc(8)
tmp.writeUIntLE(totalLength, 0, 6)
hash.update(tmp)
hash.update(data)
return Buffer.from(hash.digest('bin'), 'binary')
}
function swarmHash (data) {
assert(Buffer.isBuffer(data))
const length = data.length
if (length <= 4096) {
return swarmHashBlock(data, length)
}
var maxSize = 4096
while ((maxSize * (4096 / 32)) < length) {
maxSize *= (4096 / 32)
}
var innerNodes = []
for (var i = 0; i < length; i += maxSize) {
const size = (maxSize < (length - i)) ? maxSize : (length - i)
innerNodes.push(swarmHash(data.slice(i, i + size)))
}
return swarmHashBlock(Buffer.concat(innerNodes), length)
}
module.exports = swarmHash