Recommended way of constructing libp2p peer address & opening up stream

Hi there, I’m pretty new to IPFS and have been going through tutorials (around libp2p) for the past couple of days, the ones I used are https://docs.libp2p.io/tutorials/getting-started/go/ and https://github.com/libp2p/go-libp2p-examples. However, I noticed that sometimes the peer address was created with peerstore.AddrInfoToP2pAddrs but in another tutorial it might be manually built with hostAddr, _ := ma.NewMultiaddr(fmt.Sprintf("/ipfs/%s", basicHost.ID().Pretty())) followed by addr.Encapsulate(hostAddr) (where addr is basicHost.Addrs()[0] e.g. /ip4/1.2.3.4/tcp/80). I checked the implemenetaiton and it seems like the second is pretty much the internals of the first, but since they were both in the tutorials I wonder if there’s any scenario where we want to use one but not the other? Sorry in advance if this is a dumb question :stuck_out_tongue:

I would preferentially use peerstore.AddrInfoToP2pAddrs.

@hector Thanks for the reply! I guess a follow-up of similar nature is that I saw places where there’s call to host.PeerStore().AddAddr(..) before creating a new stream using host.NewStream(...) with another peer, and there’re also places where there’s call to host.Connect(...) which internally does the saving to peerstore as well. Then as I read further, in the comment of host.NewStream, it says if there's no connection to p, attempt to create one (which I guess also calls Connect to create a connection if there isn’t one?). So I wonder does the tutorial just use the combination of those 3 as a means to educate what’s happening under the hood by making those calls explicitly, while in the real world scenario do people just use host.NewStream directly (without explicitly connecting to peers / add peers to peerstore)?

You’re correct, NewStream does the things…

  1. Unless you want to AddAddr with custom options (i.e. special/permanent ttl)
  2. Unless you want to stablish/test connectivity first before you jump into opening streams.

Final flow will depend on application-specific needs.