diff --git a/p2p/host/basic/basic_host.go b/p2p/host/basic/basic_host.go index 606cb67b9a..530b998ac0 100644 --- a/p2p/host/basic/basic_host.go +++ b/p2p/host/basic/basic_host.go @@ -232,6 +232,16 @@ func NewHost(ctx context.Context, net network.Network, opts *HostOpts) (*BasicHo net.SetStreamHandler(h.newStreamHandler) + // register to be notified when the network's listen addrs change, + // so we can update our address set and push events if needed + listenHandler := func(network.Network, ma.Multiaddr) { + h.SignalAddressChange() + } + net.Notify(&network.NotifyBundle{ + ListenF: listenHandler, + ListenCloseF: listenHandler, + }) + return h, nil } diff --git a/p2p/host/basic/basic_host_test.go b/p2p/host/basic/basic_host_test.go index 3b2033479d..4a8a89a0e7 100644 --- a/p2p/host/basic/basic_host_test.go +++ b/p2p/host/basic/basic_host_test.go @@ -94,6 +94,38 @@ func TestMultipleClose(t *testing.T) { } +func TestSignedPeerRecordWithNoListenAddrs(t *testing.T) { + ctx := context.Background() + + h := New(swarmt.GenSwarm(t, ctx, swarmt.OptDialOnly)) + + if len(h.Addrs()) != 0 { + t.Errorf("expected no listen addrs, got %d", len(h.Addrs())) + } + + // now add a listen addr + err := h.Network().Listen(ma.StringCast("/ip4/0.0.0.0/tcp/0")) + if err != nil { + t.Fatal(err) + } + if len(h.Addrs()) < 1 { + t.Errorf("expected at least 1 listen addr, got %d", len(h.Addrs())) + } + + // we need to sleep for a moment, since the signed record with the new addr is + // added async + time.Sleep(20 * time.Millisecond) + + cab, ok := peerstore.GetCertifiedAddrBook(h.Peerstore()) + if !ok { + t.Fatalf("peerstore doesn't support certified addrs") + } + rec := cab.GetPeerRecord(h.ID()) + if rec == nil { + t.Fatalf("no signed peer record in peerstore for new host %s", h.ID()) + } +} + func TestProtocolHandlerEvents(t *testing.T) { ctx := context.Background() h := New(swarmt.GenSwarm(t, ctx))