Unverified Commit 29c9360e authored by Aral Balkan's avatar Aral Balkan
Browse files

Replication via WebRTC works

parent 4a33b98b
......@@ -7,8 +7,10 @@ const { Buffer } = require('buffer')
const ram = require('random-access-memory')
const hypercore = require('hypercore')
// Web socket / replication
const webSocketStream = require('websocket-stream')
// WebRTC swarm / replication
var signalhub = require('signalhub')
var swarm = require('webrtc-swarm')
const { discoveryKey } = require('hypercore/lib/crypto')
const pump = require('pump')
// From libsodium.
......@@ -101,4 +103,74 @@ document.addEventListener('DOMContentLoaded', () => {
// Focus the hyphalink field
hyphalinkTextField.focus()
connectionForm.addEventListener('submit', (event) => {
event.preventDefault()
// Attempt to find and replicate the hypercore
// at the requested hyphalink.
const hyphalinkInHex = hyphalinkTextField.value
const hyphalinkBuffer = Buffer.from(hyphalinkInHex, 'hex')
// Calculate the discovery key from the hyphakey.
const discoveryKeyBuffer = discoveryKey(hyphalinkBuffer)
const discoveryKeyInHex = discoveryKeyBuffer.toString('hex')
// Create new in-browser hypercore.
const localCore = hypercore((filename) => ram(filename), hyphalinkBuffer, {
createIfMissing: false,
overwrite: false,
valueEncoding: 'json',
onwrite: (index, data, peer, next) => {
console.log(`Feed: [onWrite] index = ${index}, peer = ${peer}, data:`)
console.log(data)
next()
}
})
const localReadStream = localCore.createReadStream({live: true})
localReadStream.on('data', (data) => {
console.log('[Replicate]', data)
})
localCore.on('ready', () => {
console.log('Local core ready.')
// HACK: Just for now, make sure we only connect once
// (This is an issue with hyperswarm, not sure if it is with WebRTC swarm.)
let connected = false
//
// Join the swarm
//
const webSwarm = swarm(signalhub(discoveryKeyInHex, ['https://localhost:445']))
webSwarm.on('peer', function (remoteWebStream) {
// HACK: only handle first connection
if (connected) return
connected = true
console.log(`WebSwarm [peer for ${hyphalinkInHex} (discovery key: ${discoveryKeyInHex})] About to replicate.`)
// Create the local replication stream.
const localReplicationStream = localCore.replicate({
// TODO: why is Jim’s shopping list example setting encrypt to false?
// The encryption of __what__ does this affect?
// (I haven’t even tested this yet with it set to true to limit the variables.)
encrypt: false,
live: true
})
pump(
remoteWebStream,
localReplicationStream,
remoteWebStream,
(error) => {
console.log(`Pipe closed for ${hyphalinkInHex}`, error && error.message)
}
)
})
})
})
})
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment