js-libp2p/src/peer-store/key-book.js

97 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-04-28 15:03:16 +02:00
'use strict'
const debug = require('debug')
2020-12-10 14:48:14 +01:00
const log = Object.assign(debug('libp2p:peer-store:key-book'), {
error: debug('libp2p:peer-store:key-book:err')
})
const errcode = require('err-code')
2020-04-28 15:03:16 +02:00
const PeerId = require('peer-id')
const Book = require('./book')
const {
codes: { ERR_INVALID_PARAMETERS }
} = require('../errors')
/**
2020-12-10 14:48:14 +01:00
* @typedef {import('./')} PeerStore
* @typedef {import('libp2p-crypto').PublicKey} PublicKey
*/
/**
* @extends {Book}
2020-04-28 15:03:16 +02:00
*/
class KeyBook extends Book {
/**
2020-12-10 14:48:14 +01:00
* The KeyBook is responsible for keeping the known public keys of a peer.
*
* @class
* @param {PeerStore} peerStore
*/
2020-04-28 15:03:16 +02:00
constructor (peerStore) {
super({
peerStore,
eventName: 'change:pubkey',
2020-04-28 15:03:16 +02:00
eventProperty: 'pubkey',
eventTransformer: (data) => data.pubKey
})
/**
* Map known peers to their known Public Key.
*
2020-04-28 15:03:16 +02:00
* @type {Map<string, PeerId>}
*/
this.data = new Map()
}
/**
* Set the Peer public key.
*
2020-04-28 15:03:16 +02:00
* @override
* @param {PeerId} peerId
2020-12-10 14:48:14 +01:00
* @param {PublicKey} publicKey
* @returns {KeyBook}
*/
set (peerId, publicKey) {
2020-04-28 15:03:16 +02:00
if (!PeerId.isPeerId(peerId)) {
log.error('peerId must be an instance of peer-id to store data')
throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
}
const id = peerId.toB58String()
const recPeerId = this.data.get(id)
// If no record available, and this is valid
if (!recPeerId && publicKey) {
// This might be unecessary, but we want to store the PeerId
// to avoid an async operation when reconstructing the PeerId
peerId.pubKey = publicKey
this._setData(peerId, peerId)
2020-04-28 15:03:16 +02:00
log(`stored provided public key for ${id}`)
}
return this
}
/**
* Get Public key of the given PeerId, if stored.
*
2020-04-28 15:03:16 +02:00
* @override
* @param {PeerId} peerId
2020-12-10 14:48:14 +01:00
* @returns {PublicKey | undefined}
2020-04-28 15:03:16 +02:00
*/
get (peerId) {
if (!PeerId.isPeerId(peerId)) {
throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
}
const rec = this.data.get(peerId.toB58String())
return rec ? rec.pubKey : undefined
}
}
module.exports = KeyBook