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
72 lines (59 loc) · 1.5 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
'use strict'
const bs58 = require('bs58')
module.exports = PeerBook
function PeerBook () {
if (!(this instanceof PeerBook)) {
return new PeerBook()
}
const peers = {}
this.put = (peerInfo, replace) => {
if (peers[peerInfo.id.toB58String()] && !replace) {
// peerInfo.replace merges by default
peers[peerInfo.id.toB58String()].multiaddr.replace([], peerInfo.multiaddrs)
}
peers[peerInfo.id.toB58String()] = peerInfo
}
this.getAll = () => {
return peers
}
/**
* Get the info to the given PeerId.
*
* @param {PeerId} id
* @returns {PeerInfo}
*/
this.get = (id) => {
return this.getByB58String(id.toB58String())
}
this.getByB58String = (b58String) => {
const peerInfo = peers[b58String]
if (peerInfo) {
return peerInfo
}
throw new Error('PeerInfo not found')
}
this.getByMultihash = (multihash) => {
const b58multihash = bs58.encode(multihash).toString()
return this.getByB58String(b58multihash)
}
this.removeByB58String = (b58String) => {
if (peers[b58String]) {
delete peers[b58String]
}
}
this.removeByMultihash = (multihash) => {
const b58multihash = bs58.encode(multihash).toString()
this.removeByB58String(b58multihash)
}
/**
* Return all multiaddrs for a given PeerId.
*
* @param {PeerId} id
* @returns {Array<Multiaddr>}
*/
this.getAddrs = (id) => {
const info = this.get(id)
return info.multiaddrs
}
// TODO serialize PeerBook into MerkleDAG Objects
}