diff --git a/package.json b/package.json index f5fc785d..77f3bdb9 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "dependencies": { "bs58": "^4.0.1", "ip": "^1.1.5", + "ip-address": "^5.8.9", "lodash.filter": "^4.6.0", "lodash.map": "^4.6.0", "varint": "^5.0.0", diff --git a/src/convert.js b/src/convert.js index 30bb527a..b646fb16 100644 --- a/src/convert.js +++ b/src/convert.js @@ -1,6 +1,7 @@ 'use strict' const ip = require('ip') +const ipAddress = require('ip-address') const protocols = require('./protocols-table') const bs58 = require('bs58') const varint = require('varint') @@ -45,8 +46,9 @@ Convert.toBuffer = function convertToBuffer (proto, str) { proto = protocols(proto) switch (proto.code) { case 4: // ipv4 + return ip2buf(new ipAddress.Address4(str)) case 41: // ipv6 - return ip.toBuffer(str) + return ip2buf(new ipAddress.Address6(str)) case 6: // tcp case 17: // udp @@ -66,6 +68,11 @@ Convert.toBuffer = function convertToBuffer (proto, str) { } } +function ip2buf (ipaddr) { + if (!ipaddr.isValid()) throw new Error('invalid ip address') + return ip.toBuffer(ipaddr.address) +} + function port2buf (port) { const buf = Buffer.alloc(2) buf.writeUInt16BE(port, 0) diff --git a/test/convert.spec.js b/test/convert.spec.js index 2d924359..e53c0a0f 100644 --- a/test/convert.spec.js +++ b/test/convert.spec.js @@ -8,7 +8,7 @@ const expect = chai.expect chai.use(dirtyChai) describe('convert', () => { - it('handles buffers', () => { + it('handles ip4 buffers', () => { expect( convert('ip4', Buffer.from('c0a80001', 'hex')) ).to.eql( @@ -16,7 +16,23 @@ describe('convert', () => { ) }) - it('handles strings', () => { + it('handles ip6 buffers', () => { + expect( + convert('ip6', Buffer.from('abcd0000000100020003000400050006', 'hex')) + ).to.eql( + 'abcd:0:1:2:3:4:5:6' + ) + }) + + it('handles ipv6 strings', () => { + expect( + convert('ip6', 'ABCD::1:2:3:4:5:6') + ).to.eql( + Buffer.from('ABCD0000000100020003000400050006', 'hex') + ) + }) + + it('handles ip4 strings', () => { expect( convert('ip4', '192.168.0.1') ).to.eql( @@ -24,6 +40,22 @@ describe('convert', () => { ) }) + it('throws on invalid ip4 conversion', () => { + expect( + () => convert('ip4', '555.168.0.1') + ).to.throw( + /invalid ip address/ + ) + }) + + it('throws on invalid ip6 conversion', () => { + expect( + () => convert('ip6', 'FFFF::GGGG') + ).to.throw( + /invalid ip address/ + ) + }) + describe('.toBuffer', () => { it('defaults to hex conversion', () => { expect(