Skip to content

fix: dedupe toOptions/nodeAddress code #266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 6, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 6 additions & 29 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ 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,
Expand All @@ -25,11 +21,6 @@ const P2P_CODES = [
getProtocol('ipfs').code
]

const TCP_UDP_CODES = [
getProtocol('tcp').code,
getProtocol('udp').code
]

export interface Protocol {
code: number
size: number
Expand Down Expand Up @@ -485,30 +476,16 @@ export class Multiaddr {
* ```
*/
nodeAddress (): NodeAddress {
const codes = this.protoCodes()
const names = this.protoNames()
const parts = this.toString().split('/').slice(1)
let protocol = getProtocol(parts[2]).code
let port = parseInt(parts[3])
const options = this.toOptions()

// default to https when protocol & port are omitted from DNS addrs
if (DNS_CODES.includes(codes[0]) && P2P_CODES.includes(codes[1])) {
protocol = getProtocol('tcp').code
port = 443
}

if (parts.length < 4) {
throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".')
} 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 (!TCP_UDP_CODES.includes(protocol)) {
throw new Error(`no protocol with name: "'${names[1]}'". Must have a valid transport protocol: "{tcp, udp}".`)
if (options.transport !== 'tcp' && options.transport !== 'udp') {
throw new Error(`multiaddr must have a valid format - no protocol with name: "${options.transport}". Must have a valid transport protocol: "{tcp, udp}"`)
}

return {
family: (codes[0] === 41 || codes[0] === 55) ? 6 : 4,
address: parts[1],
port // tcp or udp port
family: options.family,
address: options.host,
port: options.port
}
}

Expand Down