-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
287 lines (264 loc) Β· 8.93 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/* globals setImmediate */
const EventEmitter = require('events').EventEmitter
const util = require('util')
const methodman = require('methodman')
const SimplePeer = require('simple-peer')
const signalExchange = require('signal-exchange')
const sodi = require('sodi')
const getRoom = require('room-exchange')
// const = require('lodash') // Development Only
const _ =
{ extend: require('lodash.assignin'),
keys: require('lodash.keys'),
without: require('lodash.without'),
uniq: require('lodash.uniq'),
values: require('lodash.values')
}
const noopCallback = (err) => { if (err) console.error(err) }
function setupPeer (swarm, peer) {
function emit () {
swarm.emit.apply(swarm, arguments)
peer.emit.apply(peer, arguments)
}
let meth = methodman(peer)
meth.commands(swarm.rpc, 'init')
meth.on('commands:init', remote => {
remote.publicKey = peer.publicKey
swarm.remotes[peer.publicKey] = remote
emit('remote', remote)
})
meth.on('commands', (remote, id) => {
emit('commands', remote, id)
emit(`commands:${id}`, remote)
})
peer.createStream = (id) => meth.stream(id)
meth.on('stream', (stream, id) => {
// TODO: Relay streams.
emit('substream', stream, id)
emit(`substream:${id}`, stream)
})
peer.meth = meth
}
// Default RPC methods
function RPC (swarm) {
// This can't be a class-like object because dnode
// requires that it be a regular hash object.
let rpc = {}
rpc.ping = cb => cb(null)
rpc.getNetwork = cb => cb(null, swarm.network)
// TODO: verify the request came from this public key
rpc.connect = (proxyKey, pubKey, cb) => {
if (pubKey > swarm.publicKey) {
return cb(new Error('Cannot connect to a larger pub key.'))
}
if (swarm.peers[pubKey]) {
return cb(new Error('Already connecting'))
}
if (pubKey === swarm.publicKey) throw new Error('wtf2')
let _opts = _.extend({trickle: false}, {initiator: true}, swarm.opts)
let peer = new SimplePeer(_opts)
peer.on('signal', signal => {
signal = swarm.encrypt(JSON.stringify(signal), pubKey)
signal.box = signal.box.toString('hex')
signal.nonce = signal.nonce.toString('hex')
swarm.getRemote(proxyKey).proxySignal(pubKey, swarm.publicKey, signal, cb)
})
peer._created = Date.now()
peer.once('connect', createOnConnect(swarm, peer, pubKey))
swarm.peers[pubKey] = peer
}
rpc.inform = (toPublicKey, fromPublicKey, cb) => {
if (!swarm.getRemote(toPublicKey)) {
swarm.once('remote', () => rpc.inform(toPublicKey, fromPublicKey, cb))
} else {
swarm.getRemote(toPublicKey).connect(swarm.publicKey, fromPublicKey, cb)
}
}
rpc.signal = (proxyKey, pubKey, sig, cb) => {
// TODO: Use proxied RPC to force the other side to initiate.
// this way it can deny the request if it is mid-stream.
sig = swarm.decrypt(new Buffer(sig.box, 'hex'), new Buffer(sig.nonce, 'hex'), pubKey)
sig = JSON.parse(sig)
if (sig.type === 'offer' && !swarm.peers[pubKey]) {
let _opts = _.extend({trickle: false}, swarm.opts)
let peer = new SimplePeer(_opts)
peer.on('signal', signal => {
signal = swarm.encrypt(JSON.stringify(signal), pubKey)
signal.box = signal.box.toString('hex')
signal.nonce = signal.nonce.toString('hex')
swarm.getRemote(proxyKey).proxySignal(pubKey, swarm.publicKey, signal, cb)
})
peer._created = Date.now()
peer.once('connect', createOnConnect(swarm, peer, pubKey))
swarm.peers[pubKey] = peer
}
swarm.peers[pubKey].signal(sig)
}
rpc.proxySignal = (toPubKey, fromPubKey, sig, cb) => {
if (!cb) cb = () => {}
swarm.getRemote(toPubKey).signal(swarm.publicKey, fromPubKey, sig, cb)
}
return rpc
}
function Swarm (opts) {
const keypair = opts.keypair || sodi.generate()
const crypto = sodi(keypair)
this.publicKey = crypto.public
this.rpc = RPC(this)
this.maxDelay = 1000
this.opts = opts || {}
this.dnodes = {}
this.remotes = {}
this.peers = {}
this.network = {}
this.relays = {}
this.on('peer', (peer) => {
this.network[peer.publicKey] = null
})
this.on('remote', remote => {
this.ping(remote.publicKey, (err, delay) => {
if (err) return console.error('cannot ping', err)
})
let checkNetwork = () => {
remote.getNetwork((err, net) => {
if (err) return console.error(err)
let netkeys = _.keys(net)
let newpeers = _.without(netkeys, this.publicKey, ..._.keys(this.peers))
newpeers.forEach(pubKey => {
if (pubKey === this.publicKey) throw new Error('wtf1')
if (pubKey < this.publicKey) {
// My key is larger, I need to be the initiator.
let _opts = _.extend({}, {initiator: true}, this.opts)
let peer = new SimplePeer(_opts)
peer.nonce = // big ass random number, to be compared later.
peer.on('signal', signal => {
signal = this.encrypt(JSON.stringify(signal), pubKey)
signal.box = signal.box.toString('hex')
signal.nonce = signal.nonce.toString('hex')
remote.proxySignal(pubKey, this.publicKey, signal)
})
peer._created = Date.now()
peer.once('connect', createOnConnect(this, peer, pubKey))
this.peers[pubKey] = peer
if (err) return console.error(pubKey.slice(0, 9), err)
} else {
// Their key is larger, they need to know about me.
remote.inform(pubKey, this.publicKey, (err) => {
if (err) {
// We don't need to do anything, this likely errored
// because it was already connecting.
}
})
}
})
})
remote._timeout = setTimeout(checkNetwork, 1000 * 30)
}
checkNetwork()
})
window.SimplePeer = SimplePeer
let onSignal = signal => {
if (this.peers[signal.from]) {
// Response for initiated request.
this.peers[signal.from].signal(signal.offer)
} else {
let _opts = _.extend({}, {trickle: false}, this.opts)
let peer = new SimplePeer(_opts)
peer.publicKey = signal.from
peer.once('signal', offer => {
this.sendSignal(signal.from, offer)
})
peer.signal(signal.offer)
peer.once('connect', createOnConnect(this, peer, signal.from))
this.peers[signal.from] = peer
}
}
let sendSignal = signalExchange(keypair, onSignal)
this.sendSignal = sendSignal
this._callQueue = []
sendSignal.onReady = () => {
this._ready = true
this._callQueue.forEach(args => this.call(...args))
this._callQueue = []
this.emit('ready')
}
this.encrypt = crypto.encrypt
this.decrypt = crypto.decrypt
this.sign = crypto.sign
this.joinRoom = (host, room) => {
this.joinRoom = () => { throw new Error('Already in room.') }
// TODO: allow roomHost option to override host
getRoom(room, keypair, (err, data) => {
if (err) return console.error(err)
let keys = data.keys
keys = _.uniq(keys)
while (keys.indexOf(this.publicKey) !== -1) {
keys.splice(keys.indexOf(this.publicKey), 1)
}
sendSignal.ping(keys, (key) => {
this.call(key)
})
})
}
}
util.inherits(Swarm, EventEmitter)
Swarm.prototype.call = function (pubKey, cb) {
if (this.peers[pubKey]) return
if (!cb) cb = noopCallback
if (!this._ready) return this._callQueue.push([pubKey, cb])
var _opts = _.extend({initiator: true, trickle: false}, this.opts)
var peer = new SimplePeer(_opts)
peer.publicKey = pubKey
peer.once('signal', offer => {
peer.__signal = offer
this.sendSignal(pubKey, offer)
})
peer.on('connect', createOnConnect(this, peer, pubKey, cb))
this.peers[pubKey] = peer
}
Swarm.prototype.ping = function (publicKey, cb) {
let start = Date.now()
this.getRemote(publicKey).ping(() => {
let delay = Date.now() - start
this.network[publicKey] = delay
if (cb) cb(null, delay)
})
}
Swarm.prototype.getRemote = function (publicKey) {
return this.remotes[publicKey]
}
Swarm.prototype.activeKeys = function (cb) {
// TODO: parse through the peers in the db as well.
cb(null, Object.keys(this.peers))
}
Swarm.prototype.destroy = function () {
_.values(this.peers).forEach(p => p.destroy())
}
if (process.browser) {
window.Swarm = Swarm
}
module.exports = opts => new Swarm(opts)
function createOnConnect (swarm, peer, pubKey, cb) {
function onclose () {
delete swarm.peers[pubKey]
delete swarm.remotes[pubKey]
delete swarm.network[pubKey]
swarm.emit('disconnect', pubKey, peer)
}
peer.on('error', onclose)
peer.once('close', onclose)
peer.once('stream', stream => { peer.__stream = stream })
peer.once('stream', stream => {
stream.peer = peer
swarm.emit('stream', stream)
})
function _ret () {
if (cb) cb(null, peer)
peer.publicKey = pubKey
// swarm.peers[pubKey] = peer
setupPeer(swarm, peer)
swarm.emit('peer', peer)
if (peer.__stream) peer.emit('stream', peer.__stream)
}
return _ret
}