mirror of
https://github.com/fluencelabs/js-libp2p
synced 2025-05-04 06:52:14 +00:00
* feat: address and proto books * chore: apply suggestions from code review Co-Authored-By: Jacob Heun <jacobheun@gmail.com> * chore: minor fixes and initial tests added * chore: integrate new peer-store with code using adapters for other modules * chore: do not use peerstore.put on get-peer-info * chore: apply suggestions from code review Co-Authored-By: Jacob Heun <jacobheun@gmail.com> * chore: add new peer store tests * chore: apply suggestions from code review Co-Authored-By: Jacob Heun <jacobheun@gmail.com> Co-authored-by: Jacob Heun <jacobheun@gmail.com>
64 lines
1.4 KiB
JavaScript
64 lines
1.4 KiB
JavaScript
'use strict'
|
|
|
|
const debug = require('debug')
|
|
const log = debug('libp2p-ping')
|
|
log.error = debug('libp2p-ping:error')
|
|
const errCode = require('err-code')
|
|
|
|
const crypto = require('libp2p-crypto')
|
|
const pipe = require('it-pipe')
|
|
const { toBuffer } = require('it-buffer')
|
|
const { collect, take } = require('streaming-iterables')
|
|
|
|
const { PROTOCOL, PING_LENGTH } = require('./constants')
|
|
|
|
/**
|
|
* Ping a given peer and wait for its response, getting the operation latency.
|
|
* @param {Libp2p} node
|
|
* @param {PeerId} peer
|
|
* @returns {Promise<Number>}
|
|
*/
|
|
async function ping (node, peer) {
|
|
log('dialing %s to %s', PROTOCOL, peer.toB58String())
|
|
|
|
const { stream } = await node.dialProtocol(peer, PROTOCOL)
|
|
|
|
const start = new Date()
|
|
const data = crypto.randomBytes(PING_LENGTH)
|
|
|
|
const [result] = await pipe(
|
|
[data],
|
|
stream,
|
|
stream => take(1, stream),
|
|
toBuffer,
|
|
collect
|
|
)
|
|
const end = Date.now()
|
|
|
|
if (!data.equals(result)) {
|
|
throw errCode(new Error('Received wrong ping ack'), 'ERR_WRONG_PING_ACK')
|
|
}
|
|
|
|
return end - start
|
|
}
|
|
|
|
/**
|
|
* Subscribe ping protocol handler.
|
|
* @param {Libp2p} node
|
|
*/
|
|
function mount (node) {
|
|
node.handle(PROTOCOL, ({ stream }) => pipe(stream, stream))
|
|
}
|
|
|
|
/**
|
|
* Unsubscribe ping protocol handler.
|
|
* @param {Libp2p} node
|
|
*/
|
|
function unmount (node) {
|
|
node.unhandle(PROTOCOL)
|
|
}
|
|
|
|
exports = module.exports = ping
|
|
exports.mount = mount
|
|
exports.unmount = unmount
|