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