· 7 years ago · Feb 14, 2018, 06:36 PM
1const mirrorFolder = require('mirror-folder')
2const { keyPair } = require('hypercore/lib/crypto')
3const hyperdrive = require('hyperdrive')
4const assert = require('assert')
5const pify = require('pify')
6const ram = require('random-access-memory')
7
8const seed = Buffer(32).fill('hello')
9const { publicKey, secretKey } = keyPair(seed)
10const a = hyperdrive(ram, publicKey, {sparse: false, sparseMetadata: false, secretKey})
11const b = hyperdrive(ram, publicKey, {sparse: false, sparseMetadata: false, secretKey})
12const c = hyperdrive(ram, publicKey, {sparse: false, sparseMetadata: false, })
13
14const replicate = (a, b) => pify((cb) => {
15 const x = a.replicate()
16 const y = b.replicate()
17 x.pipe(y).pipe(x).on('end', cb)
18})()
19
20const readdir = (drive, ...args) => pify(drive.readdir.bind(drive))(...args)
21const mirror = (a, b, ...args) => pify(mirrorFolder)(a, b, ...args)
22const ready = (drive, ...args) => pify(drive.ready.bind(drive))(...args)
23const mkdir = (drive, ...args) => pify(drive.mkdir.bind(drive))(...args)
24const write = (drive, ...args) => pify(drive.writeFile.bind(drive))(...args)
25const read = (drive, ...args) => pify(drive.readFile.bind(drive))(...args)
26
27async function sync(x, y) {
28 if (y.writable) return await mirror({name: '/', fs: x}, {name: '/', fs: y})
29 else return await replicate(x, y)
30}
31
32async function check(a, b) {
33 const invariant = await readdir(a, '/')
34 const proof = await readdir(b, '/')
35 for (const z of invariant) {
36 const x = String(await read(a, '/'+z))
37 const y = String(await read(b, '/'+z))
38 assert(x == y)
39 }
40}
41
42void async function main() {
43 try {
44 const writes = {
45 '/a': Buffer('A'),
46 '/b': Buffer('B'),
47 '/c': Buffer('C'),
48
49 '/1': Buffer('one'),
50 '/2': Buffer('two'),
51 '/3': Buffer('three'),
52 }
53
54 await ready(a)
55 await ready(b)
56 await ready(c)
57
58 for (const filename in writes) {
59 const buffer = writes[filename]
60 await write(a, filename, buffer)
61 }
62
63 await sync(a, b)
64 await sync(b, c)
65
66 await check(a, b)
67 await check(a, c)
68 await check(b, c)
69
70 console.log('ok!');
71 } catch (err) {
72 console.error('error:', err);
73 }
74}()