js-libp2p/test/peer-store/peer-store.node.js
Alex Potsides 978eb3676f
feat: async peerstore backed by datastores (#1058)
We have a peerstore that keeps all data for all observed peers in memory with no eviction.

This is fine when you don't discover many peers but when using the DHT you encounter a significant number of peers so our peer storage grows and grows over time.

We have a persistent peer store, but it just periodically writes peers into the datastore to be read at startup, still keeping them in memory.

It also means a restart doesn't give you any temporary reprieve from the memory leak as the previously observed peer data is read into memory at startup.

This change refactors the peerstore to use a datastore by default, reading and writing peer info as it arrives.  It can be configured with a MemoryDatastore if desired.

It was necessary to change the peerstore and *book interfaces to be asynchronous since the datastore api is asynchronous.

BREAKING CHANGE: `libp2p.handle`, `libp2p.registrar.register` and the peerstore methods have become async
2022-01-20 12:03:35 +00:00

51 lines
1.6 KiB
JavaScript

'use strict'
/* eslint-env mocha */
const { expect } = require('aegir/utils/chai')
const sinon = require('sinon')
const baseOptions = require('../utils/base-options')
const peerUtils = require('../utils/creators/peer')
const all = require('it-all')
describe('libp2p.peerStore', () => {
let libp2p, remoteLibp2p
beforeEach(async () => {
[libp2p, remoteLibp2p] = await peerUtils.createPeer({
number: 2,
populateAddressBooks: false,
config: {
...baseOptions
}
})
})
afterEach(() => Promise.all([libp2p, remoteLibp2p].map(l => l.stop())))
it('adds peer address to AddressBook and keys to the keybook when establishing connection', async () => {
const remoteIdStr = remoteLibp2p.peerId.toB58String()
const spyAddressBook = sinon.spy(libp2p.peerStore.addressBook, 'add')
const spyKeyBook = sinon.spy(libp2p.peerStore.keyBook, 'set')
const remoteMultiaddr = `${remoteLibp2p.multiaddrs[0]}/p2p/${remoteIdStr}`
const conn = await libp2p.dial(remoteMultiaddr)
expect(conn).to.exist()
expect(spyAddressBook).to.have.property('called', true)
expect(spyKeyBook).to.have.property('called', true)
const localPeers = await all(libp2p.peerStore.getPeers())
expect(localPeers.length).to.equal(1)
const publicKeyInLocalPeer = localPeers[0].id.pubKey
expect(publicKeyInLocalPeer.bytes).to.equalBytes(remoteLibp2p.peerId.pubKey.bytes)
const publicKeyInRemotePeer = await remoteLibp2p.peerStore.keyBook.get(libp2p.peerId)
expect(publicKeyInRemotePeer).to.exist()
expect(publicKeyInRemotePeer.bytes).to.equalBytes(libp2p.peerId.pubKey.bytes)
})
})