-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
431 lines (369 loc) · 12.3 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
'use strict'
var pull = require('pull-stream')
var Notify = require('pull-notify')
var valid = require('muxrpc-validation')({})
var u = require('./util')
var ref = require('ssb-ref')
var ping = require('pull-ping')
var stats = require('statistics')
var Schedule = require('./schedule')
var Init = require('./init')
var AtomicFile = require('atomic-file')
var fs = require('fs')
var path = require('path')
var deepEqual = require('deep-equal')
function isFunction (f) {
return 'function' === typeof f
}
function stringify(peer) {
if(peer.host && peer.port && peer.key)
return [peer.host, peer.port, peer.key].join(':')
else
return peer.address
}
function isObject (o) {
return o && 'object' == typeof o
}
function toBase64 (s) {
if(isString(s)) return s.substring(1, s.indexOf('.'))
else s.toString('base64') //assume a buffer
}
function isString (s) {
return 'string' == typeof s
}
function coearseAddress (address) {
if(isObject(address)) {
if(ref.isAddress(address.address))
return address.address
var protocol = 'net'
if (address.host && address.host.endsWith(".onion"))
protocol = 'onion'
return [protocol, address.host, address.port].join(':') +'~'+['shs', toBase64(address.key)].join(':')
}
return address
}
/*
Peers : [{
//modern:
address: <multiserver address>,
//legacy
key: id,
host: ip,
port: int,
//to be backwards compatible with patchwork...
announcers: {length: int}
//TODO: availability
//availability: 0-1, //online probability estimate
//where this peer was added from. TODO: remove "pub" peers.
source: 'pub'|'manual'|'local'
}]
*/
module.exports = {
name: 'gossip',
version: '1.0.0',
manifest: require('./manifest.json'),
permissions: {
anonymous: {allow: ['ping']}
},
init: function (server, config) {
var notify = Notify()
var closed = false, closeScheduler
var conf = config.gossip || {}
var gossipJsonPath = path.join(config.path, 'gossip.json')
var stateFile = AtomicFile(gossipJsonPath)
var status = {}
//Known Peers
var peers = []
function getPeer(id) {
return u.find(peers, function (e) {
return e && e.key === id
})
}
function simplify (peer) {
return {
address: peer.address || coearseAddress(peer),
source: peer.source,
state: peer.state, stateChange: peer.stateChange,
failure: peer.failure,
client: peer.client,
stats: {
duration: peer.duration || undefined,
rtt: peer.ping ? peer.ping.rtt : undefined,
skew: peer.ping ? peer.ping.skew : undefined,
}
}
}
server.status.hook(function (fn) {
var _status = fn()
_status.gossip = status
peers.forEach(function (peer) {
if(peer.stateChange + 3e3 > Date.now() || peer.state === 'connected')
status[peer.key] = simplify(peer)
})
return _status
})
server.close.hook(function (fn, args) {
closed = true
closeScheduler()
for(var id in server.peers)
server.peers[id].forEach(function (peer) {
peer.close(true)
})
return fn.apply(this, args)
})
var timer_ping = 5*6e4
function setConfig(name, value) {
config.gossip = config.gossip || {}
config.gossip[name] = value
var cfgPath = path.join(config.path, 'config')
var existingConfig = {}
// load ~/.ssb/config
try { existingConfig = JSON.parse(fs.readFileSync(cfgPath, 'utf-8')) }
catch (e) {}
// update the plugins config
existingConfig.gossip = existingConfig.gossip || {}
existingConfig.gossip[name] = value
// write to disc
fs.writeFileSync(cfgPath, JSON.stringify(existingConfig, null, 2), 'utf-8')
}
var gossip = {
wakeup: 0,
peers: function () {
return peers
},
get: function (addr) {
//addr = ref.parseAddress(addr)
if(ref.isFeed(addr)) return getPeer(addr)
else if(ref.isFeed(addr.key)) return getPeer(addr.key)
else throw new Error('must provide id:'+JSON.stringify(addr))
// return u.find(peers, function (a) {
// return (
// addr.port === a.port
// && addr.host === a.host
// && addr.key === a.key
// )
// })
},
connect: function (addr, cb) {
if(!addr) return cb(new Error('ssb-gossip.connect: address, or peer id must be provided'))
if(ref.isFeed(addr)) {
const id = addr
addr = gossip.get(addr)
if(!addr) return cb(new Error('no known address for peer:'+id))
}
if(!ref.isAddress(addr.address))
addr = ref.parseAddress(addr)
if (!addr || typeof addr != 'object')
return cb(new Error('first param must be an address'))
if(!addr.address)
if(!addr.key) return cb(new Error('address must have ed25519 key'))
// add peer to the table, incase it isn't already.
server.emit('log:info', ['ssb-server', stringify(addr), 'CONNECTING'])
gossip.add(addr, 'manual')
var p = gossip.get(addr)
if(!p) return cb()
p.stateChange = Date.now()
p.state = 'connecting'
server.connect(p.address, function (err, rpc) {
if (err) {
p.error = err.stack
p.state = undefined
p.failure = (p.failure || 0) + 1
p.stateChange = Date.now()
notify({ type: 'connect-failure', peer: p })
server.emit('log:info', ['ssb-server', stringify(p), 'ERR', (err.message || err)])
p.duration = stats(p.duration, 0)
return (cb && cb(err))
}
else {
delete p.error
p.state = 'connected'
p.failure = 0
}
cb && cb(null, rpc)
})
},
disconnect: function (addr, cb) {
var peer = gossip.get(addr)
peer.state = 'disconnecting'
peer.stateChange = Date.now()
if(!peer || !peer.disconnect) cb && cb()
else peer.disconnect(true, function (err) {
peer.stateChange = Date.now()
cb && cb()
})
},
changes: function () {
return notify.listen()
},
//add an address to the peer table.
add: valid.sync(function (addr, source) {
if(isObject(addr)) {
//console.log(addr)
addr.address = coearseAddress(addr)
}
else if(ref.isAddress(addr)) {
addr = {address: addr, key: ref.getKeyFromAddress(addr)}
}
else {
var _addr = ref.parseAddress(addr)
if(!_addr) throw new Error('not a valid address:'+addr)
_addr.address = addr
addr = _addr
}
if(!ref.isAddress(addr.address) /*&& !ref.isAddress(addr)*/)
throw new Error('not a valid address:' + JSON.stringify(addr))
// check that this is a valid address, and not pointing at self.
if(addr.key === server.id) return
var f = gossip.get(addr)
if(!f) {
// new peer
addr.source = source
addr.announcers = 1
addr.duration = addr.duration || null
peers.push(addr)
notify({ type: 'discover', peer: addr, source: source || 'manual' })
return addr
} else if (source === 'friends' || source === 'local') {
// this peer is a friend or local, override old source to prioritize gossip
f.source = source
}
//don't count local over and over
else if(f.source != 'local')
f.announcers ++
return f
}, 'string|object', 'string?'),
remove: function (addr) {
var peer = gossip.get(addr)
var index = peers.indexOf(peer)
if (~index) {
peers.splice(index, 1)
notify({ type: 'remove', peer: peer })
}
},
ping: function (opts) {
var timeout = config.timers && config.timers.ping || 5*60e3
//between 10 seconds and 30 minutes, default 5 min
timeout = Math.max(10e3, Math.min(timeout, 30*60e3))
return ping({timeout: timeout})
},
reconnect: function () {
for(var id in server.peers)
if(id !== server.id) //don't disconnect local client
server.peers[id].forEach(function (peer) {
peer.close(true)
})
return gossip.wakeup = Date.now()
},
enable: valid.sync(function (type) {
type = type || 'global'
setConfig(type, true)
if(type === 'local' && server.local && server.local.init)
server.local.init()
return 'enabled gossip type ' + type
}, 'string?'),
disable: valid.sync(function (type) {
type = type || 'global'
setConfig(type, false)
return 'disabled gossip type ' + type
}, 'string?'),
help: function () { return require('./help') }
}
closeScheduler = Schedule (gossip, config, server)
Init (gossip, config, server)
//get current state
server.on('rpc:connect', function (rpc, isClient) {
// if we're not ready, close this connection immediately
if (!server.ready() && rpc.id !== server.id) return rpc.close()
var peer = getPeer(rpc.id)
//don't track clients that connect, but arn't considered peers.
//maybe we should though?
if(!peer) {
if(rpc.id !== server.id) {
server.emit('log:info', ['ssb-server', rpc.id, 'Connected'])
rpc.on('closed', function () {
server.emit('log:info', ['ssb-server', rpc.id, 'Disconnected'])
})
}
return
}
status[rpc.id] = simplify(peer)
server.emit('log:info', ['ssb-server', stringify(peer), 'PEER JOINED'])
//means that we have created this connection, not received it.
peer.client = !!isClient
peer.state = 'connected'
peer.stateChange = Date.now()
peer.disconnect = function (err, cb) {
if(isFunction(err)) cb = err, err = null
rpc.close(err, cb)
}
if(isClient) {
//default ping is 5 minutes...
var pp = ping({serve: true, timeout: timer_ping}, function (_) {})
peer.ping = {rtt: pp.rtt, skew: pp.skew}
pull(
pp,
rpc.gossip.ping({timeout: timer_ping}, function (err) {
if(err && err.name === 'TypeError') peer.ping.fail = true
}),
pp
)
}
rpc.on('closed', function () {
delete status[rpc.id]
server.emit('log:info', ['ssb-server', stringify(peer),
['DISCONNECTED. state was', peer.state, 'for',
(new Date() - peer.stateChange)/1000, 'seconds'].join(' ')])
//track whether we have successfully connected.
//or how many failures there have been.
var since = peer.stateChange
peer.stateChange = Date.now()
// if(peer.state === 'connected') //may be "disconnecting"
peer.duration = stats(peer.duration, peer.stateChange - since)
peer.state = undefined
notify({ type: 'disconnect', peer: peer })
})
notify({ type: 'connect', peer: peer })
})
var last
stateFile.get(function (err, ary) {
last = ary || []
if(Array.isArray(ary))
ary.forEach(function (v) {
delete v.state
// don't add local peers (wait to rediscover)
// adding peers back this way means old format gossip.json
// will be updated to having proper address values.
if(v.source !== 'local') {
gossip.add(v, 'stored')
}
})
})
var int = setInterval(function () {
var copy = peers.filter(function (e) {
return e.source !== 'local'
}).map(function (e) {
var o = {}
for(var k in e) {
if(k !== 'state') o[k] = e[k]
}
//try to ensure that the peer always has host and port
//so that the output file is understood by previous versions
//of scuttlebutt.
if(!o.host || !o.port) {
var _addr = ref.parseAddress(e.address)
o.host = _addr.host
o.port = _addr.port
}
return o
})
if(deepEqual(copy, last)) return
last = copy
stateFile.set(copy, function(err) {
if (err) console.log(err)
})
}, 10*1000)
if(int.unref) int.unref()
return gossip
}
}