Skip to content

Commit

Permalink
Merge pull request #27 from cabal-club/fix-handshake
Browse files Browse the repository at this point in the history
fix: reliable key exchange
  • Loading branch information
noffle authored Nov 11, 2018
2 parents 04720e2 + f9ba4c8 commit d86abcb
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions swarm.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,34 @@ module.exports = function (cabal) {
swarm.join(cabal.key.toString('hex'))
swarm.on('connection', function (conn, info) {
var remoteKey
var ended = false

cabal.getLocalKey(function (err, key) {
if (key) {
// send local key to remote
conn.write(new Buffer(key, 'hex'))
conn.once('data', function (rkey) {

// read remote key from remote
conn.once('readable', onReadable)

conn.once('end', function () {
ended = true
})

function onReadable () {
if (ended) return
var rkey = conn.read(32)
if (!rkey) {
conn.once('readable', onReadable)
return
}

remoteKey = rkey.toString('hex')
conn.pause()
cabal._addConnection(remoteKey)
replicate()
})
}
} else {
replicate()
throw new Error('UNEXPECTED STATE: no local key!')
}
})

Expand Down

0 comments on commit d86abcb

Please sign in to comment.