chore: store self protocols in protobook (#760)

This commit is contained in:
Vasco Santos
2020-10-27 13:50:14 +00:00
committed by Vasco Santos
parent e36b67a212
commit 97e3633f47
6 changed files with 258 additions and 100 deletions

View File

@ -51,9 +51,8 @@ class IdentifyService {
* @class
* @param {object} options
* @param {Libp2p} options.libp2p
* @param {Map<string, handler>} options.protocols - A reference to the protocols we support
*/
constructor ({ libp2p, protocols }) {
constructor ({ libp2p }) {
/**
* @property {PeerStore}
*/
@ -74,8 +73,6 @@ class IdentifyService {
*/
this._libp2p = libp2p
this._protocols = protocols
this.handleMessage = this.handleMessage.bind(this)
// Store self host metadata
@ -97,6 +94,13 @@ class IdentifyService {
this.pushToPeerStore()
}
})
// When self protocols change, trigger identify-push
this.peerStore.on('change:protocols', ({ peerId }) => {
if (peerId.toString() === this.peerId.toString()) {
this.pushToPeerStore()
}
})
}
/**
@ -108,7 +112,7 @@ class IdentifyService {
async push (connections) {
const signedPeerRecord = await this.peerStore.addressBook.getRawEnvelope(this.peerId)
const listenAddrs = this._libp2p.multiaddrs.map((ma) => ma.bytes)
const protocols = Array.from(this._protocols.keys())
const protocols = this.peerStore.protoBook.get(this.peerId) || []
const pushes = connections.map(async connection => {
try {
@ -139,6 +143,11 @@ class IdentifyService {
* @returns {void}
*/
pushToPeerStore () {
// Do not try to push if libp2p node is not running
if (!this._libp2p.isStarted()) {
return
}
const connections = []
let connection
for (const peer of this.peerStore.peers.values()) {
@ -258,6 +267,7 @@ class IdentifyService {
}
const signedPeerRecord = await this.peerStore.addressBook.getRawEnvelope(this.peerId)
const protocols = this.peerStore.protoBook.get(this.peerId) || []
const message = Message.encode({
protocolVersion: this._host.protocolVersion,
@ -266,7 +276,7 @@ class IdentifyService {
listenAddrs: this._libp2p.multiaddrs.map((ma) => ma.bytes),
signedPeerRecord,
observedAddr: connection.remoteAddr.bytes,
protocols: Array.from(this._protocols.keys())
protocols
})
try {