├── .gitignore ├── LICENSE ├── README.md ├── bin └── test.js ├── examples └── chat │ ├── _chat_p2p.js │ └── chat.js ├── lib ├── index.js ├── libp2p-bundle.js └── util.js ├── package-lock.json └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # node-js-libp2p-ipc 2 | Holochain IPC connector to the javascript (node-js) version of libp2p 3 | -------------------------------------------------------------------------------- /bin/test.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { Node } = require('../lib/index') 4 | 5 | function _sleep (ms) { 6 | return new Promise((resolve, reject) => { 7 | setTimeout(resolve, ms) 8 | }) 9 | } 10 | 11 | async function _main () { 12 | const node1 = new Node() 13 | const node2 = new Node() 14 | const node3 = new Node() 15 | 16 | const handleTerm = async () => { 17 | try { 18 | await node1.close() 19 | } catch (e) { /* pass */ } 20 | try { 21 | await node2.close() 22 | } catch (e) { /* pass */ } 23 | try { 24 | await node3.close() 25 | } catch (e) { /* pass */ } 26 | process.exit(0) 27 | } 28 | process.on('SIGINT', handleTerm) 29 | 30 | console.log('-- node1 --') 31 | let node1addr = '' 32 | await node1.init('ipc://node1.ipc.sock', '/ip4/0.0.0.0/tcp/0') 33 | console.log('-- node1 addrs --') 34 | for (let addr of node1.getAddrs()) { 35 | node1addr = addr 36 | console.log(addr) 37 | } 38 | console.log('-- node1 addrs --') 39 | 40 | console.log('-- node2 --') 41 | await node2.init('ipc://node2.ipc.sock', '/ip4/0.0.0.0/tcp/0') 42 | console.log('attept connect node2 to node1 (' + node1addr + ')') 43 | await node2.connect(node1addr) 44 | 45 | console.log('-- node3 --') 46 | await node3.init('ipc://node3.ipc.sock', '/ip4/0.0.0.0/tcp/0') 47 | console.log('attept connect node3 to node1 (' + node1addr + ')') 48 | await node3.connect(node1addr) 49 | 50 | await _sleep(10000) 51 | handleTerm() 52 | } 53 | 54 | _main().then(() => {}, (err) => { 55 | console.error(err) 56 | process.exit(1) 57 | }) 58 | -------------------------------------------------------------------------------- /examples/chat/_chat_p2p.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const msgpack = require('msgpack-lite') 4 | 5 | const { Node } = require('../../lib/index') 6 | 7 | async function _main () { 8 | if (process.argv.length < 3 || process.argv.length > 4) { 9 | throw new Error('expecting ipc / node name, and optional connect addr') 10 | } 11 | 12 | const ipc = 'ipc://./' + process.argv[2] + '.ipc.sock' 13 | 14 | console.log('ipc socket: ' + ipc) 15 | 16 | const node = new Node() 17 | console.log('initialize node') 18 | await node.init(ipc, '/ip4/0.0.0.0/tcp/0') 19 | 20 | node.on('message', opt => { 21 | opt.resolve() 22 | node.ipcSendMessage(msgpack.encode({ 23 | type: 'message', 24 | data: { 25 | from: opt.data.from.substr(0, 8), 26 | msg: opt.data.msg 27 | } 28 | })) 29 | }) 30 | 31 | node.on('ipcMessage', async opt => { 32 | try { 33 | const msg = msgpack.decode(opt.data) 34 | switch (msg.type) { 35 | case 'getName': 36 | opt.resolve(msgpack.encode(node.getId().substr(0, 8))) 37 | break 38 | case 'message': 39 | opt.resolve(Buffer.alloc(0)) 40 | // trying to store data in dht?? 41 | const s = msg.data.match(/^\/store\s*([^=]+)=(.+)$/) 42 | if (s && s.length === 3) { 43 | const key = s[1].trim() 44 | const val = s[2].trim() 45 | console.log(`store '${key}'='${val}'`) 46 | await node.store(key, val) 47 | break 48 | } 49 | // trying to fetch data from dht?? 50 | const f = msg.data.match(/^\/fetch\s*(.+)$/) 51 | if (f && f.length === 2) { 52 | const key = f[1].trim() 53 | console.log(`fetch '${key}'`) 54 | const res = node.fetch(key) 55 | console.log(`fetched '${key}' = '${res.toString()}'`) 56 | break 57 | } 58 | // otherwise, it's just a message 59 | for (let peer of node.listPeers()) { 60 | node.send(peer, msgpack.encode(msg.data)).then(() => {}, () => {}) 61 | } 62 | break 63 | default: 64 | opt.reject(new Error('unhandled message: ' + msg.type)) 65 | break 66 | } 67 | } catch (e) { 68 | opt.reject(e) 69 | } 70 | }) 71 | 72 | if (process.argv.length > 3) { 73 | await node.connect(process.argv[3]) 74 | } 75 | 76 | for (let e of node.getAddrs()) { 77 | console.log(e) 78 | } 79 | 80 | _log('start') 81 | const handleTerm = () => { 82 | _log('end') 83 | node.close() 84 | process.exit(0) 85 | } 86 | 87 | process.on('SIGINT', handleTerm) 88 | process.on('SIGTERM', handleTerm) 89 | process.on('exit', handleTerm) 90 | process.on('uncaughtException', e => { 91 | console.error(e.stack || e.toString()) 92 | handleTerm() 93 | }) 94 | 95 | setInterval(() => {}, 1000) 96 | } 97 | 98 | function _log (...args) { 99 | // args.unshift((new Date()).toISOString()) 100 | // fs.appendFileSync('_clog.txt', JSON.stringify(args) + '\n') 101 | } 102 | 103 | _main().then(() => {}, (err) => { 104 | console.error(err) 105 | process.exit(1) 106 | }) 107 | -------------------------------------------------------------------------------- /examples/chat/chat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const crypto = require('crypto') 4 | const fs = require('fs') 5 | const path = require('path') 6 | const childProcess = require('child_process') 7 | 8 | const msgpack = require('msgpack-lite') 9 | 10 | const { IpcClient } = require('node-p2p-ipc') 11 | 12 | function _sleep (ms) { 13 | return new Promise((resolve, reject) => { 14 | setTimeout(resolve, ms) 15 | }) 16 | } 17 | 18 | function _spawnP2p (sockName, connectTo, disp) { 19 | const fn = path.resolve(path.join(__dirname, '_chat_p2p.js')) 20 | disp('spawn ' + fn) 21 | 22 | const args = [fn, sockName] 23 | connectTo && args.push(connectTo) 24 | const proc = childProcess.spawn('node', args) 25 | 26 | proc.stdout.on('data', (data) => { 27 | data.toString().split('\n').forEach(e => { 28 | e && disp(e) 29 | }) 30 | }) 31 | 32 | proc.stderr.on('data', (data) => { 33 | data.toString().split('\n').forEach(e => { 34 | e && disp(e) 35 | }) 36 | }) 37 | 38 | proc.on('close', (code) => { 39 | disp('exited ' + code) 40 | process.exit(1) 41 | }) 42 | 43 | return proc 44 | } 45 | 46 | async function _main () { 47 | let connectTo = null 48 | if (process.argv.length > 2) { 49 | connectTo = process.argv[2] 50 | } 51 | 52 | process.stdin.setEncoding('utf8') 53 | process.stdin.resume() 54 | process.stdin.setRawMode(true) 55 | 56 | const sockName = Math.random().toString(36).replace(/\./g, '') 57 | const ipcSocket = './' + sockName + '.ipc.sock' 58 | 59 | let line = '' 60 | 61 | const disp = (...args) => { 62 | process.stdout.write('\u001B[2K\r') 63 | args.length && console.log(...args) 64 | process.stdout.write('c3hat> ' + line) 65 | } 66 | 67 | const clean = () => { 68 | process.stdin.removeListener('data', getc) 69 | process.stdin.setRawMode(false) 70 | process.stdin.pause() 71 | } 72 | 73 | const handleTerm = () => { 74 | clean() 75 | try { 76 | p2pProc.kill() 77 | } catch (e) { /* pass */ } 78 | try { 79 | client.close() 80 | } catch (e) { /* pass */ } 81 | try { 82 | fs.unlinkSync(ipcSocket) 83 | } catch (e) { /* pass */ } 84 | console.log('\nc3hat done') 85 | 86 | process.exit(0) 87 | } 88 | 89 | process.on('SIGINT', handleTerm) 90 | process.on('SIGTERM', handleTerm) 91 | process.on('exit', handleTerm) 92 | process.on('uncaughtException', e => { 93 | console.error(e.stack || e.toString()) 94 | handleTerm() 95 | }) 96 | 97 | const getc = (c) => { 98 | switch (c) { 99 | case '\r': 100 | case '\n': 101 | const tmp = line 102 | line = '' 103 | disp('\n' + name + ': ' + tmp) 104 | ipcMsg('message', tmp).then(() => {}, (err) => { 105 | console.error(err) 106 | process.exit(1) 107 | }) 108 | break 109 | case '\u0004': 110 | case '\u0003': 111 | handleTerm() 112 | break 113 | default: 114 | if (c.charCodeAt(0) === 127) { 115 | line = line.substr(0, line.length - 1) 116 | disp() 117 | } else { 118 | line += c 119 | disp() 120 | } 121 | break 122 | } 123 | } 124 | 125 | const p2pProc = _spawnP2p(sockName, connectTo, (txt) => { 126 | disp('@p2p@ ' + txt) 127 | }) 128 | 129 | // give p2p a chance to gen keys, etc 130 | await _sleep(2000) 131 | 132 | const client = new IpcClient() 133 | await client.connect('ipc://' + ipcSocket) 134 | 135 | const ipcMsg = async (type, data) => { 136 | const resp = await client.call( 137 | msgpack.encode({ type, data })) 138 | if (!resp) { 139 | console.error('bad ipc response', resp) 140 | process.exit(1) 141 | } 142 | if (resp.byteLength) { 143 | return msgpack.decode(resp) 144 | } 145 | } 146 | 147 | const name = await ipcMsg('getName') 148 | disp('\nTHIS NAME:', name) 149 | 150 | client.on('call', (opt) => { 151 | const msg = msgpack.decode(opt.data) 152 | disp('\n' + msg.data.from + ': ' + msg.data.msg) 153 | opt.resolve(Buffer.alloc(0)) 154 | }) 155 | 156 | process.stdin.on('data', getc) 157 | } 158 | 159 | _main().then(() => {}, (err) => { 160 | console.error(err) 161 | process.exit(1) 162 | }) 163 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 'use strict' 3 | 4 | const crypto = require('crypto') 5 | const EventEmitter = require('events') 6 | 7 | const msgpack = require('msgpack-lite') 8 | const PeerId = require('peer-id') 9 | const PeerInfo = require('peer-info') 10 | const pull = require('pull-stream/pull') 11 | const { IpcServer } = require('node-p2p-ipc') 12 | 13 | const { P2pBundle } = require('./libp2p-bundle') 14 | const { $p } = require('./util') 15 | 16 | function _sleep (ms) { 17 | return new Promise((resolve, reject) => { 18 | setTimeout(resolve, ms) 19 | }) 20 | } 21 | 22 | function hash (data) { 23 | if (!(data instanceof Buffer)) { 24 | data = Buffer.from(data) 25 | } 26 | const h = crypto.createHash('sha256') 27 | h.update(data) 28 | return h.digest() 29 | } 30 | 31 | class Node extends EventEmitter { 32 | /** 33 | */ 34 | constructor () { 35 | super() 36 | this._peerCache = new Map() 37 | } 38 | 39 | /** 40 | */ 41 | async init (ipcBind, p2pBind) { 42 | await this._initP2pSocket(Array.isArray(p2pBind) ? p2pBind : [p2pBind]) 43 | await this._initIpcSocket(Array.isArray(ipcBind) ? ipcBind : [ipcBind]) 44 | } 45 | 46 | /** 47 | */ 48 | async close () { 49 | this._peerCache.clear() 50 | this.removeAllListeners() 51 | this.setMaxListeners(0) 52 | if (this._ipc) { 53 | this._ipc.destroy() 54 | this._ipc = null 55 | } 56 | if (this._p2p) { 57 | /// ACK! HACK! is there a better way to do this?? 58 | this._p2p._dht.randomWalk.stop() 59 | 60 | await $p(this._p2p.stop.bind(this._p2p)) 61 | this._p2p = null 62 | } 63 | } 64 | 65 | /** 66 | */ 67 | async connect (endpoint) { 68 | console.log('attempting to dial:', endpoint) 69 | await $p(this._p2p.dial.bind(this._p2p, endpoint)) 70 | console.log('dial complete') 71 | } 72 | 73 | /** 74 | */ 75 | getId () { 76 | return this._p2p.peerInfo.id.toB58String() 77 | } 78 | 79 | /** 80 | */ 81 | getAddrs () { 82 | return this._p2p.peerInfo.multiaddrs.toArray().map( 83 | (a) => a.toString()) 84 | } 85 | 86 | /** 87 | */ 88 | listPeers () { 89 | return Array.from(this._peerCache.keys()) 90 | } 91 | 92 | /** 93 | */ 94 | send (toAddress, data) { 95 | // this needed?? 96 | return this._p2pSend(toAddress, data) 97 | } 98 | 99 | /** 100 | */ 101 | async store (key, val) { 102 | await $p(this._p2p.dht.put.bind(this._p2p.dht, hash(key), Buffer.from(val))) 103 | } 104 | 105 | /** 106 | */ 107 | async fetch (key) { 108 | return await $p(this._p2p.dht.get.bind(this._p2p.dht, hash(key))) 109 | } 110 | 111 | // -- private -- // 112 | 113 | /** 114 | */ 115 | async _cachePeerFromConn (conn) { 116 | const peer = await $p(conn.getPeerInfo.bind(conn)) 117 | this._peerCache.set(peer.id.toB58String(), peer) 118 | return peer.id.toB58String() 119 | } 120 | 121 | /** 122 | */ 123 | async _fetchPeer (peerId) { 124 | if (this._peerCache.has(peerId)) { 125 | return this._peerCache.get(peerId) 126 | } 127 | const pr = this._p2p.peerRouting 128 | const start = Date.now(); 129 | let peer = null 130 | while (Date.now() - start < 5000) { 131 | try { 132 | peer = await $p(pr.findPeer.bind( 133 | pr, PeerId.createFromB58String(peerId))) 134 | } catch (e) { 135 | peer = null 136 | await _sleep(100) 137 | } 138 | } 139 | if (!peer) { 140 | throw new Error('could not find peer') 141 | } 142 | if (peer.id.toB58String() !== peerId) { 143 | throw new Error('wtf') 144 | } 145 | this._peerCache.set(peerId, peer) 146 | return peer 147 | } 148 | 149 | /** 150 | */ 151 | async _p2pSend (toAddress, data) { 152 | const peer = await this._fetchPeer(toAddress) 153 | const result = await new Promise(async (resolve, reject) => { 154 | const conn = await $p(this._p2p.dialProtocol.bind(this._p2p, peer, '/holomsg/0.0.1')) 155 | pull(makeGen(data), conn) 156 | pull(conn, makeSink((data) => { 157 | resolve(data) 158 | })) 159 | }) 160 | return result 161 | } 162 | 163 | /** 164 | */ 165 | async _initP2pSocket (p2pBind) { 166 | const me = await $p(PeerInfo.create) 167 | const id = me.id.toB58String() 168 | 169 | for (let bind of p2pBind) { 170 | me.multiaddrs.add(bind) 171 | } 172 | 173 | const node = this._p2p = new P2pBundle({ 174 | peerInfo: me 175 | }) 176 | 177 | node.handle('/holomsg/0.0.1', async (protocol, conn) => { 178 | const peerId = await this._cachePeerFromConn(conn) 179 | pull(conn, makeSink(async (data) => { 180 | const query = msgpack.decode(data) 181 | switch (query.type) { 182 | case 'ping': 183 | pull(makeGen(msgpack.encode({ 184 | type: 'pong', 185 | originTime: query.now, 186 | srvTime: Date.now() 187 | })), conn) 188 | break 189 | default: 190 | //throw new Error('unexpected holomsg type: ' + JSON.stringify(query)) 191 | const res = await new Promise((resolve, reject) => { 192 | this.emit('message', { 193 | data: { 194 | from: peerId, 195 | msg: query 196 | }, 197 | resolve, 198 | reject 199 | }) 200 | }) 201 | pull(makeGen(data), conn) 202 | } 203 | })) 204 | }) 205 | 206 | // this doesn't seem to ever be emitted 207 | //node.on('peer:discovery', (peer) => { 208 | // console.log('DISCOVERY', peer.id.toB58String()) 209 | //}) 210 | 211 | node.on('peer:connect', async (peer) => { 212 | console.log('new peer', peer.id.toB58String()) 213 | 214 | // side effect: adds this to our peer cache 215 | const result = msgpack.decode(await this._p2pSend( 216 | peer.id.toB58String(), msgpack.encode({ 217 | type: 'ping', 218 | now: Date.now() 219 | }))) 220 | console.log(' -- ping round trip -- ' + ( 221 | Date.now() - result.originTime) + ' ms') 222 | }) 223 | 224 | node.on('peer:disconnect', (peer) => { 225 | peer = peer.id.toB58String() 226 | console.log('lost peer', peer) 227 | this._peerCache.delete(peer) 228 | }) 229 | 230 | await $p(node.start.bind(node)) 231 | 232 | /// ACK! HACK! is there a better way to do this?? 233 | node._dht.randomWalk.start(1, 5000, 10000) 234 | 235 | this.emit( 236 | 'listening', 237 | this.getAddrs()) 238 | } 239 | 240 | /** 241 | */ 242 | async _initIpcSocket (ipcBind) { 243 | this._ipc = new IpcServer() 244 | this._ipc.on('call', opt => { 245 | this.emit('ipcMessage', { 246 | data: opt.data, 247 | resolve: opt.resolve, 248 | reject: opt.reject 249 | }) 250 | }) 251 | await this._ipc.bind(ipcBind) 252 | } 253 | 254 | /** 255 | */ 256 | ipcSendMessage (data) { 257 | return this._ipc.call(data) 258 | } 259 | } 260 | 261 | /** 262 | */ 263 | function makeGen(data) { 264 | let sent = false 265 | return (end, cb) => { 266 | if (end) return cb(end) 267 | if (sent) { 268 | cb(true) 269 | } else { 270 | sent = true 271 | cb(null, data) 272 | } 273 | } 274 | } 275 | 276 | /** 277 | */ 278 | function makeSink (cb) { 279 | return (read) => { 280 | let data = Buffer.alloc(0) 281 | const next = (end, chunk) => { 282 | if (end === true) { 283 | cb(data) 284 | return 285 | } 286 | if (end) throw end 287 | data = Buffer.concat([data, chunk]) 288 | setImmediate(() => { 289 | read(null, next) 290 | }) 291 | } 292 | read(null, next) 293 | } 294 | } 295 | 296 | exports.Node = Node 297 | -------------------------------------------------------------------------------- /lib/libp2p-bundle.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const libp2p = require('libp2p') 4 | const Tcp = require('libp2p-tcp') 5 | const Spdy = require('libp2p-spdy') 6 | const Mplex = require('libp2p-mplex') 7 | const SecIo = require('libp2p-secio') 8 | const KadDht = require('libp2p-kad-dht') 9 | const defaultsDeep = require('@nodeutils/defaults-deep') 10 | 11 | class P2pBundle extends libp2p { 12 | constructor (_options) { 13 | const defaults = { 14 | modules: { 15 | transport: [ Tcp ], 16 | streamMuxer: [ Mplex ], 17 | // streamMuxer: [ Spdy ], 18 | // connEncryption: [ SecIo ], 19 | dht: KadDht 20 | }, 21 | config: { 22 | dht: { 23 | kBucketSize: 20 24 | }, 25 | EXPERIMENTAL: { 26 | dht: true 27 | } 28 | } 29 | } 30 | 31 | super(defaultsDeep(_options, defaults)) 32 | } 33 | } 34 | 35 | exports.P2pBundle = P2pBundle 36 | -------------------------------------------------------------------------------- /lib/util.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | /** 4 | * Execute a callback function as a promise. 5 | * You may need to bind any parameters to the function. 6 | * 7 | * @example 8 | * const data = await $p(fs.readFile.bind(fs, 'my-file.txt')) 9 | */ 10 | exports.$p = function $p (fn) { 11 | return new Promise((resolve, reject) => { 12 | fn((err, res) => { 13 | if (err) return reject(err) 14 | resolve(res) 15 | }) 16 | }) 17 | } 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-js-libp2p-ipc", 3 | "version": "0.0.1", 4 | "description": "Holochain IPC connector to the javascript (node-js) version of libp2p", 5 | "main": "lib/index.js", 6 | "scripts": { 7 | "docs": "", 8 | "test": "standard --fix '**/*.js' && npm run docs && nyc ./node_modules/mocha/bin/mocha 'lib/**/*.test.js'", 9 | "coverage": "node -e \"require('opn')('coverage/lcov-report/index.html')\"" 10 | }, 11 | "license": "Apache-2.0", 12 | "devDependencies": { 13 | "chai": "^4.1.2", 14 | "jsdoc-to-markdown": "^4.0.1", 15 | "mocha": "^5.2.0", 16 | "nyc": "^12.0.2", 17 | "opn": "^5.3.0", 18 | "sinon": "^6.2.0", 19 | "standard": "^11.0.1" 20 | }, 21 | "dependencies": { 22 | "@nodeutils/defaults-deep": "^1.1.0", 23 | "libp2p": "^0.23.1", 24 | "libp2p-kad-dht": "^0.10.2", 25 | "libp2p-mplex": "^0.8.0", 26 | "libp2p-secio": "^0.10.0", 27 | "libp2p-spdy": "^0.12.1", 28 | "libp2p-tcp": "^0.12.1", 29 | "msgpack-lite": "^0.1.26", 30 | "node-p2p-ipc": "github:holochain/node-p2p-ipc#1a9ee69c832015546d8ad46838275305eced673b", 31 | "peer-id": "^0.11.0", 32 | "pull-stream": "^3.6.9" 33 | }, 34 | "standard": { 35 | "env": { 36 | "mocha": true 37 | } 38 | }, 39 | "nyc": { 40 | "check-coverage": true, 41 | "per-file": false, 42 | "lines": 80, 43 | "statements": 80, 44 | "functions": 80, 45 | "branches": 80, 46 | "all": true, 47 | "include": [ 48 | "./lib/**/*.js" 49 | ], 50 | "reporter": [ 51 | "lcov", 52 | "text-summary" 53 | ] 54 | } 55 | } 56 | --------------------------------------------------------------------------------