Need help using @chainsafe/libp2p-gossipsub

Hi, I’m trying to use gossipsub to build a decentralized mobile chat app @ ETHIndia.

I’m using GitHub - ChainSafe/js-libp2p-gossipsub: TypeScript implementation of Gossipsub but need some help

Here is the code to setup libp2p node:

import { GossipSub } from '@chainsafe/libp2p-gossipsub'

const createNode = async () => {
    const node = await createLibp2p({
        addresses: {
            // add a listen address (localhost) to accept TCP connections on a random port
            listen: ['/ip4/0.0.0.0/tcp/0/ws']
        },
        // transports: [tcp()],
        transports: [webSockets({
            filters: all
        })],
        connectionEncryption: [noise()],
        streamMuxers: [mplex()],
        peerDiscovery: [
            bootstrap({
                list: bootstrapMultiaddrs,
            })
        ],
        connectionManager: {
            autoDial: true,
        },
        dht: kadDHT(),
        // pubsub: floodsub()
        pubsub: new GossipSub({
            emitSelf: true
        })
    })
    return node
}

const options = {}
const gsub = new GossipSub(node, options)
await gsub.start()

gsub.on('fruit', (data) => {
    console.log(data)
})

gsub.subscribe('fruit')

gsub.publish('fruit', new TextEncoder().encode('banana'))

And here is the error I’m facing right now:

gsub.on('fruit', (data) => {
     ^

TypeError: gsub.on is not a function
    at file:///home/boogeyman/GIT/Hub/ohjihq/js-libp2p-playground/src/index.js:62:6
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.10.0

You should take a look at the libp2p pubsub example if you haven’t already:

I think the reademe examples in ChainSafe’s Gossipsub is outdated, the GossipSub class extends libp2p’s EventEmitter which extends EventTarget so instead of using on you probably want to use addEventListener:

import { gossipsub } from '@chainsafe/libp2p-gossipsub'

const gsub = gossipsub(options)(node)

await gsub.start()

gsub.addEventListener('message', (message) => {
  console.log(`${message.detail.topic}:`, new TextDecoder().decode(message.detail.data))
})

gsub.subscribe('fruit')

gsub.publish('fruit', new TextEncoder().encode('banana'))

// ...
1 Like

Hi @saul ,

Thank you!

I am now able to use the gossipsub function with my libp2p node and options.

With selfEmit: true in the config, I am able to see my own messages.

However I am unable to see the messages sent by other peers.

The nodes need to be connected and subscribed to the same topic to gossip about messages.

Also your original code has two instances of gossipsub, this may lead to bugs/confusion you should probably be doing the following (as opposed to my last code example):

const node = await createLibp2p({
  // ...
  pubsub: gossipsub({
    emitSelf: true
   })
  // ...
});

// ...

node.pubsub.subscribe("fruit");

node.pubsub.addEventListener("message", (evt) => {
  // ...
});