From 408ed937d14be4e84375af43aaf5fc9116040b4d Mon Sep 17 00:00:00 2001 From: achingbrain Date: Thu, 23 Jun 2022 14:22:26 +0100 Subject: [PATCH] fix: support dns and dnsaddr Not sure why but we currently can't parse `/dns/foo.com/...` or `/dnsaddr/foo.com/...` so this PR fixes that. --- src/index.ts | 15 +++++++++++++-- test/index.spec.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 47ba663d..5e83c6ce 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 @@ -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}".`) } diff --git a/test/index.spec.ts b/test/index.spec.ts index 1b92520f..36411a30 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -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({ @@ -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()