Browse Source
* Use `compact-encoding-net` for encoding IPs * Feedback from @mafintoshsession-estimator
committed by
GitHub
3 changed files with 14 additions and 34 deletions
@ -1,4 +1,5 @@ |
|||||
node_modules |
node_modules |
||||
|
package-lock.json |
||||
sandbox.js |
sandbox.js |
||||
sandbox |
sandbox |
||||
coverage |
coverage |
||||
|
@ -1,49 +1,27 @@ |
|||||
const sodium = require('sodium-universal') |
const sodium = require('sodium-universal') |
||||
const c = require('compact-encoding') |
const c = require('compact-encoding') |
||||
|
const net = require('compact-encoding-net') |
||||
const addr = Buffer.alloc(6) |
|
||||
let i = 0 |
|
||||
|
|
||||
const ipv4 = { |
const ipv4 = { |
||||
preencode (state, p) { |
...net.ipv4Address, |
||||
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 |
|
||||
}, |
|
||||
decode (state) { |
decode (state) { |
||||
if (state.end - state.start < 6) throw new Error('Out of bounds') |
const ip = net.ipv4Address.decode(state) |
||||
return { |
return { |
||||
id: null, // populated elsewhere
|
id: null, // populated by the callee
|
||||
host: state.buffer[state.start++] + '.' + state.buffer[state.start++] + '.' + state.buffer[state.start++] + '.' + state.buffer[state.start++], |
host: ip.host, |
||||
port: state.buffer[state.start++] + 256 * state.buffer[state.start++] |
port: ip.port |
||||
} |
} |
||||
} |
} |
||||
} |
} |
||||
|
|
||||
module.exports = { id, ipv4, ipv4Array: c.array(ipv4) } |
module.exports = { id, ipv4, ipv4Array: c.array(ipv4) } |
||||
|
|
||||
function num (ip) { |
function id (host, port, out = Buffer.allocUnsafe(32)) { |
||||
let n = 0 |
const addr = out.subarray(0, 6) |
||||
let c = 0 |
ipv4.encode( |
||||
while (i < ip.length && (c = ip.charCodeAt(i++)) !== 46) n = n * 10 + (c - 48) |
{ start: 0, end: 6, buffer: addr }, |
||||
return n |
{ host, port } |
||||
} |
) |
||||
|
|
||||
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 |
|
||||
sodium.crypto_generichash(out, addr) |
sodium.crypto_generichash(out, addr) |
||||
return out |
return out |
||||
} |
} |
||||
|
Loading…
Reference in new issue