This repository has been archived by the owner on Feb 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
121 lines (98 loc) · 2.65 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
'use strict'
const bs58 = require('bs58')
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
function getB58Str (peer) {
let b58Str
if (typeof peer === 'string') {
b58Str = peer
} else if (Buffer.isBuffer(peer)) {
b58Str = bs58.encode(peer).toString()
} else if (PeerId.isPeerId(peer)) {
b58Str = peer.toB58String()
} else if (PeerInfo.isPeerInfo(peer)) {
b58Str = peer.id.toB58String()
} else {
throw new Error('not valid PeerId or PeerInfo, or B58Str')
}
return b58Str
}
class PeerBook {
constructor () {
this._peers = {}
}
// checks if peer exists
// peer can be PeerId, b58String or PeerInfo
has (peer) {
const b58Str = getB58Str(peer)
return Boolean(this._peers[b58Str])
}
/**
* Stores a peerInfo, if already exist, merges the new into the old.
*
* @param {PeerInfo} peerInfo
* @param {replace} boolean
* @returns {PeerInfo}
*/
put (peerInfo, replace) {
const localPeerInfo = this._peers[peerInfo.id.toB58String()]
// insert if doesn't exist or replace if replace flag is true
if (!localPeerInfo || replace) {
this._peers[peerInfo.id.toB58String()] = peerInfo
return peerInfo
}
// peerInfo.replace merges by default if none to replace are passed
peerInfo.multiaddrs.forEach((ma) => localPeerInfo.multiaddrs.add(ma))
// pass active connection state
const ma = peerInfo.isConnected()
if (ma) {
localPeerInfo.connect(ma)
}
// pass known protocols
peerInfo.protocols.forEach((p) => localPeerInfo.protocols.add(p))
if (!localPeerInfo.id.privKey && peerInfo.id.privKey) {
localPeerInfo.id.privKey = peerInfo.id.privKey
}
if (!localPeerInfo.id.pubKey && peerInfo.id.pubKey) {
localPeerInfo.id.pubKey = peerInfo.id.pubKey
}
return localPeerInfo
}
/**
* Get the info to the given PeerId, PeerInfo or b58Str id
*
* @param {PeerId} id
* @returns {PeerInfo}
*/
get (peer) {
const b58Str = getB58Str(peer)
const peerInfo = this._peers[b58Str]
if (peerInfo) {
return peerInfo
}
throw new Error('PeerInfo not found')
}
getAll () {
return this._peers
}
getAllArray () {
return Object.keys(this._peers).map((b58Str) => this._peers[b58Str])
}
/**
* Return all multiaddrs for a given PeerId.
*
* @param {PeerId, PeerInfo, Multihash, B58Str} id
* @returns {Array<Multiaddr>}
*/
getMultiaddrs (peer) {
const info = this.get(peer)
return info.multiaddrs
}
remove (peer) {
const b58Str = getB58Str(peer)
if (this._peers[b58Str]) {
delete this._peers[b58Str]
}
}
}
module.exports = PeerBook