Files: 806b9f80cab0da81d7e98a62754b80167fe58296 / datastore.js
1030 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 | const encoded = cbor.encode(val) |
10 | const key = await TreeDAG.getMerkleLink(encoded) |
11 | |
12 | return new Promise((resolve, reject) => { |
13 | this._dag.put(key, encoded.toString('hex'), () => { |
14 | resolve(key) |
15 | }) |
16 | }) |
17 | } |
18 | |
19 | get (link) { |
20 | return new Promise((resolve, reject) => { |
21 | this._dag.get(link, (err, val) => { |
22 | if (err) { |
23 | reject(err) |
24 | } else { |
25 | val = Buffer.from(val, 'hex') |
26 | const decoded = cbor.decode(val) |
27 | resolve(decoded) |
28 | } |
29 | }) |
30 | }) |
31 | } |
32 | |
33 | static isValidLink (link) { |
34 | return Buffer.isBuffer(link) && link.length === HASH_LEN |
35 | } |
36 | |
37 | static getMerkleLink (buf) { |
38 | const hash = crypto.createHash('sha256') |
39 | hash.update(buf) |
40 | return hash.digest().slice(0, HASH_LEN) |
41 | } |
42 | } |
43 |
Built with git-ssb-web