Skip to content

Instantly share code, notes, and snippets.

@samuelmaddock
Last active January 14, 2018 03:33
Show Gist options
  • Save samuelmaddock/22acdbecd7ae11e4c483c9c453eec1b2 to your computer and use it in GitHub Desktop.
Save samuelmaddock/22acdbecd7ae11e4c483c9c453eec1b2 to your computer and use it in GitHub Desktop.
Swarm remote connection test
export ARCHIVE_KEY='deadbeafdeadbeafdeadbeafdeadbeafdeadbeafdeadbeafdeadbeafdeadbeaf'
const Dat = require('dat-node')
const swarmDefaults = require('dat-swarm-defaults')
const ram = require('random-access-memory')
const { ARCHIVE_KEY } = process.env
if (!ARCHIVE_KEY) {
throw new Error(`Missing 'ARCHIVE_KEY' environment variable`)
}
const archiveKey = new Buffer(ARCHIVE_KEY, 'hex')
console.log(`archiveKey=${archiveKey.toString('hex')}`)
Dat(ram, {
key: archiveKey
}, (err, dat) => {
if (err) {
console.error('Error', err)
return
}
dat.joinNetwork(swarmDefaults(), err => {
if (err) {
console.error(err)
return
}
})
})
const os = require('os')
const swarmDefaults = require('dat-swarm-defaults')
const discoverySwarm = require('discovery-swarm')
const sodium = require('sodium-universal')
const { ARCHIVE_KEY } = process.env
if (!ARCHIVE_KEY) {
throw new Error(`Missing 'ARCHIVE_KEY' environment variable`)
}
const isHosting = process.argv[2] === '1'
const archiveKey = new Buffer(ARCHIVE_KEY, 'hex')
console.log(`archiveKey=${archiveKey.toString('hex')}`)
const HYPERCORE = new Buffer('hypercore')
const digest = new Buffer(32)
sodium.crypto_generichash(digest, HYPERCORE, archiveKey)
const discoveryKey = digest
console.info(`${isHosting ? 'Announcing' : 'Joining'} swarm ${discoveryKey.toString('hex')}`);
const swarm = discoverySwarm(swarmDefaults({
hash: false
}))
swarm.listen(3282)
swarm.join(discoveryKey, { announce: isHosting })
swarm.on('error', function(){
console.log('Error, changing ports')
swarm.listen(0)
})
swarm.on('peer', peer => {
console.log(`Found peer ${peer.host}:${peer.port}`)
})
swarm.on('connection', socket => {
const addr = socket.remoteAddress
const port = socket.remotePort
const ip = `${addr}:${port}`;
console.log(`New conn ${ip}`)
socket.once('close', () => console.log(`Rip ${ip}`))
socket.once('data', data => console.log(data.toString()))
socket.write(new Buffer(`Hello from ${os.hostname()}`))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment