Skip to content

Commit

Permalink
fix: support dns and dnsaddr (#253)
Browse files Browse the repository at this point in the history
Not sure why but we currently can't parse `/dns/foo.com/...` or
`/dnsaddr/foo.com/...` so this PR fixes that.
  • Loading branch information
achingbrain authored Jun 24, 2022
1 parent 25d22f9 commit 53fb15f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ import { equals as uint8ArrayEquals } from 'uint8arrays/equals'

const inspect = Symbol.for('nodejs.util.inspect.custom')

const IP_CODES = [
getProtocol('ip4').code,
getProtocol('ip6').code
]
const DNS_CODES = [
getProtocol('dns').code,
getProtocol('dns4').code,
getProtocol('dns6').code,
getProtocol('dnsaddr').code
]

export interface Protocol {
code: number
size: number
Expand Down Expand Up @@ -447,8 +458,8 @@ export class Multiaddr {

if (parts.length < 4) {
throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6}/{address}/{tcp, udp}/{port}".')
} else if (codes[0] !== 4 && codes[0] !== 41 && codes[0] !== 54 && codes[0] !== 55) {
throw new Error(`no protocol with name: "'${names[0]}'". Must have a valid family name: "{ip4, ip6, dns4, dns6}".`)
} else if (!IP_CODES.includes(codes[0]) && !DNS_CODES.includes(codes[0])) {
throw new Error(`no protocol with name: "'${names[0]}'". Must have a valid family name: "{ip4, ip6, dns, dns4, dns6, dnsaddr}".`)
} else if (parts[2] !== 'tcp' && parts[2] !== 'udp') {
throw new Error(`no protocol with name: "'${names[1]}'". Must have a valid transport protocol: "{tcp, udp}".`)
}
Expand Down
30 changes: 30 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,16 @@ describe('helpers', () => {
})

it('returns a node friendly address with dns', () => {
expect(
new Multiaddr('/dns/wss0.bootstrap.libp2p.io/tcp/443').nodeAddress()
).to.be.eql({
address: 'wss0.bootstrap.libp2p.io',
family: 4,
port: 443
})
})

it('returns a node friendly address with dns4', () => {
expect(
new Multiaddr('/dns4/wss0.bootstrap.libp2p.io/tcp/443').nodeAddress()
).to.be.eql({
Expand All @@ -695,6 +705,26 @@ describe('helpers', () => {
})
})

it('returns a node friendly address with dns6', () => {
expect(
new Multiaddr('/dns6/wss0.bootstrap.libp2p.io/tcp/443').nodeAddress()
).to.be.eql({
address: 'wss0.bootstrap.libp2p.io',
family: 6,
port: 443
})
})

it('returns a node friendly address with dnsaddr', () => {
expect(
new Multiaddr('/dnsaddr/wss0.bootstrap.libp2p.io/tcp/443').nodeAddress()
).to.be.eql({
address: 'wss0.bootstrap.libp2p.io',
family: 4,
port: 443
})
})

it('throws on an invalid format address when the addr is not prefixed with a /', () => {
expect(
() => new Multiaddr('ip4/192.168.0.1/udp').nodeAddress()
Expand Down

0 comments on commit 53fb15f

Please sign in to comment.