-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
66 lines (52 loc) · 1.65 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var async = require('async')
var hyperlog = require('hyperlog')
var merkledag = require('ipfs-dag')
var defined = require('defined')
module.exports = function (db, opts) {
opts = defined(opts, {
hashFunction: undefined,
asyncHashFunction: hash
})
// The inner hyperlog object.
var log = hyperlog(db, opts)
// Hash an opaque value blob and a list of links to an IPFS multihash.
function hash (links, value, cb) {
convertToMerkleDagNode(value, links, doneConversion)
function doneConversion (err, dagNode) {
if (err) return cb(err)
cb(null, dagNode.multihash)
}
}
function keyToMerkleDagNode (key, cb) {
// Look up the node by its key and convert it recursively.
log.get(key, function (err, node) {
if (err) return cb(err)
convertToMerkleDagNode(node.value, node.links, cb)
})
}
// Take an opaque value and list of links and conver them into an IPFS Merkle
// DAG node (recursively).
function convertToMerkleDagNode (value, links, cb) {
// Base class: no links.
if (!links || links.length <= 0) {
var dagNode = new merkledag.Node(value)
process.nextTick(function () {
cb(null, dagNode)
})
return
}
// Retrieve each key as a hyperlog node.
async.map(links, keyToMerkleDagNode, onLinksReady)
function onLinksReady (err, nodes) {
if (err) return cb(err)
// Convert each Merkle DAG node to a Merkle DAG link.
nodes = nodes.map(function (node) {
return node.asLink('')
})
// Create the final Merkle DAG node.
var dagNode = new merkledag.Node(value, nodes)
cb(null, dagNode)
}
}
return log
}