Skip to content

Instantly share code, notes, and snippets.

@josselinchevalay
Created October 6, 2019 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josselinchevalay/9efdb379cdbb70fff5c59f692b91126e to your computer and use it in GitHub Desktop.
Save josselinchevalay/9efdb379cdbb70fff5c59f692b91126e to your computer and use it in GitHub Desktop.
lowdb + ipfs
const Base = require('./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 => {
let 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(async (resolve, reject) => {
let dataSerialized = null
data._parentHash = this.lastHash
let serialized = this.serialize(data)
dataSerialized = Ipfs.Buffer.from(
this.key ? this.encrypt(serialized) : serialized
)
const results = await this.ipfs.add(dataSerialized)
this.lastHash = results[0].hash
resolve(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
const IPFSAdapter = require('../../src/adapters/Ipfs')
const IPFS = require('ipfs')
const path = require('path')
const os = require('os')
const hat = require('hat')
const crypto = require('crypto')
const obj = { a: 1, _parentHash: null }
const password = 'mySecretTest'
const salt = 'MySalt'
const keyLength = 24
describe('simple test', () => {
it('should read and write', async () => {
const node = await IPFS.create()
const ipfs = new IPFSAdapter(node)
expect(ipfs.read()).toEqual({})
await ipfs.write(obj)
const result = await ipfs.read()
expect(result).toEqual(obj)
})
it('should read and write with key', async () => {
const node = await IPFS.create({
repo: path.join(os.tmpdir(), 'ipfs-repo-' + hat()),
init: { bits: 512 },
config: {
Addresses: {
Swarm: []
}
},
preload: { enabled: false }
})
const key = crypto.scryptSync(password, salt, keyLength)
const ipfs = new IPFSAdapter(node, null, key)
expect(ipfs.read()).toEqual({})
await ipfs.write(obj)
const result = await ipfs.read()
expect(result).toEqual(obj)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment