-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (53 loc) · 1.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict'
const Base = require('lowdb/adapters/Base')
const Ipfs = require('ipfs')
const crypto = require('crypto')
const algorithm = 'aes-192-cbc'
class IPFSAdapter extends Base {
constructor (ipfs, lastHash, key, iv) {
super('ipfs')
this.key = key || null
this.iv = iv || Buffer.alloc(16, 0)
this.lastHash = lastHash || null
this.ipfs = ipfs
if (this.lastHash) this.defaultValue = this.read()
}
read () {
if (!this.lastHash) return {}
return this.ipfs
.get(this.lastHash)
.then(results => {
const data = this.key
? this.decrypt(results[0].content.toString('utf8'))
: results[0].content.toString('utf8')
return this.deserialize(data)
})
.catch(error => error)
}
write (data) {
return new Promise((resolve) => {
let dataSerialized = null
data._parentHash = this.lastHash
const serialized = this.serialize(data)
dataSerialized = Ipfs.Buffer.from(
this.key ? this.encrypt(serialized) : serialized
)
this.ipfs
.add(dataSerialized)
.then((results) => { resolve(results[0].hash); this.lastHash = results[0].hash })
})
}
encrypt (data) {
const cipher = crypto.createCipheriv(algorithm, this.key, this.iv)
let encrypted = cipher.update(data, 'utf8', 'hex')
encrypted += cipher.final('hex')
return encrypted.toString()
}
decrypt (data) {
const decipher = crypto.createDecipheriv(algorithm, this.key, this.iv)
let decrypted = decipher.update(data, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted.toString()
}
}
module.exports = IPFSAdapter