This repository has been archived by the owner on Jul 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
swarm.js
191 lines (152 loc) · 4.57 KB
/
swarm.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
var events = require('events')
var subleveldown = require('subleveldown')
var webrtcSwarm = require('webrtc-swarm')
var signalhub = require('signalhub')
var hyperlog = require('hyperlog')
var through = require('through2')
var protobuf = require('protocol-buffers')
var multiline = require('multiline')
var nets = require('nets')
var messages = protobuf(multiline(function () { /*
message SignedMessage {
optional bytes signature = 1;
required bytes message = 2;
}
message Message {
optional string username = 1;
optional string channel = 2;
optional uint64 timestamp = 3;
optional string text = 4;
}
*/ }))
module.exports = createSwarm
function createSwarm (db, defaultOpts) {
var swarm = new events.EventEmitter()
var logs = {}
swarm.logs = logs
var processor
var sign
var verify
if (!defaultOpts) defaultOpts = {}
if (!defaultOpts.hubs) {
defaultOpts.hubs = [
'https://signalhub.mafintosh.com' // mafintosh
// 'https://instant.io:8080' // feross
]
}
var remoteConfigUrl = defaultOpts.remoteConfigUrl || 'https://instant.io/rtcConfig' // thanks feross
swarm.changes = function (name) {
return logs[name] ? logs[name].changes : 0
}
/**
* fn should be a function that takes the args `data, callback`.
* The `callback` takes the args `err, signature`.
*/
swarm.sign = function (fn) {
sign = fn
}
/**
* fn should be a function that takes the args `username, signature, callback`.
* The `callback` is called with `err, valid` with valid being truthy if the signature was verified.
*/
swarm.verify = function (fn) {
verify = fn
}
swarm.process = function (fn) {
processor = fn
Object.keys(logs).forEach(function (name) {
startProcessor(logs[name])
})
}
swarm.removeChannel = function (name) {
var log = logs[name]
if (!log) return
delete logs[name]
if (log.processing) log.processing.destroy()
log.peers.forEach(function (p) {
p.destroy()
})
}
swarm.addChannel = function (name) {
if (logs[name]) return
getRemoteConfig(remoteConfigUrl, function (err, config) {
if (err) console.error('skipping remote config', err)
if (config) defaultOpts.config = config
var log = logs[name] = hyperlog(subleveldown(db, name))
var id = 'friends-' + name
var hub = signalhub(id, defaultOpts.hubs)
var sw = webrtcSwarm(hub, defaultOpts)
log.peers = []
sw.on('peer', function (p, id) {
var stream = log.replicate({ live: true })
log.peers.push(p)
p.on('close', function () {
var i = log.peers.indexOf(p)
if (i > -1) log.peers.splice(i, 1)
})
swarm.emit('peer', p, name, id, stream)
stream.on('push', function () {
swarm.emit('push', name)
})
stream.on('pull', function () {
swarm.emit('pull', name)
})
p.pipe(stream).pipe(p)
})
if (processor) startProcessor(log)
})
}
swarm.send = function (message, cb) {
var addMessage = function (m, sig) {
var ch = message.channel || 'friends'
swarm.addChannel(ch)
var log = logs[ch]
log.heads(function (err, heads) {
if (err) return cb(err)
log.add(heads, messages.SignedMessage.encode({ signature: sig, message: m }), cb)
})
}
var m = messages.Message.encode(message)
if (sign) {
sign(m, function (err, sig) {
if (err) return cb(err)
addMessage(m, sig)
})
return
}
addMessage(m, null)
}
function startProcessor (log) {
log.ready(function () {
if (log.processing) return
var rs = log.processing = log.createReadStream({
live: true,
since: Math.max(log.changes - 500, 0)
})
rs.pipe(through.obj(function (data, enc, cb) {
if (data.value.toString()[0] === '{') return cb() // old stuff
var val = messages.SignedMessage.decode(data.value)
var m = messages.Message.decode(val.message)
var u = m.username
m.change = data.change
if (verify) {
verify(u, val.message, val.signature, function (_, valid) {
m.valid = !!valid
processor(m, cb)
})
return
}
m.valid = false
processor(m, cb)
}))
})
}
return swarm
}
// get remote webrtc config (ice/stun/turn)
function getRemoteConfig (remoteConfigUrl, cb) {
nets({ url: remoteConfigUrl, json: true }, function gotConfig (err, resp, config) {
if (err || resp.statusCode > 299) config = undefined // ignore errors
cb(null, config)
})
}