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

89 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-04-28 15:03:16 +02:00
'use strict'
const errcode = require('err-code')
const debug = require('debug')
const log = debug('libp2p:peer-store:key-book')
log.error = debug('libp2p:peer-store:key-book:error')
const PeerId = require('peer-id')
const Book = require('./book')
const {
codes: { ERR_INVALID_PARAMETERS }
} = require('../errors')
/**
* The KeyBook is responsible for keeping the known public keys of a peer.
*/
class KeyBook extends Book {
/**
* @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
* @param {RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey} 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
* @returns {RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey}
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