diff --git a/.gitignore b/.gitignore index df9289e..1170f7d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules +package-lock.json sandbox.js sandbox coverage diff --git a/lib/peer.js b/lib/peer.js index 55eae72..f9d93f8 100644 --- a/lib/peer.js +++ b/lib/peer.js @@ -1,49 +1,27 @@ const sodium = require('sodium-universal') const c = require('compact-encoding') - -const addr = Buffer.alloc(6) -let i = 0 +const net = require('compact-encoding-net') const ipv4 = { - preencode (state, p) { - state.end += 6 - }, - encode (state, p) { - i = 0 - state.buffer[state.start++] = num(p.host) - state.buffer[state.start++] = num(p.host) - state.buffer[state.start++] = num(p.host) - state.buffer[state.start++] = num(p.host) - state.buffer[state.start++] = p.port - state.buffer[state.start++] = p.port >>> 8 - }, + ...net.ipv4Address, decode (state) { - if (state.end - state.start < 6) throw new Error('Out of bounds') + const ip = net.ipv4Address.decode(state) return { - id: null, // populated elsewhere - host: state.buffer[state.start++] + '.' + state.buffer[state.start++] + '.' + state.buffer[state.start++] + '.' + state.buffer[state.start++], - port: state.buffer[state.start++] + 256 * state.buffer[state.start++] + id: null, // populated by the callee + host: ip.host, + port: ip.port } } } module.exports = { id, ipv4, ipv4Array: c.array(ipv4) } -function num (ip) { - let n = 0 - let c = 0 - while (i < ip.length && (c = ip.charCodeAt(i++)) !== 46) n = n * 10 + (c - 48) - return n -} - -function id (ip, port, out = Buffer.allocUnsafe(32)) { - i = 0 - addr[0] = num(ip) - addr[1] = num(ip) - addr[2] = num(ip) - addr[3] = num(ip) - addr[4] = port - addr[5] = port >>> 8 +function id (host, port, out = Buffer.allocUnsafe(32)) { + const addr = out.subarray(0, 6) + ipv4.encode( + { start: 0, end: 6, buffer: addr }, + { host, port } + ) sodium.crypto_generichash(out, addr) return out } diff --git a/package.json b/package.json index 3a4e854..2a06faa 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "dependencies": { "bind-easy": "^1.0.0", "compact-encoding": "^2.1.0", + "compact-encoding-net": "^1.0.1", "fast-fifo": "^1.0.0", "kademlia-routing-table": "^1.0.0", "nat-sampler": "^1.0.1",