Files: 8370f62963962f6038a5541f8b3fbc040babd4e7 / datastore.js
1052 bytesRaw
1 | const Buffer = require('safe-buffer').Buffer |
2 | const crypto = require('node-webcrypto-shim') |
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 | return crypto.subtle.digest({ |
39 | name: 'SHA-256' |
40 | }, buf).then(link => Buffer.from(link.slice(0, HASH_LEN))) |
41 | } |
42 | } |
43 |
Built with git-ssb-web