{"name":"dht-rpc","version":"6.6.0","author":{"url":"@mafintosh","name":"Mathias Buus"},"license":"MIT","_id":"dht-rpc@6.6.0","homepage":"https://github.com/mafintosh/dht-rpc","bugs":{"url":"https://github.com/mafintosh/dht-rpc/issues"},"dist":{"shasum":"c02224125adad01b1a1cab2b90f036cc883efa23","tarball":"http://registry-npm.ywwl.com/dht-rpc/download/dht-rpc-6.6.0.tgz","fileCount":16,"integrity":"sha512-dSM+9BgqubEp1QpbvRbT5LG5yrxAEYJ+4mzfRntc5F5ATpnaG/iJV5hf1uWA2B5y2miEw4WI/b2hihUadZpkEg==","signatures":[{"sig":"MEUCIBXk70qCroaqEjbAATOlWX0g6Jzo91LGZ2RnNJ+bshMtAiEAo6cCOjKciV+NUMfVYXeFGgCapIQI3eBm4+iIWEmngPs=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":73309,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjtIwsACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpocA//XeJDObQm7uAj7CshYtG2ldKExtvBdx2SaLGaiXheNajecu4x\r\n8fdP6zkNMuZ0VXvJEXguZf+UUc4xmgJ9DAm+ipWnhvBRDVrqHEGXO0pMql9O\r\nxYx1kmFuiMfoD3UMzkPRBvWzAD6q0Yo8WQUh3AurYFHK5KmuJpnkq/iGX3Nx\r\nS0orFHmPaPSy8YsUY0xSkL69R+HL5Sy/bzn2i/TYrv6R6wIpJHrkfqArvqTT\r\ntYlWnAIM2BYGQCI15de06K9GW6SAKGFt8DT8Y9iBEM8j6l68U1gNqdf8Jeky\r\nOnNTHrrZNBL3slM9zaobzhgvZY6xzfA7ybB//0819yLaKekDoaz7SBkDmZ7e\r\nbsztg5I7lk35hGlgqcvEGstG/GoStNRPgLOzOXtjfL1vXRSG7GSX5fzPHvb0\r\nF8TMglCXWsy7A8b38Q5VK8pw0qgiluQoQagWf6W1uAi8qFhHDCqxGzSfR58i\r\nKlyKdAfVlCVBXPGV9Hqc/AoZAKmDQf109WcuRSMZnq6kfgCDbiYxZHyjYVld\r\n8+PCbPtc6rHe/MR+K88l7xSa5UlhnR5+BBMGTrkSXlVhd0okA7euEgsSfMHX\r\ntI39dkW4KySWed1RNlqdoTu5iZ6DLWvpW7Qene+HzembbmxIzCl3mqaVR2Bl\r\nrtJEp1kkWP4MtHDWKFWox6HXEwCbrtQp+gg=\r\n=59C/\r\n-----END PGP SIGNATURE-----\r\n","size":20288,"noattachment":false,"key":"/dht-rpc/-/dht-rpc-6.6.0.tgz"},"main":"index.js","gitHead":"216d3ed14212f3197d3eccb0b829db6794923e23","scripts":{"test":"standard && brittle test.js"},"_npmUser":{"name":"mafintosh","email":"mathiasbuus@gmail.com"},"repository":{"url":"git+https://github.com/mafintosh/dht-rpc.git","type":"git"},"_npmVersion":"8.15.0","description":"Make RPC calls over a Kademlia based DHT","directories":{},"_nodeVersion":"16.17.0","dependencies":{"b4a":"^1.3.1","events":"^3.3.0","streamx":"^2.10.3","fast-fifo":"^1.0.0","udx-native":"^1.2.0","nat-sampler":"^1.0.1","compact-encoding":"^2.1.0","sodium-universal":"^3.0.4","time-ordered-set":"^1.0.2","compact-encoding-net":"^1.0.1","kademlia-routing-table":"^1.0.0"},"_hasShrinkwrap":false,"devDependencies":{"brittle":"^3.0.0","standard":"^17.0.0"},"_npmOperationalInternal":{"tmp":"tmp/dht-rpc_6.6.0_1672776748029_0.35836169481819513","host":"s3://npm-registry-packages"},"readme":"# dht-rpc\n\nMake RPC calls over a [Kademlia](https://pdos.csail.mit.edu/~petar/papers/maymounkov-kademlia-lncs.pdf) based DHT.\n\n```\nnpm install dht-rpc\n```\n\n## Key Features\n\n* Remote IP / firewall detection\n* Easily add any command to your DHT\n* Streaming queries and updates\n\nNote that internally V5 of dht-rpc differs significantly from V4, due to a series\nof improvements to NAT detection, secure routing IDs and more.\n\n## Usage\n\nHere is an example implementing a simple key value store\n\nFirst spin up a bootstrap node. You can make multiple if you want for redundancy.\nThere is nothing special about a bootstrap node, except it needs to know it's own host and port,\nsince it knows no other nodes to infer it from.\n\n``` js\nimport DHT from 'dht-rpc'\n\nconst bootstrap = DHT.bootstrapper(10001, '127.0.0.1')\n```\n\nNow lets make some dht nodes that can store values in our key value store.\n\n``` js\nimport DHT from 'dht-rpc'\nimport crypto from 'crypto'\n\n// Let's create 100 dht nodes for our example.\nfor (var i = 0; i < 100; i++) createNode()\n\nfunction createNode () {\n  const node = new DHT({\n    bootstrap: [\n      'localhost:10001'\n    ]\n  })\n\n  const values = new Map()\n  const VALUES = 0 // define a command enum\n\n  node.on('request', function (req) {\n    if (req.command === VALUES) {\n      if (req.token) { // if we are the closest node store the value (ie the node sent a valid roundtrip token)\n        const key = hash(req.value).toString('hex')\n        values.set(key, req.value)\n        console.log('Storing', key, '-->', req.value.toString())\n        return req.reply(null)\n      }\n\n      const value = values.get(req.target.toString('hex'))\n      req.reply(value)\n    }\n  })\n}\n\nfunction hash (value) {\n  return crypto.createHash('sha256').update(value).digest()\n}\n```\n\nTo insert a value into this dht make another script that does this following\n\n``` js\nconst node = new DHT()\n\nconst q = node.query({\n  target: hash(val),\n  command: VALUES,\n  value\n}, {\n  // commit true will make the query re-request the 20 closest\n  // nodes with a valid round trip token to update the values\n  commit: true\n})\n\nawait q.finished()\n```\n\nThen after inserting run this script to query for a value\n\n``` js\nconst target = Buffer.from(hexFromAbove, 'hex')\nfor await (const data of node.query({ target, command: VALUES })) {\n  if (data.value && hash(data.value).toString('hex') === hexFromAbove) {\n    // We found the value! Destroy the query stream as there is no need to continue.\n    console.log(val, '-->', data.value.toString())\n    break\n  }\n}\nconsole.log('(query finished)')\n```\n\n## API\n\n#### `const node = new DHT([options])`\n\nCreate a new DHT node.\n\nOptions include:\n\n``` js\n{\n  // A list of bootstrap nodes\n  bootstrap: [ 'bootstrap-node.com:24242', ... ],\n  // Optionally pass in array of { host, port } to add to the routing table if you know any peers\n  nodes: [{ host, port }, ...],\n  // Optionally pass a port you prefer to bind to instead of a random one\n  port: 0,\n  // Optionally pass a host you prefer to bind to instead of all networks\n  host: '0.0.0.0',\n  // Optionally pass a UDX instance on which sockets will be created.\n  udx,\n  // dht-rpc will automatically detect if you are firewalled. If you know that you are not set this to false\n  firewalled: true\n}\n```\n\nNodes per default use something called adaptive mode to decide whether or not they want to join other nodes' routing table.\nThis includes things like node uptime, if the node is firewalled etc. Adaptive mode is conservative, so it might take ~20-30 mins for the node to turn persistent. If you are making a test case with your own bootstrap network you'd usually want to turn this off to make sure your test finishes in a timely manner. You can do this by passing `ephemeral: false` in the constructor.\nFor the vast majority of use-cases you should always use adaptive mode to ensure good DHT health, ie the defaults.\n\nYour DHT routing id is `hash(publicIp + publicPort)` and will be autoconfigured internally.\n\n#### `const node = DHT.bootstrapper(port, host, [options])`\n\nMake a bootstrap node for your DHT. The port and host needs to be its globally accessible port and host.\nNote: `port` and `host` parameters are used to create the node id. Use `options.host` if you want to bind to i.e. 127.0.0.1.\nDHT nodes can use any other DHT node to bootstrap, but a bootstrap node can bootstrap itself, by itself.\n\n#### `await node.ready()`\n\nWait for the node to be fully bootstrapped etc.\nYou don't have to wait for this method, but can be useful during testing.\n\n#### `node.id`\n\nGet your own routing ID. Only available when the node is not ephemeral.\n\n#### `node.ephemeral`\n\nA boolean indicating if you are currently ephemeral or not\n\n#### `node.on('bootstrap')`\n\nEmitted when the routing table is fully bootstrapped. Emitted as a conveinience.\n\n#### `node.on('listening')`\n\nEmitted when the underlying UDX socket is listening. Emitted as a conveinience.\n\n#### `node.on('ready')`\n\nEmitted when the node is fully bootstrapped etc.\n\n#### `node.on('persistent')`\n\nEmitted when the node is no longer in ephemeral mode.\nAll nodes start in ephemeral mode, as they figure out their NAT settings.\nIf you set `ephemeral: false` then this is emitted during the bootstrap phase, assuming\nyou are on an open NAT.\n\n#### `node.on('wake-up')`\n\nEmitted when the node has detected that the computer has gone to sleep. If this happens,\nit will switch from persistent mode to ephemeral again.\n\n#### `node.on('network-change', interfaces)`\n\nEmitted when the network interfaces of the computer change.\n\n#### `node.on('nat-update', (host, port) => {})`\nEmitted when `node.host` or `node.port` were changed.\n\n#### `node.on('close')`\n\nWill be emitted after `node.destroy()` is completed.\n\n#### `node.refresh()`\n\nRefresh the routing table by looking up a random node in the background.\nThis is called internally periodically, but exposed in-case you want to force a refresh.\n\n#### `node.host`\n\nGet your node's public ip, inferred from other nodes in the DHT.\nIf the ip cannot be determined, this is set to `null`.\n\n#### `node.port`\n\nGet your node's public port, inferred from other nodes in the DHT.\nIf your node does not have a consistent port, this is set to 0.\n\n#### `node.firewalled`\n\nBoolean indicated if your node is behind a firewall.\n\nThis is auto detected by having other nodes trying to do a PING to you\nwithout you contacting them first.\n\n#### `node.randomized`\n\nBoolean indicating if your node is likely behind a randomizing NAT.\n\n#### `const addr = node.address()`\n\nGet the local address of the UDP socket bound.\n\nNote that if you are in ephemeral mode, this will return a different\nport than the one you provided in the constructor (under `port`), as ephemeral\nmode always uses a random port.\n\n#### `node.on('request', req)`\n\nEmitted when an incoming DHT request is received. This is where you can add your own RPC methods.\n\n* `req.target` - the dht target the peer is looking (routing is handled behind the scene)\n* `req.command` - the RPC command enum\n* `req.value` - the RPC value buffer\n* `req.token` - If the remote peer echoed back a valid roundtrip token, proving their \"from address\" this is set\n* `req.from` - who sent this request (host, port)\n\nTo reply to a request use the `req.reply(value)` method and to reply with an error code use `req.error(errorCode)`.\n\nIn general error codes are up to the user to define, with the general suggestion to start application specific errors\nfrom error code `16` and up, to avoid future clashes with `dht-rpc` internals.\n\nCurrently dht-rpc defines the following errors\n\n``` js\nDHT.OK = 0 // ie no error\nDHT.ERROR_UNKNOWN_COMMAND = 1 // the command requested does not exist\nDHT.ERROR_INVALID_TOKEN = 2 // the round trip token sent is invalid\n```\n\n#### `reply = await node.request({ token, target, command, value }, to, [options])`\n\nSend a request to a specific node specified by the to address (`{ host, port }`).\nSee the query API for more info on the arguments.\n\nOptions include:\n\n```js\n{\n  retry: true, // whether the request should retry on timeout\n  socket: udxSocket // request on this specific socket\n}\n```\n\nNormally you'd set the token when committing to the dht in the query's commit hook.\n\n#### `reply = await node.ping(to, [options])`\n\nSugar for `dht.request({ command: 'ping' }, to, options)`\n\nAdditional options include:\n\n```js\n{\n  size: 0, // size of the value buffer, filled with zeroes\n}\n```\n\n#### `stream = node.query({ target, command, value }, [options])`\n\nQuery the DHT. Will move as close as possible to the `target` provided, which should be a 32-byte uniformly distributed buffer (ie a hash).\n\n* `target` - find nodes close to this (should be a 32 byte buffer like a hash)\n* `command` - an enum (uint) indicating the method you want to invoke\n* `value` - optional binary payload to send with it\n\nIf you want to modify state stored in the dht, you can use the commit flag to signal the closest\nnodes.\n\n``` js\n{\n  // \"commit\" the query to the 20 closest nodes so they can modify/update their state\n  commit: true\n}\n```\n\nCommiting a query will just re-request your command to the closest nodes once those are verified.\nIf you want to do some more specific logic with the closest nodes you can specify a function instead,\nthat is called for each close reply.\n\n``` js\n{\n  async commit (reply, dht, query) {\n    // normally you'd send back the roundtrip token here, to prove to the remote that you own\n    // your ip/port\n    await dht.request({ token: reply.token, target, command, value }, reply.from)\n  }\n}\n```\n\nOther options include:\n\n``` js\n{\n  nodes: [\n    // start the query by querying these nodes\n    // useful if you are re-doing a query from a set of closest nodes.\n  ],\n  replies: [\n    // similar to nodes, but useful if you have an array of closest replies instead\n    // from a previous query.\n  ],\n  map (reply) {\n    // map the reply into what you want returned on the stream\n    return { onlyValue: reply.value }\n  }\n}\n```\n\nThe query method returns a stream encapsulating the query, that is also an async iterator. Each `data` event contain a DHT reply.\nIf you just want to wait for the query to finish, you can use the `await stream.finished()` helper. After completion the closest\nnodes are stored in `stream.closestNodes` array.\n\nIf you want to access the closest replies to your provided target you can see those at `stream.closestReplies`.\n\n#### `stream = node.findNode(target, [options])`\n\nFind the node closest to the node with id `target`. Returns a stream encapsulating the query (see `node.query()`). `options` are the same as `node.query()`.\n\n#### `node.destroy()`\n\nShutdown the DHT node.\n\n#### `node.destroyed`\n\nBoolean indicating if this has been destroyed.\n\n#### `node.toArray()`\n\nGet the routing table peers out as an array of `{ host, port }`\n\n#### `node.addNode({ host, port })`\n\nManually add a node to the routing table.\n\n#### `await node.suspend()`\n\nTell the DHT you are going to background (ie suspend and allow it to make preperations for that)\n\n#### `await node.resume()`\n\nTell the DHT you are resuming from suspension.\n\n## License\n\nMIT\n","publish_time":1672776748233,"maintainers":[{"name":"mafintosh","email":"mathiasbuus@gmail.com"}],"_cnpm_publish_time":1672776748233,"dist-tags":{"latest":"6.28.0"}}