Files: 944bce06413fb71fd0d491577015823816a6e618 / datastore.js
1382 bytesRaw
1 | const Buffer = require('safe-buffer').Buffer |
2 | const crypto = require('crypto') |
3 | const DAG = require('ipld-graph-builder/datastore.js') |
4 | const cbor = require('borc') |
5 | |
6 | const HASH_LEN = 20 |
7 | const LINK_TAG = 42 |
8 | |
9 | module.exports = class TreeDAG extends DAG { |
10 | async put (val) { |
11 | if (val[1]) { |
12 | val[1] = new cbor.Tagged(LINK_TAG, val[1]['/']) |
13 | } |
14 | if (val[2]) { |
15 | val[2] = new cbor.Tagged(LINK_TAG, val[2]['/']) |
16 | } |
17 | |
18 | const encoded = cbor.encode(val) |
19 | const key = await TreeDAG.getMerkleLink(encoded) |
20 | |
21 | return new Promise((resolve, reject) => { |
22 | this._dag.put(key, encoded.toString('hex'), () => { |
23 | resolve(key) |
24 | }) |
25 | }) |
26 | } |
27 | |
28 | get (link) { |
29 | return new Promise((resolve, reject) => { |
30 | this._dag.get(link, (err, val) => { |
31 | if (err) { |
32 | reject(err) |
33 | } else { |
34 | val = Buffer.from(val, 'hex') |
35 | const decoded = cbor.decode(val) |
36 | if (decoded[1]) { |
37 | decoded[1]['/'] = decoded[1].value |
38 | } |
39 | if (decoded[2]) { |
40 | decoded[2]['/'] = decoded[2].value |
41 | } |
42 | resolve(decoded) |
43 | } |
44 | }) |
45 | }) |
46 | } |
47 | |
48 | static isValidLink (link) { |
49 | return Buffer.isBuffer(link) && link.length === HASH_LEN |
50 | } |
51 | |
52 | static getMerkleLink (buf) { |
53 | const hash = crypto.createHash('sha256') |
54 | hash.update(buf) |
55 | return hash.digest().slice(0, HASH_LEN) |
56 | } |
57 | } |
58 |
Built with git-ssb-web