git ssb

0+

wanderer🌟 / js-dfinity-radix-tree



Tree: dc4dcb9b9fa76eee440632309af8c4a27fd14f84

Files: dc4dcb9b9fa76eee440632309af8c4a27fd14f84 / datastore.js

1030 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 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