Browse Source

Use `compact-encoding-net` for encoding IPs (#33)

* Use `compact-encoding-net` for encoding IPs

* Feedback from @mafintosh
session-estimator
Kasper Isager 3 years ago
committed by GitHub
parent
commit
d3ad60ec7b
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      .gitignore
  2. 46
      lib/peer.js
  3. 1
      package.json

1
.gitignore

@ -1,4 +1,5 @@
node_modules
package-lock.json
sandbox.js
sandbox
coverage

46
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
}

1
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",

Loading…
Cancel
Save