git ssb

0+

wanderer🌟 / js-dfinity-radix-tree



Tree: e2cd325fdcc6c86a830407f0c4c8638f3a5ad25a

Files: e2cd325fdcc6c86a830407f0c4c8638f3a5ad25a / datastore.js

1052 bytesRaw
1const Buffer = require('safe-buffer').Buffer
2const crypto = require('node-webcrypto-shim')
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 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