Chainlink

Discharge

chainlink 2022 spring hackathon winner!$7,500 Filecoin - On the Tools

Free, secure, unlimited data storage powered by FileCoin.

Discharge
Discharge

Code Snippets

> File Encryption using AES-256-CBC Cipher

1export async function encrypt(path: string, key: string, out: string) {
2  const name = path.substring(path.lastIndexOf('\\') + 1)
3  const bytes =
4    key.length >= 32
5      ? Buffer.from(key).slice(0, 32)
6      : Buffer.from(key).slice(0, key.length) + '-'.repeat(32 - key.length)
7  if (bytes.length != 32)
8    throw new Error('Encryption key is unstable in estuary.ts: encrypt()')
9  const iv = crypto.randomBytes(IV_LENGTH)
10  const cipher = crypto.createCipheriv('aes-256-cbc', bytes, iv)
11  const input = fs.createReadStream(path)
12  const output = fs.createWriteStream(join(out, name + '.enc'))
13  await new Promise((fulfill, reject) =>
14    output.write(iv, (err: any) => {
15      if (err) reject(err)
16      else fulfill(null)
17    })
18  )
19  const pipe = pipeline(input, cipher, output, (err: any) => console.error(err))
20  await new Promise(fulfill => pipe.on('finish', fulfill))
21  return join(out, name + '.enc')
22}

> Asynchronous Data Handling with Electron

1ipcMain.on('app:file:download', async (event, data) => {
2    const file = data.file
3    const directory = data.directory.replace(/\//g, '\\')
4    const path = await readItem(file, join(app.getPath('userData'), 'Temp'))
5    if (!fs.existsSync(join(preferences.get('path'), directory)))
6      fs.mkdirSync(join(preferences.get('path'), directory))
7    await decrypt(
8      path,
9      preferences.get('key'),
10      join(preferences.get('path'), directory)
11    )
12    event.reply(`client:file:loaded:${directory + file.name}`)
13  })

> Downloading Files from the Web

1export async function readItem(file: any, path: string) {
2  const res = await fetch(`https://dweb.link/ipfs/${file.cid}`)
3  const dest = fs.createWriteStream(join(path, file.name))
4  const data = res.body as fs.ReadStream
5  const pipe = pipeline(data, dest, (err: any) => console.error(err))
6  await new Promise(fulfill => pipe.on('finish', fulfill))
7  return join(path, file.name)
8}