Libp2p-js relay behind NAT

Hi
I want to implement the below scenario
Screen Shot 2022-05-20 at 1.25.32 AM
I have many peers behind NAT, beside these I have a public node to relay these peers

I want node 2 connect to node 1, similarly to node 3 connect to node 1, after that, nodes 2 and 3 can talk to each other with encrypted messages. But I can’t find a good solution for this.

I tried to get help from this example (js-libp2p/examples/peer-and-content-routing at master · libp2p/js-libp2p · GitHub) but it did not help me

Hi,

node 1 has to be configured as a relayer. You can use a configuration like this:

var id = await createRSAPeerId()
const node = await createLibp2p({
  peerId: id,
  addresses: {
    listen: [
      '/ip4/0.0.0.0/tcp/34100/ws',
    ],
  },
  dht: new KadDHT(),
  transports: [new WebSockets()],
  connectionEncryption: [new Noise()],
  streamMuxers: [new Mplex()],
  pubsub: new GossipSub(),
  relay: {
    enabled: true,
    hop: {
      enabled: true
    },
    advertise: {
      enabled: true,
    }
  }
})

You need to note the Public IP of the relayer and the peerId.

For the normal nodes you can use a configuration like this:

peerId = createRSAPeerId();
const node = await createLibp2p( {
  peerId: id,
  transports: [
    new WebSockets(),
  ],
  connectionEncryption: [new Noise()],
  streamMuxers: [
    new Mplex()
  ],
  peerDiscovery: [
    new Bootstrap({
       list: ["/ip4/X.X.X.X/tcp/34100/ws/p2p/Qma5QbMXc4DsZCa55vGhQAhK1ZLxy4ZBFTQALRyNCjYVYg"],
    })
  ],
  dht: new KadDHT(),
  pubsub: new GossipSub(),
  addresses: {
    listen: [
      "/ip4/0.0.0.0/tcp/0/ws",
    ],
  },
  connectionManager: {
    autoDial: true
  },
  relay: {
    enabled: true,
    autoRelay: {
      enabled: true,
      maxListeners: 10
    }
  },
})

Replace X.X.X.X with the Public IP of the relayer and Qma5QbMXc4DsZCa55vGhQAhK1ZLxy4ZBFTQALRyNCjYVYg with the peerId of your relayer.

With this the NAT-Nodes should automatically connect to the relayer, and discover each other. through KadDHT.

Be aware, the connections between the NAT-Nodes are not direct as in your diagram. All traffic goes through the public node.

Also checkout the auto-relay example.

Regards Sneaker