package p2p import ( "context" "crypto/rand" "errors" "log/slog" "net" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" madns "github.com/multiformats/go-multiaddr-dns" ) // fakeDNS answers TXT lookups from a table the test can change. type fakeDNS struct { mu sync.Mutex txt map[string][]string err error } func (f *fakeDNS) set(name string, records ...string) { f.mu.Lock() defer f.mu.Unlock() if f.txt == nil { f.txt = map[string][]string{} } f.txt[name] = records } func (f *fakeDNS) fail(err error) { f.mu.Lock() defer f.mu.Unlock() f.err = err } func (f *fakeDNS) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) { return nil, errors.New("no addresses in this fake") } func (f *fakeDNS) LookupTXT(_ context.Context, name string) ([]string, error) { f.mu.Lock() defer f.mu.Unlock() if f.err != nil { return nil, f.err } return f.txt[name], nil } func resolverFor(t *testing.T, f *fakeDNS) *madns.Resolver { t.Helper() r, err := madns.NewResolver(madns.WithDefaultResolver(f)) if err != nil { t.Fatal(err) } return r } func connected(a *tnode, b *tnode) bool { return a.host.Network().Connectedness(b.ID()) == network.Connected } func TestBootstrapNameIsResolvedAndDialled(t *testing.T) { a := startNode(t, nil, "u1x") dns := &fakeDNS{} dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0], "dnsaddr=/ip4/192.0.2.1/tcp/1", "not a record") b := startNodeWith(t, nil, func(c *Config) { c.Bootstrap = []string{"/dnsaddr/boot.test"} c.Resolver = resolverFor(t, dns) }, "u1x") eventually(t, "b reaches a through the name", func() bool { return connected(b, a) }) } func TestBootstrapNameKeepsTheLastAnswerWhenDNSFails(t *testing.T) { a := startNode(t, nil, "u1x") dns := &fakeDNS{} dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0]) b := startNodeWith(t, nil, func(c *Config) { c.Bootstrap = []string{"/dnsaddr/boot.test"} c.Resolver = resolverFor(t, dns) }, "u1x") eventually(t, "first connection", func() bool { return connected(b, a) }) dns.fail(errors.New("servfail")) b.host.Network().ClosePeer(a.ID()) eventually(t, "b dials again from its remembered answer", func() bool { return connected(b, a) }) } // stuckDNS never answers and ignores cancellation, like a resolver whose // server drops packets. type stuckDNS struct{ release chan struct{} } func (s stuckDNS) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) { <-s.release return nil, errors.New("released") } func (s stuckDNS) LookupTXT(context.Context, string) ([]string, error) { <-s.release return nil, errors.New("released") } func TestStoppingDoesNotWaitForAStuckResolver(t *testing.T) { dns := stuckDNS{release: make(chan struct{})} defer close(dns.release) r, err := madns.NewResolver(madns.WithDefaultResolver(dns)) if err != nil { t.Fatal(err) } var logged strings.Builder log := slog.New(slog.NewTextHandler(&logged, nil)) b, err := newBootstrapper([]string{"/dnsaddr/boot.test"}, r, "", log) if err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { b.peers(ctx) close(done) }() time.Sleep(50 * time.Millisecond) cancel() // the node is stopping select { case <-done: case <-time.After(time.Second): t.Fatal("stopping waited for a resolver that never answers") } if logged.Len() != 0 { t.Errorf("stopping is not a DNS failure, but it was logged: %s", logged.String()) } } func TestBootstrapEntriesAreCheckedUpFront(t *testing.T) { id := "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo" for addr, ok := range map[string]bool{ "/dnsaddr/allmende.example": true, "/ip4/203.0.113.5/tcp/4001/p2p/" + id: true, "/dns4/node.example/tcp/4001/p2p/" + id: true, "/ip4/203.0.113.5/tcp/4001": false, // no peer ID to verify "allmende.example": false, "/dnsaddr/": false, "": false, } { _, err := newBootstrapper([]string{addr}, nil, "", testLogger()) if (err == nil) != ok { t.Errorf("%q: error = %v, want ok = %v", addr, err, ok) } } } func TestBootstrapNeverDialsItself(t *testing.T) { a := startNode(t, nil) dns := &fakeDNS{} dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0]) b, err := newBootstrapper([]string{"/dnsaddr/boot.test", a.Addrs()[0]}, resolverFor(t, dns), a.ID(), testLogger()) if err != nil { t.Fatal(err) } if got := b.peers(context.Background()); len(got) != 0 { t.Fatalf("a bootstrap node must not dial itself: %v", got) } other, _ := newBootstrapper([]string{"/dnsaddr/boot.test"}, resolverFor(t, dns), peer.ID("someone else"), testLogger()) if got := other.peers(context.Background()); len(got) != 1 || got[0].ID != a.ID() { t.Fatalf("got %v", got) } } func TestPeersFromEarlierRunsAreRedialled(t *testing.T) { a := startNode(t, nil, "u1x") path := filepath.Join(t.TempDir(), "peers.json") ai := peer.AddrInfo{ID: a.ID(), Addrs: a.host.Addrs()} err := writePeerCache(path, []cachedPeer{{ID: a.ID().String(), Addrs: directAddrs(ai.Addrs), Seen: time.Now().Unix()}}) if err != nil { t.Fatal(err) } // No bootstrap, no mDNS, no DHT: only the remembered address can lead to a. b := startNodeWith(t, nil, func(c *Config) { c.PeerCache = path }, "u1x") eventually(t, "b finds a from its cache", func() bool { return connected(b, a) }) } func TestPeersAreRememberedOnTheWayOut(t *testing.T) { a := startNode(t, nil, "u1x") path := filepath.Join(t.TempDir(), "peers.json") b := startNodeWith(t, nil, func(c *Config) { c.PeerCache = path }, "u1x") connect(t, b, a) eventually(t, "connected", func() bool { return connected(b, a) }) b.Close() // saves once more as it stops got := readPeerCache(path, time.Now()) if len(got) != 1 || got[0].ID != a.ID().String() || len(got[0].Addrs) == 0 { t.Fatalf("cache = %+v, want a's address", got) } for _, addr := range got[0].Addrs { if strings.Contains(addr, "p2p-circuit") { t.Errorf("a relayed address was remembered: %s", addr) } } } func TestPeerCacheIgnoresStaleAndBrokenEntries(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "peers.json") id := "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo" now := time.Now() err := writePeerCache(path, []cachedPeer{ {ID: id, Addrs: []string{"/ip4/127.0.0.1/tcp/1"}, Seen: now.Unix()}, {ID: id + "x", Addrs: []string{"/ip4/127.0.0.1/tcp/2"}, Seen: now.Unix()}, // not a peer ID {ID: id, Addrs: nil, Seen: now.Unix()}, // nothing to dial {ID: id, Addrs: []string{"/ip4/127.0.0.1/tcp/3"}, Seen: now.Add(-31 * 24 * time.Hour).Unix()}, // too old }) if err != nil { t.Fatal(err) } if got := readPeerCache(path, now); len(got) != 1 || got[0].Addrs[0] != "/ip4/127.0.0.1/tcp/1" { t.Fatalf("got %+v", got) } for name, content := range map[string]string{"garbage": "{not json", "empty": ""} { p := filepath.Join(dir, name) if err := os.WriteFile(p, []byte(content), 0o600); err != nil { t.Fatal(err) } if got := readPeerCache(p, now); got != nil { t.Errorf("%s: want an empty cache, got %+v", name, got) } } if got := readPeerCache(filepath.Join(dir, "missing"), now); got != nil { t.Errorf("missing file: %+v", got) } } func TestPeerCacheKeepsTheNewestEntries(t *testing.T) { path := filepath.Join(t.TempDir(), "peers.json") var many []cachedPeer for i := 0; i < maxCachedPeers+20; i++ { _, pub, err := crypto.GenerateEd25519Key(rand.Reader) if err != nil { t.Fatal(err) } id, err := peer.IDFromPublicKey(pub) if err != nil { t.Fatal(err) } many = append(many, cachedPeer{ID: id.String(), Addrs: []string{"/ip4/127.0.0.1/tcp/1"}, Seen: int64(1000 + i)}) } if err := writePeerCache(path, many); err != nil { t.Fatal(err) } got := readPeerCache(path, time.Unix(2000, 0)) if len(got) != maxCachedPeers || got[0].Seen != int64(1000+maxCachedPeers+19) { t.Fatalf("kept %d, newest first = %d", len(got), got[0].Seen) } } // Two nodes that only know a bootstrap node must find each other through the // DHT, not by being introduced. func TestDHTFindsPeersOfTheSameRegion(t *testing.T) { r := startNodeWith(t, nil, func(c *Config) { c.Public, c.DHT, c.DiscoverInterval = true, true, 200*time.Millisecond }, "u1x") seed := func(c *Config) { c.Bootstrap = []string{r.Addrs()[0]} c.DHT, c.DiscoverInterval = true, 200*time.Millisecond } a := startNodeWith(t, nil, seed, "u1x") b := startNodeWith(t, nil, seed, "u1x") other := startNodeWith(t, nil, seed, "u1y") // a different region: not for a or b eventually(t, "a and b are connected directly", func() bool { return connected(a, b) && connected(b, a) }) if connected(a, other) || connected(b, other) { t.Error("a node of another region was dialled; discovery is per region") } } // A node that cannot be reached directly takes a reservation on a bootstrap // node, so that others can still get to it through that relay. (libp2p only // advertises relay addresses built on public IPs, so on loopback the test // dials the relayed path itself; that works only if the reservation exists.) func TestNodeBehindANATIsReachableThroughTheBootstrapNode(t *testing.T) { r := startNodeWith(t, nil, func(c *Config) { c.Public = true }, "u1x") a := startNodeWith(t, nil, func(c *Config) { c.Bootstrap = []string{r.Addrs()[0]} c.ForcePrivate = true c.RelayBootDelay = 100 * time.Millisecond }, "u1x") b := startNode(t, nil, "u1x") // knows nothing of a connect(t, b, r) via := r.Addrs()[0] + "/p2p-circuit/p2p/" + a.ID().String() ai, err := peer.AddrInfoFromString(via) if err != nil { t.Fatal(err) } eventually(t, "b reaches a through r", func() bool { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() ctx = network.WithAllowLimitedConn(ctx, "test") return b.host.Connect(ctx, *ai) == nil && b.host.Network().Connectedness(a.ID()) != network.NotConnected }) }