Skip to content

Instantly share code, notes, and snippets.

@jwerle
Created January 31, 2018 21:36
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 jwerle/cacdd320ff36cc6387df5cbcc9218852 to your computer and use it in GitHub Desktop.
Save jwerle/cacdd320ff36cc6387df5cbcc9218852 to your computer and use it in GitHub Desktop.
const mirrorFolder = require('mirror-folder')
const { keyPair } = require('hypercore/lib/crypto')
const hyperdrive = require('hyperdrive')
const assert = require('assert')
const pify = require('pify')
const ram = require('random-access-memory')
const seed = Buffer(32).fill('hello')
const { publicKey, secretKey } = keyPair(seed)
const a = hyperdrive(ram, publicKey, {sparse: false, sparseMetadata: false, secretKey})
const b = hyperdrive(ram, publicKey, {sparse: false, sparseMetadata: false, secretKey})
const c = hyperdrive(ram, publicKey, {sparse: false, sparseMetadata: false, })
const replicate = (a, b) => pify((cb) => {
const x = a.replicate()
const y = b.replicate()
x.pipe(y).pipe(x).on('end', cb)
})()
const readdir = (drive, ...args) => pify(drive.readdir.bind(drive))(...args)
const mirror = (a, b, ...args) => pify(mirrorFolder)(a, b, ...args)
const ready = (drive, ...args) => pify(drive.ready.bind(drive))(...args)
const mkdir = (drive, ...args) => pify(drive.mkdir.bind(drive))(...args)
const write = (drive, ...args) => pify(drive.writeFile.bind(drive))(...args)
const read = (drive, ...args) => pify(drive.readFile.bind(drive))(...args)
async function sync(x, y) {
if (y.writable) return await mirror({name: '/', fs: x}, {name: '/', fs: y})
else return await replicate(x, y)
}
async function check(a, b) {
const invariant = await readdir(a, '/')
const proof = await readdir(b, '/')
for (const z of invariant) {
const x = String(await read(a, '/'+z))
const y = String(await read(b, '/'+z))
assert(x == y)
}
}
void async function main() {
try {
const writes = {
'/a': Buffer('A'),
'/b': Buffer('B'),
'/c': Buffer('C'),
'/1': Buffer('one'),
'/2': Buffer('two'),
'/3': Buffer('three'),
}
await ready(a)
await ready(b)
await ready(c)
for (const filename in writes) {
const buffer = writes[filename]
await write(a, filename, buffer)
}
await sync(a, b)
await sync(b, c)
await check(a, b)
await check(a, c)
await check(b, c)
console.log('ok!');
} catch (err) {
console.error('error:', err);
}
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment