js-libp2p-utils/src/ip-port-to-multiaddr.js

58 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-09-23 17:39:32 +02:00
'use strict'
2021-04-08 11:52:55 +02:00
const debug = require('debug')
const log = Object.assign(debug('libp2p:ip-port-to-multiaddr'), {
error: debug('libp2p:ip-port-to-multiaddr:err')
})
2021-04-08 18:34:20 +02:00
const { Multiaddr } = require('multiaddr')
const errCode = require('err-code')
2019-09-23 17:39:32 +02:00
const { Address4, Address6 } = require('ip-address')
const errors = {
ERR_INVALID_IP_PARAMETER: 'ERR_INVALID_IP_PARAMETER',
ERR_INVALID_PORT_PARAMETER: 'ERR_INVALID_PORT_PARAMETER',
ERR_INVALID_IP: 'ERR_INVALID_IP'
}
2020-10-07 15:01:44 +02:00
/**
* Transform an IP, Port pair into a multiaddr
*
* @param {string} ip
* @param {number|string} port
*/
function ipPortToMultiaddr (ip, port) {
2019-09-23 17:39:32 +02:00
if (typeof ip !== 'string') {
throw errCode(new Error(`invalid ip provided: ${ip}`), errors.ERR_INVALID_IP_PARAMETER)
2019-09-23 17:39:32 +02:00
}
2021-04-08 11:52:55 +02:00
if (typeof port === 'string') {
port = parseInt(port)
}
2019-09-23 17:39:32 +02:00
if (isNaN(port)) {
throw errCode(new Error(`invalid port provided: ${port}`), errors.ERR_INVALID_PORT_PARAMETER)
2019-09-23 17:39:32 +02:00
}
2021-04-08 11:52:55 +02:00
try {
// Test valid IPv4
new Address4(ip) // eslint-disable-line no-new
2021-04-08 18:34:20 +02:00
return new Multiaddr(`/ip4/${ip}/tcp/${port}`)
2021-04-08 11:52:55 +02:00
} catch {}
2019-09-23 17:39:32 +02:00
2021-04-08 11:52:55 +02:00
try {
// Test valid IPv6
const ip6 = new Address6(ip)
2019-09-23 17:39:32 +02:00
return ip6.is4()
2021-04-08 18:34:20 +02:00
? new Multiaddr(`/ip4/${ip6.to4().correctForm()}/tcp/${port}`)
: new Multiaddr(`/ip6/${ip}/tcp/${port}`)
2021-04-08 11:52:55 +02:00
} catch (err) {
const errMsg = `invalid ip:port for creating a multiaddr: ${ip}:${port}`
log.error(errMsg)
throw errCode(new Error(errMsg), errors.ERR_INVALID_IP)
2019-09-23 17:39:32 +02:00
}
}
2020-10-07 15:01:44 +02:00
module.exports = ipPortToMultiaddr
module.exports.Errors = errors