Pubsub works on node creation but fails on subsequent runs

I am running a very simple pubsub test in node.js.

The script:

import * as IPFS from 'ipfs-core'
import { Buffer } from 'buffer'

const main = async () => {
  const topic = 'topic'

  const ipfs1 = await IPFS.create({
    config: {
      Addresses: {
        API: '/ip4/127.0.0.1/tcp/5002',
        RPC: '/ip4/127.0.0.1/tcp/5003',
        Gateway: '/ip4/127.0.0.1/tcp/8085',
        Swarm: ['/ip4/0.0.0.0/tcp/4012', '/ip4/127.0.0.1/tcp/4013/ws']
      }
    },
    repo: 'ipfs1'
  })

  const identity1 = await ipfs1.id()

  await ipfs1.pubsub.subscribe(topic, (msg) => {
    console.log('ipfs1 subscription', msg.data.toString())
  })

  const ipfs2 = await IPFS.create({
    config: {
      Addresses: {
        API: '/ip4/127.0.0.1/tcp/5004',
        RPC: '/ip4/127.0.0.1/tcp/5005',
        Gateway: '/ip4/127.0.0.1/tcp/8086',
        Swarm: ['/ip4/0.0.0.0/tcp/4014', '/ip4/127.0.0.1/tcp/4015/ws']
      }
    },
    repo: 'ipfs2'
  })

  const identity2 = await ipfs2.id()

  await ipfs2.pubsub.subscribe(topic, (msg) => {
    console.log('ipfs2 subscription', msg.data.toString())
  })

  await ipfs2.swarm.connect(identity1.id)

  const bufferedMsg = Buffer.from('hello from ipfs1')

  setInterval(async () => {
    console.log('subscribed peers (via ipfs1)', await ipfs1.pubsub.peers(topic))
    console.log('subscribed peers (via ipfs2)', await ipfs2.pubsub.peers(topic))
    await ipfs1.pubsub.publish(topic, bufferedMsg)
  }, 5000)
}

main()

The concept is simple; stand up two IPFS nodes (ipfs1 and ipfs2) on localhost, connect one to the other, subscribe to the same topic, then have one node publish messages.

On the initial run (I.e. when no IPFS repos exist) it works fine. The output of the setInterval shows subscribed peers and both subscribe callbacks get fired.

However, stop the node app and start it again and ipfs2’s pubsub subscribe callback no longer fires.

The only way to solve the issue is to delete one of the two created repos; ipfs1 or ipfs2. Once one of the repos is deleted, re-running the script results in a successful ipfs2 subscribe callback. Stop index.js and start again and no ipfs2 subscribe callback.

The same also happens if ipfs1 and ipfs2 are reversed.

1 Like

To narrow it down, deleting the datastore directory from either of the repos resolves the problem (although deleting ipfs1’s datastore can result in the subscribe message from ipfs2 returning as ascii codes rather than the actual message).

I’m not sure exactly what fixed it, but upgrading to ipfs-core 0.18.0 fixed the problem. I’m assuming there has been a fix to libp2p between v0.40 (which ipfs-core 0.17.0 used) and v0.42 (which ipfs-core 0.18.0 uses).

1 Like