libp2p / js-libp2p

The JavaScript Implementation of libp2p networking stack.
https://libp2p.github.io/js-libp2p/
Other
2.33k stars 446 forks source link

protocol matchFunction not working properly #455

Closed sce9sc closed 1 year ago

sce9sc commented 5 years ago

When using the example illustrated here with some modifications an error was thrown.

After investigating a little I found that if you console.log(requestedProtocol) the function is running multiple time.

/* eslint-disable no-console */
'use strict'

const libp2p = require('libp2p')
const TCP = require('libp2p-tcp')
const SPDY = require('libp2p-spdy')
const Mplex = require('libp2p-mplex')
const PeerInfo = require('peer-info')
const waterfall = require('async/waterfall')
const parallel = require('async/parallel')
const series = require('async/series')
const pull = require('pull-stream')
const defaultsDeep = require('@nodeutils/defaults-deep')
const KadDHT = require('libp2p-kad-dht')
const secio = require('libp2p-secio')
const Bootstrap = require('libp2p-bootstrap')
const MulticastDNS = require('libp2p-mdns')
const Protector  = require('libp2p/src/pnet')
const writeKey  = require('libp2p/src/pnet').generate;

// Create a buffer and write the swarm key to it
const swarmKey = Buffer.alloc(95)
writeKey(swarmKey)

const swarmKey1 = Buffer.alloc(95)
writeKey(swarmKey1)

console.log(swarmKey)
console.log(swarmKey1)

class MyBundle extends libp2p {
    constructor (_options,d) {
        console.log(d)
        const defaults = {
            modules: {
                transport: [ TCP ],
                streamMuxer: [ Mplex ],
                connEncryption: [ secio ],
                // we add the DHT module that will enable Peer and Content Routing
                dht: KadDHT,
                //peerDiscovery: [ MulticastDNS ] // if using MulticastDNS all found will be connected as it seems
                connProtector: new Protector(d ?swarmKey: swarmKey1)
            },
            config: {
                dht: {
                    kBucketSize: 20,
                    enabled: true,
                    randomWalk: {
                        enabled: true,      // Allows to disable discovery (enabled by default)
                        interval: 300e3,
                        timeout: 10e3
                    }
                }
            }

        }

        super(defaultsDeep(_options, defaults))
    }
}

function createNode (callback,d) {
    let node

    waterfall([
        (cb) => PeerInfo.create(cb),
        (peerInfo, cb) => {
            peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
            node = new MyBundle({
                peerInfo
            },d)
            node.start(cb)
        }
    ], (err) => callback(err, node))
}

parallel([
    (cb) => createNode(cb,true),
    (cb) => createNode(cb,true),
    (cb) => createNode(cb, true)
], (err, nodes) => {
    if (err) { throw err }

    const node1 = nodes[0]
    const node2 = nodes[1]
    const node3 = nodes[2]

    node1.handle('/node-1', (protocol, conn) => {
        pull(
            conn,
            pull.map((v) => v.toString()),
            pull.log()
        )
    },(myProtocol, requestedProtocol, callback) => {
        console.log('requestedProtocol',requestedProtocol)
        //console.log('requestedProtocol',requestedProtocol)
        // This is all custom. I'm checking the base path matches, think of this
        // as a HTTP routing table.
        if (requestedProtocol.includes(myProtocol)) {
            //console.log('requestedProtocol',requestedProtocol)
            const params = requestedProtocol.replace(myProtocol+'/', '')
            console.log(params)
            callback(null, true)
        } else {

            callback(null, true)
        }

    })

    node2.handle('/node-2', (protocol, conn) => {
        pull(
            conn,
            pull.map((v) => v.toString()),
            pull.log()
        )
    })

    node3.handle('/node-3', (protocol, conn) => {
        pull(
            conn,
            pull.map((v) => v.toString()),
            pull.log()
        )
    })

    console.log(node1.peerInfo)

    series([
        (cb) => node1.dialProtocol(node2.peerInfo, '/node-2', (err, conn) => {
            if (err) { throw err }
            pull(pull.values(['from 1 to 2']), conn)
            cb()
        }),
        (cb) => node2.dialProtocol(node1.peerInfo, '/node-1/test', (err, conn) => {
            if (err) { throw err }
            pull(pull.values(['from 2 to 1']), conn)
            cb()
        }),
        (cb) => node3.dial(node1.peerInfo, cb),
        (cb) => setTimeout(cb, 6000)
    ], (err) => {
        if (err) { throw err }
        console.log('Addresses by which both peers are connected')

        node1.peerBook
            .getAllArray()
            .forEach((peer) => console.log('node 1 to :', peer.isConnected().toString()))
        node2.peerBook
            .getAllArray()
            .forEach((peer) => console.log('node 2 to :', peer.isConnected().toString()))

        node3.peerBook
            .getAllArray()
            .forEach((peer) => console.log('node 3 to :', peer.isConnected().toString()))

    })
})

Output

requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /mplex/6.7.0
requestedProtocol /libp2p/circuit/relay/0.1.0
requestedProtocol /ipfs/kad/1.0.0
requestedProtocol /ipfs/id/1.0.0
Addresses by which both peers are connected
node 1 to : /ip4/127.0.0.1/tcp/63708/ipfs/QmV1zx82XbhBc5CbAeUWyg48rPxQ16Qha9MCGupqXswgXs
node 1 to : /ip4/127.0.0.1/tcp/63709/ipfs/QmfKrk9wjk191tzafTfgBuevVR8GMmgf34b1fWtxB2ML26
node 2 to : /ip4/127.0.0.1/tcp/63707/ipfs/QmQXaRaVgEUc3bPMvhyNC83SNB8f1yD7besRkgiji1b7NE
node 3 to : /ip4/127.0.0.1/tcp/63707/ipfs/QmQXaRaVgEUc3bPMvhyNC83SNB8f1yD7besRkgiji1b7NE
requestedProtocol /ipfs/kad/1.0.0
requestedProtocol /ipfs/kad/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0
requestedProtocol /ipfs/id/1.0.0

dependencies used:

 "@nodeutils/defaults-deep": "^1.1.0",
    "libp2p": "^0.26.1",
    "libp2p-bootstrap": "^0.9.7",
    "libp2p-circuit": "^0.3.x",
    "libp2p-delegated-content-routing": "^0.2.x",
    "libp2p-delegated-peer-routing": "^0.2.x",
    "libp2p-floodsub": "^0.17.x",
    "libp2p-gossipsub": "^0.0.x",
    "libp2p-kad-dht": "^0.15.x",
    "libp2p-mdns": "^0.12.x",
    "libp2p-mplex": "^0.8.x",
    "libp2p-secio": "^0.11.x",
    "libp2p-spdy": "^0.13.x",
    "libp2p-tcp": "^0.13.x",
    "libp2p-webrtc-star": "^0.16.x",
    "libp2p-websocket-star": "^0.10.x",
    "libp2p-websocket-star-rendezvous": "^0.4.x",
    "libp2p-websockets": "^0.12.x"

Also even after returning callback(null, true); The handle function is not fired

wemeetagain commented 1 year ago

The code has changed significantly since this issue has opened. Closing due to it being stale.