package p2p import ( "context" "testing" "time" "github.com/libp2p/go-libp2p" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager" ) // inboundLimit is the cap on inbound connections the node's resource manager enforces. func inboundLimit(t *testing.T, n *Node) int { t.Helper() var limit int err := n.host.Network().ResourceManager().ViewSystem(func(s network.ResourceScope) error { l, ok := s.(rcmgr.ResourceScopeLimiter) if !ok { t.Fatalf("the system scope %T exposes no limit", s) } limit = l.Limit().GetConnLimit(network.DirInbound) return nil }) if err != nil { t.Fatal(err) } return limit } func TestAPublicNodeAcceptsManyMoreConnectionsThanLibp2pDoesByDefault(t *testing.T) { public := startNodeWith(t, nil, func(c *Config) { c.Public = true }) if got := inboundLimit(t, public.Node); got != DefaultPublicConns { t.Errorf("a --public node accepts %d inbound connections, want %d", got, DefaultPublicConns) } private := startNode(t, nil) if got := inboundLimit(t, private.Node); got == DefaultPublicConns { t.Errorf("a node that is not --public must keep libp2p's own default, got %d", got) } opted := startNodeWith(t, nil, func(c *Config) { c.Public = true; c.MaxConns = -1 }) if got := inboundLimit(t, opted.Node); got == DefaultPublicConns { t.Errorf("MaxConns -1 must keep libp2p's default even when public, got %d", got) } } func TestTheConnectionLimitIsEnforced(t *testing.T) { const limit = 3 n := startNodeWith(t, nil, func(c *Config) { c.Public = true; c.MaxConns = limit }) if got := inboundLimit(t, n.Node); got != limit { t.Fatalf("limit is %d, want %d", got, limit) } info, err := peer.AddrInfoFromString(n.Addrs()[0]) if err != nil { t.Fatal(err) } connected := 0 for i := 0; i < 8; i++ { h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) if err != nil { t.Fatal(err) } t.Cleanup(func() { h.Close() }) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) if h.Connect(ctx, *info) == nil { connected++ } cancel() } if connected < limit { t.Errorf("only %d of the first %d connections were accepted", connected, limit) } time.Sleep(500 * time.Millisecond) if got := len(n.host.Network().Conns()); got > limit { t.Errorf("the node holds %d connections, over its limit of %d", got, limit) } }