-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
405 lines (343 loc) · 14.4 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
const crypto = require('crypto')
const { EventEmitter } = require('events')
const WebTorrent = require('webtorrent')
const Zerok = require('zerok')
EventEmitter.defaultMaxListeners = 25
function generateECDHKeys() {
const ecdh = crypto.createECDH('secp256k1');
const publicKey = ecdh.generateKeys();
return { ecdh, publicKey };
}
function computeSharedSecret(theirPublicKey, myECDH) {
const sharedSecret = myECDH.computeSecret(theirPublicKey);
return sharedSecret;
}
function encryptWithSharedSecret(data, sharedSecret) {
// Generate a random initialization vector
const iv = crypto.randomBytes(16);
// Create a cipher using our secret and the AES-256-CBC encryption algorithm
const cipher = crypto.createCipheriv('aes-256-cbc', sharedSecret.slice(0, 32), iv);
// Encrypt the data
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
// Return the initialization vector and the encrypted data
return { iv: iv.toString('hex'), encryptedData: encrypted };
}
function decryptWithSharedSecret(encrypted, sharedSecret, iv) {
// Create a decipher with the shared secret and the IV
const decipher = crypto.createDecipheriv('aes-256-cbc', sharedSecret.slice(0, 32), Buffer.from(iv, 'hex'));
// Decrypt the data
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
// Return the decrypted data
return decrypted;
}
let pubkey = generateECDHKeys().publicKey.toString('hex')
console.log('Public Key: ' + pubkey)
const PREFIX = 'easypeers-'
const Easypeers = function(identifier, args) {
let easypeers = this
if (typeof identifier === 'object') {
easypeers.opts = { ...identifier }
} else {
easypeers.opts = { ...args, identifier }
}
let zerok = new Zerok(easypeers.opts.bitlength)
const events = new EventEmitter()
easypeers.on = events.on.bind(events)
easypeers.once = events.once.bind(events)
easypeers.emit = events.emit.bind(events)
// easypeers.send = (to, data) => {easypeers.emit('_send', (to, data))}
easypeers.off = events.off.bind(events)
easypeers.removeAllListeners = events.removeAllListeners.bind(events)
easypeers.maxPeers = easypeers.opts.maxPeers || 6
easypeers.coverage = easypeers.opts.coverage || 0.33
if (easypeers.maxPeers < 2) easypeers.maxPeers = 2
easypeers.timeout = easypeers.opts.timeout || 30 * 1000
easypeers.webtorrentOpts = easypeers.opts.webtorrentOpts
easypeers.identifier = crypto
.createHash('sha1')
.update(PREFIX + (typeof identifier === 'object' ? identifier.identifier : identifier))
.digest('hex')
easypeers.address = easypeers.opts.address || crypto.randomBytes(20).toString('hex')
// Generate a SHA-256 hash of the swarmId
const hash = crypto.createHash('sha256')
hash.update(easypeers.identifier)
const seed = hash.digest()
easypeers.wires = {}
let seen = {}
let client = new WebTorrent({dht:false, lsd:false, peerId:easypeers.address})
let opts = {
infoHash: easypeers.identifier,
peerId: easypeers.address,
announce: [
easypeers.opts.tracker ? easypeers.opts.tracker : '',
'wss://tracker.peer.ooo',
'wss://tracker.openwebtorrent.com',
],
port: process ? easypeers.opts.port || 6881 : undefined
}
let torrent = client.add(opts)
client.on('warning', err => {
console.warning('Warning', err)
})
client.on('error', err => {
console.error('Error', err)
})
// Function to calculate distance
function calculateDistance(hash1, hash2) {
const hexDigits = '0123456789abcdef'
let distance = ''
for (let i = 0; i < hash1.length; i++) {
const digit1 = hexDigits.indexOf(hash1[i])
const digit2 = hexDigits.indexOf(hash2[i])
const diff = (digit1 - digit2 + 16) % 16
distance += hexDigits[diff]
}
return distance
}
// Function to find closest peers
function findClosestPeers(targetPeerHash, knownPeers, maxPeers, ratio) {
const k = Math.round(maxPeers * ratio) // Calculate the number of closest peers based on the ratio
// Calculate distances
const distances = knownPeers.map(peer => ({ peer, distance: calculateDistance(targetPeerHash, peer) }))
// Sort by distance
distances.sort((a, b) => a.distance.localeCompare(b.distance, 'en', { numeric: true }))
// Get k closest peers (or less if fewer peers available)
const closestPeers = distances.slice(0, Math.min(k, knownPeers.length)).map(d => d.peer)
// Return subset of closest peers based on maxPeers
return closestPeers.slice(0, maxPeers)
}
easypeers.wireCount = 0
torrent.on("wire", function(wire) {
wire.on('close', ()=>{
easypeers.wireCount--
if(easypeers.wireCount < 0) easypeers.wireCount = 0
delete easypeers.wires[wire.peerId]
if(torrent && torrent.numPeers <= 2 && torrent.numPeers < easypeers.maxPeers
&& easypeers.wireCount < 2 ){
torrent.resume()
torrent.announce[opts.announce]
}
easypeers.peerCount = torrent.numPeers
if(wire._writableState.emitClose && seen[wire.peerId] && new Date().getTime() - seen[wire.peerId].when > new Date().getTime() - (2 * 60 * 1000))
easypeers.emit('disconnect', wire.peerId)
wire.removeAllListeners()
wire = null
})
// Avoid duplicate connections to existing peers
if(easypeers.wires.hasOwnProperty(wire.peerId)) {
wire.destroy()
return
}
// let closestPeerId = getClosestPeer(wire.peerId)
// let furthestPeerId = getFurthestPeer(closestPeerId)
if (easypeers.wireCount < easypeers.maxPeers) {
easypeers.wires[wire.peerId] = wire
easypeers.wires[wire.peerId].use(_easypeers(easypeers.wires[wire.peerId]))
easypeers.wireCount++
easypeers.peerCount = torrent.numPeers
} else {
wire.destroy()
return
}
})
function isValidJSON(json) {
try {
JSON.parse(json)
return true
} catch (e) {
return false
}
}
easypeers.send = (to, data) => {
let message = {}
let sendTo
if (to && data) {
sendTo = to
}
if (data === undefined) {
data = to
}
if (typeof data === 'number') {
data = data.toString()
}
data = data.toString()
if (Buffer.isBuffer(data.message)) {
if(easypeers.opts.debug) console.debug('Received buffer ' + data)
message = Buffer.from(data.message).toString('utf8')
}
// if(Buffer.isBuffer(data)) Buffer.from(data).toString('utf-8')
// data = JSON.stringify(data)
message = {
id: crypto.createHash('sha1').update(data, 'binary').digest('hex') + Math.random(),
has: Object.keys(easypeers.wires),
message: data,
}
message.from = easypeers.address
message.certificate = {
id: zerok.proof(message.id),
from: zerok.proof([message.from]),
message: zerok.proof(message.message),
pubkey: zerok.keypair.publicKey,
}
if (easypeers.opts.debug) console.debug('sendTo: ' + sendTo)
if (sendTo) {
// Direct messaging to specific peer(s)
message.to = [sendTo]
let knownPeers = Object.keys(easypeers.wires)
let closePeers = findClosestPeers(message.to, knownPeers, easypeers.maxPeers, easypeers.coverage)
if (easypeers.debug) console.debug('Sending direct message to ' + message.to + ' via ' + closePeers)
for (let wire of closePeers) {
try {
if (easypeers.wires[wire]) {
easypeers.wires[wire].extended('sw_easypeers', JSON.stringify(message))
if (easypeers.opts.debug) console.debug('Sent message to: ' + wire) // Added logging here
}
} catch (e) {
if (easypeers.debug) console.error(e)
}
}
} else {
// Broadcast messaging to all peers
let knownPeers = Object.keys(easypeers.wires)
if (easypeers.debug) console.debug('Sending broadcast message to all peers')
for (let wire of knownPeers) {
try {
if (easypeers.wires[wire]) {
easypeers.wires[wire].extended('sw_easypeers', JSON.stringify(message))
if (easypeers.opts.debug) console.debug('Sent message to: ' + wire) // Added logging here
}
} catch (e) {
if (easypeers.debug) console.error(e)
}
}
}
}
setInterval(()=>{
torrent.announce[opts.announce]
}, easypeers.timeout)
let sentMessages = {}
let seenMessages = {}
let _easypeers = () => {
let swEasypeers = function(wire) {
easypeers.wires[wire.peerId].extendedHandshake.keys = 'SEA Pairs' // establish SEA pairs here
this.onHandshake = (infoHash, peerId, extensions) => {
seen[wire.peerId] = {when: new Date().getTime()}
}
this.onExtendedHandshake = (handshake) => {
if(new Date().getTime() - seen[wire.peerId].when < new Date().getTime() - (5 * 60 * 1000))
easypeers.emit('connect', wire.peerId)
}
this.onMessage = function(message) {
if (easypeers.opts.debug) console.debug('Received raw message:', message);
message = message.toString();
if (easypeers.opts.debug) console.debug(message);
try {
message = message.substring(message.indexOf(':') + 1);
if (easypeers.opts.debug) console.debug('Parsed message before conversion:', message);
message = JSON.parse(message, (key, value) => {
if (typeof value === 'string' && value.startsWith('`') && value.endsWith('`')) {
const strippedValue = value.slice(1, -1);
try {
const parsedObject = JSON.parse(strippedValue);
if (typeof parsedObject === 'object' && parsedObject !== null) {
return parsedObject; // Convert back to object
}
} catch {
// Ignore the value if it's not a valid JSON object
}
}
return value;
});
if (
!zerok.verify(message.id, message.certificate.id, message.certificate.pubkey) ||
!zerok.verify(message.from, message.certificate.from, message.certificate.pubkey) ||
!zerok.verify(message.message, message.certificate.message, message.certificate.pubkey)
) {
return
}
if (!seenMessages[message.id]) {
seenMessages[message.id] = true
} else {
if (easypeers.opts.debug) console.debug(`Duplicate message ${message.id} received, ignoring`)
return
}
// Check if the message has a 'to' field containing the local peer's address
if (message.to) {
if(!Array.isArray(message.to)) message.to = [message.to]
if (message.to.includes(easypeers.address)) {
// Process direct message
if (easypeers.opts.debug) console.debug(`Received direct message from ${message.from}:`, message.message)
// Emit a 'directMessage' event with the direct message
easypeers.emit('message', {
from: message.from,
message: Buffer.from(message.message).toString('utf-8')
})
return // Stop processing further for direct messages
} else {
// If the current peer is not the intended recipient, only forward the message without emitting it
message.has.push(easypeers.address) // immediately add self to "has" list of message
let peers = Object.keys(easypeers.wires)
for (let i = 0; i < peers.length; i++) {
let peer = peers[i]
if (peer === message.from || message.has.includes(peer)) {
if (easypeers.opts.debug) console.debug(`Skipping peer ${peer} for message ${message.id}`)
} else {
if (easypeers.opts.debug) console.debug(`Forwarding message ${message.id} to peer ${peer}`)
if (!sentMessages[message.id]) {
sentMessages[message.id] = []
}
sentMessages[message.id].push(peer)
easypeers.wires[peer].extended('sw_easypeers', JSON.stringify(message), () => {
// Assuming 'messageAck' is the event for receiving an acknowledgment
easypeers.wires[peer].on('messageAck', (ack) => {
if (ack === message.id) {
if (easypeers.opts.debug) console.debug(`Received acknowledgment from peer ${peer} for message ${message.id}`)
}
})
})
}
}
return
}
}
// If the message does not have a 'to' property or if it's not an array,
// emit the message and forward it to other peers
if (easypeers.opts.debug) console.debug(`Received message from ${message.from}:`, message.message)
if (typeof message.message === 'string') {
if (Buffer.isBuffer(message.mmessage)) message.message = message.message.toString('utf-8')
easypeers.emit('message', message)
}
message.has.push(easypeers.address) // immediately add self to "has" list of message
let peers = Object.keys(easypeers.wires)
for (let i = 0; i < peers.length; i++) {
let peer = peers[i]
if (peer === message.from || message.has.includes(peer)) {
if (easypeers.opts.debug) console.debug(`Skipping peer ${peer} for message ${message.id}`)
} else {
if (easypeers.opts.debug) console.debug(`Forwarding message ${message.id} to peer ${peer}`)
if (!sentMessages[message.id]) {
sentMessages[message.id] = []
}
sentMessages[message.id].push(peer)
easypeers.wires[peer].extended('sw_easypeers', JSON.stringify(message), () => {
// Assuming 'messageAck' is the event for receiving an acknowledgment
easypeers.wires[peer].on('messageAck', (ack) => {
if (ack === message.id) {
if (easypeers.opts.debug) console.debug(`Received acknowledgment from peer ${peer} for message ${message.id}`)
}
})
})
}
}
} catch (err) {
// handle error
}
}
}
swEasypeers.prototype.name = 'sw_easypeers'
return swEasypeers
}
}
module.exports = Easypeers