This repository was archived by the owner on Aug 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdialer.js
86 lines (69 loc) · 2.05 KB
/
dialer.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
'use strict'
const PeerInfo = require('peer-info')
const PeerId = require('peer-id')
const multiaddr = require('multiaddr')
const pull = require('pull-stream/pull')
const take = require('pull-stream/throughs/take')
const collect = require('pull-stream/sinks/collect')
const lp = require('pull-length-prefixed')
const msg = require('./message')
module.exports = (conn, expectedPeerInfo, callback) => {
if (typeof expectedPeerInfo === 'function') {
callback = expectedPeerInfo
expectedPeerInfo = null
console.warn('WARNING: no expected peer info was given, identify will not be able to verify peer integrity')
}
pull(
conn,
lp.decode(),
take(1),
collect((err, data) => {
if (err) {
return callback(err)
}
// connection got closed graciously
if (data.length === 0) {
return callback(new Error('conn was closed, did not receive data'))
}
const input = msg.decode(data[0])
PeerId.createFromPubKey(input.publicKey, (err, id) => {
if (err) {
return callback(err)
}
const peerInfo = new PeerInfo(id)
if (expectedPeerInfo && expectedPeerInfo.id.toB58String() !== id.toB58String()) {
return callback(new Error('invalid peer'))
}
try {
input.listenAddrs
.map(multiaddr)
.forEach((ma) => peerInfo.multiaddrs.add(ma))
} catch (err) {
return callback(err)
}
let observedAddr
try {
observedAddr = getObservedAddrs(input)
} catch (err) {
return callback(err)
}
// Copy the protocols
peerInfo.protocols = new Set(input.protocols)
callback(null, peerInfo, observedAddr)
})
})
)
}
function getObservedAddrs (input) {
if (!hasObservedAddr(input)) {
return []
}
let addrs = input.observedAddr
if (!Array.isArray(addrs)) {
addrs = [addrs]
}
return addrs.map((oa) => multiaddr(oa))
}
function hasObservedAddr (input) {
return input.observedAddr && input.observedAddr.length > 0
}