git ssb

0+

wanderer🌟 / js-dfinity-radix-tree



Tree: 588bfeefe36f73792935e70a42db416f2a0d838c

Files: 588bfeefe36f73792935e70a42db416f2a0d838c / datastore.js

1534 bytesRaw
1const Buffer = require('safe-buffer').Buffer
2const crypto = require('crypto')
3const DAG = require('ipld-graph-builder/datastore.js')
4const cbor = require('borc')
5
6const HASH_LEN = 20
7const LINK_TAG = 42
8
9function insertTags (val) {
10 if (Array.isArray(val)) {
11 val = val.map(v => {
12 if (v && v.hasOwnProperty('/')) {
13 return new cbor.Tagged(LINK_TAG, v['/'])
14 } else {
15 return insertTags(v)
16 }
17 })
18 }
19 return val
20}
21
22module.exports = class TreeDAG extends DAG {
23 constructor (dag, decoder = new cbor.Decoder({
24 tags: {
25 42: val => {
26 return {
27 '/': val
28 }
29 }
30 }
31 })) {
32 super(dag)
33 this.decoder = decoder
34 }
35
36 async put (val) {
37 val = insertTags(val)
38 const encoded = cbor.encode(val)
39 const key = await TreeDAG.getMerkleLink(encoded)
40
41 return new Promise((resolve, reject) => {
42 this._dag.put(key, encoded.toString('hex'), () => {
43 resolve(key)
44 })
45 })
46 }
47
48 get (link) {
49 return new Promise((resolve, reject) => {
50 this._dag.get(link, (err, val) => {
51 if (err) {
52 reject(err)
53 } else {
54 val = Buffer.from(val, 'hex')
55 const decoded = this.decoder.decodeFirst(val)
56 resolve(decoded)
57 }
58 })
59 })
60 }
61
62 static isValidLink (link) {
63 return Buffer.isBuffer(link) && link.length === HASH_LEN
64 }
65
66 static getMerkleLink (buf) {
67 const hash = crypto.createHash('sha256')
68 hash.update(buf)
69 return hash.digest().slice(0, HASH_LEN)
70 }
71}
72

Built with git-ssb-web