git ssb

0+

wanderer🌟 / js-dfinity-radix-tree



Tree: 27ff705435b6458d192cfb844027d32cd144a183

Files: 27ff705435b6458d192cfb844027d32cd144a183 / datastore.js

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

Built with git-ssb-web