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

81 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-04-28 15:03:16 +02:00
'use strict'
const debug = require('debug')
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')
/**
* @typedef {import('./')} PeerStore
2020-12-02 21:39:17 +01:00
* @typedef {import('libp2p-crypto').PublicKey} PublicKey
*/
2020-04-28 15:03:16 +02:00
/**
* @extends {Book<PeerId, PublicKey, PublicKey>}
2020-04-28 15:03:16 +02:00
*/
class KeyBook extends Book {
/**
2020-11-16 11:56:18 +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 && data.pubKey,
getTransformer: (data) => data && data.pubKey
2020-04-28 15:03:16 +02:00
})
/**
* 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-02 21:39:17 +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
}
}
module.exports = KeyBook