Skip to content

Commit

Permalink
fix(@libp2p/utils): switch to @chainsafe/is-ip (#1957)
Browse files Browse the repository at this point in the history
The `@achingbrain/ip-address` module is a fork of `ip-address` which
seems to have dependencies on older modules that break modern runtimes
like react native.

`@Chainsafe/is-ip` does not have these limitations so switch to that.

Fixes #1926
  • Loading branch information
achingbrain authored Aug 13, 2023
1 parent a31b420 commit 18567b7
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 18 deletions.
2 changes: 1 addition & 1 deletion packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
"test:electron-main": "aegir test -t electron-main"
},
"dependencies": {
"@achingbrain/ip-address": "^8.1.0",
"@chainsafe/is-ip": "^2.0.2",
"@libp2p/interface": "^0.1.1",
"@libp2p/logger": "^3.0.1",
"@multiformats/multiaddr": "^12.1.5",
Expand Down
26 changes: 10 additions & 16 deletions packages/utils/src/ip-port-to-multiaddr.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Address4, Address6 } from '@achingbrain/ip-address'
import { isIPv4, isIPv6 } from '@chainsafe/is-ip'
import { CodeError } from '@libp2p/interface/errors'
import { logger } from '@libp2p/logger'
import { type Multiaddr, multiaddr } from '@multiformats/multiaddr'
Expand Down Expand Up @@ -27,21 +27,15 @@ export function ipPortToMultiaddr (ip: string, port: number | string): Multiaddr
throw new CodeError(`invalid port provided: ${port}`, Errors.ERR_INVALID_PORT_PARAMETER)
}

try {
// Test valid IPv4
new Address4(ip) // eslint-disable-line no-new
if (isIPv4(ip)) {
return multiaddr(`/ip4/${ip}/tcp/${port}`)
} catch {}

try {
// Test valid IPv6
const ip6 = new Address6(ip)
return ip6.is4()
? multiaddr(`/ip4/${ip6.to4().correctForm()}/tcp/${port}`)
: multiaddr(`/ip6/${ip}/tcp/${port}`)
} catch (err) {
const errMsg = `invalid ip:port for creating a multiaddr: ${ip}:${port}`
log.error(errMsg)
throw new CodeError(errMsg, Errors.ERR_INVALID_IP)
}

if (isIPv6(ip)) {
return multiaddr(`/ip6/${ip}/tcp/${port}`)
}

const errMsg = `invalid ip:port for creating a multiaddr: ${ip}:${port}`
log.error(errMsg)
throw new CodeError(errMsg, Errors.ERR_INVALID_IP)
}
2 changes: 1 addition & 1 deletion packages/utils/test/ip-port-to-multiaddr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('IP and port to Multiaddr', () => {
it('creates multiaddr from valid IPv4 in IPv6 IP and port', () => {
const ip = '0:0:0:0:0:0:101.45.75.219'
const port = '9090'
expect(ipPortToMultiaddr(ip, port).toString()).to.equal(`/ip4/101.45.75.219/tcp/${port}`)
expect(ipPortToMultiaddr(ip, port).toString()).to.equal(`/ip6/::652d:4bdb/tcp/${port}`)
})

it('creates multiaddr from valid IPv6 IP and port', () => {
Expand Down

0 comments on commit 18567b7

Please sign in to comment.