package p2p import ( "context" "encoding/json" "errors" "io" "log/slog" "os" "strings" "testing" "time" pubsub "github.com/libp2p/go-libp2p-pubsub" pb "github.com/libp2p/go-libp2p-pubsub/pb" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/store" ) const ( difficulty = 6 msgDifficulty = 4 ) // testLogger is silent unless P2P_DEBUG is set. func testLogger() *slog.Logger { if os.Getenv("P2P_DEBUG") != "" { return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug})) } return slog.New(slog.NewTextHandler(io.Discard, nil)) } type tnode struct { *Node s *store.Store root *identity.Identity dev *identity.Device } func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode { t.Helper() return startNodeWith(t, root, nil, regions...) } func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), regions ...string) *tnode { t.Helper() if root == nil { root, _, _ = identity.NewRoot() } dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour) if err != nil { t.Fatal(err) } s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty}) if err != nil { t.Fatal(err) } cfg := Config{ Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, Regions: regions, Difficulty: difficulty, MessageDifficulty: msgDifficulty, SyncPageSize: 3, RedialInterval: 200 * time.Millisecond, Logger: testLogger(), } if tweak != nil { tweak(&cfg) } n, err := New(context.Background(), cfg) if err != nil { t.Fatal(err) } t.Cleanup(func() { n.Close(); s.Close() }) return &tnode{Node: n, s: s, root: root, dev: dev} } func (tn *tnode) listing(t *testing.T, geohash string) *listing.Listing { t.Helper() id, _ := listing.NewID() now := time.Now() l := &listing.Listing{ Version: listing.Version, ID: id, Seq: 1, CreatedAt: now.Unix(), ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(), Kind: "rent", Category: "apartment", Geohash: geohash, Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"}, Title: "Wohnung", } if err := l.Seal(tn.dev, difficulty); err != nil { t.Fatal(err) } return l } func connect(t *testing.T, from, to *tnode) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := from.Connect(ctx, to.Addrs()[0]); err != nil { t.Fatal(err) } } func eventually(t *testing.T, what string, cond func() bool) { t.Helper() deadline := time.Now().Add(15 * time.Second) for time.Now().Before(deadline) { if cond() { return } time.Sleep(50 * time.Millisecond) } t.Fatalf("timed out waiting for: %s", what) } func count(tn *tnode) int { n, _ := tn.s.Count(context.Background()) return n } func TestGossipDeliversWithinRegion(t *testing.T) { a := startNode(t, nil, "u1x") b := startNode(t, nil, "u1x") c := startNode(t, nil, "u30") // different region connect(t, b, a) connect(t, c, a) eventually(t, "a sees b on the region topic", func() bool { return len(a.RegionPeers("u1x")) == 1 }) l := a.listing(t, "u1xjhx") if err := a.Publish(context.Background(), l); err != nil { t.Fatal(err) } eventually(t, "b receives the listing", func() bool { return count(b) == 1 }) got, err := b.s.Get(context.Background(), l.Author, l.ID) if err != nil || got.Title != "Wohnung" { t.Fatalf("b has %v, %v", got, err) } time.Sleep(500 * time.Millisecond) if count(c) != 0 { t.Fatal("node in another region received the listing") } } func TestSyncCatchesUpLateJoiner(t *testing.T) { a := startNode(t, nil, "u1x") ctx := context.Background() // Seven listings (page size is 3, so three pages), one of them deleted, // plus one in a region b does not replicate. var ls []*listing.Listing for i := 0; i < 7; i++ { l := a.listing(t, "u1xjhx") if _, err := a.s.Put(ctx, l); err != nil { t.Fatal(err) } ls = append(ls, l) } ts := &listing.Listing{ Version: listing.Version, ID: ls[0].ID, Seq: 2, CreatedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(30 * 24 * time.Hour).Unix(), Tombstone: true, Geohash: ls[0].Geohash, } if err := ts.Seal(a.dev, difficulty); err != nil { t.Fatal(err) } if _, err := a.s.Put(ctx, ts); err != nil { t.Fatal(err) } other := a.listing(t, "u30000") if _, err := a.s.Put(ctx, other); err != nil { t.Fatal(err) } b := startNode(t, nil, "u1x") // joins after everything was published connect(t, b, a) eventually(t, "b has caught up", func() bool { return count(b) == 6 }) if _, err := b.s.Get(ctx, ls[0].Author, ls[0].ID); !errors.Is(err, store.ErrNotFound) { t.Fatal("deleted listing was not deleted on the late joiner") } if _, err := b.s.Get(ctx, other.Author, other.ID); !errors.Is(err, store.ErrNotFound) { t.Fatal("b stored a listing from a region it does not replicate") } } func TestRevocationPropagatesAndBlocks(t *testing.T) { owner, _, _ := identity.NewRoot() a := startNode(t, owner, "u1x") // the owner's (soon to be compromised) node b := startNode(t, nil, "u1x") connect(t, b, a) eventually(t, "mesh formed", func() bool { return len(a.RegionPeers("u1x")) == 1 && len(b.RegionPeers("u1x")) == 1 }) ctx := context.Background() l := a.listing(t, "u1xjhx") if err := a.Publish(ctx, l); err != nil { t.Fatal(err) } eventually(t, "b has the listing", func() bool { return count(b) == 1 }) // The owner enters the recovery phrase on a new machine and revokes node a. rev, err := identity.Revoke(owner, a.dev.Cert, time.Now(), difficulty) if err != nil { t.Fatal(err) } newMachine := startNode(t, owner, "u1x") connect(t, newMachine, b) if err := newMachine.PublishRevocation(ctx, rev); err != nil { t.Fatal(err) } eventually(t, "b dropped the revoked device's listing", func() bool { return count(b) == 0 }) eventually(t, "a dropped it too", func() bool { return count(a) == 0 }) // The compromised node can no longer publish anything. if err := a.Publish(ctx, a.listing(t, "u1xjhx")); !errors.Is(err, store.ErrRevoked) { t.Fatalf("revoked node could publish: %v", err) } // A node joining later learns about the revocation through sync. late := startNode(t, nil, "u1x") connect(t, late, b) eventually(t, "late joiner learns the revocation", func() bool { ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device, a.dev.Cert.IssuedAt) return ok }) } func TestValidatorRejectsBadMessages(t *testing.T) { a := startNode(t, nil, "u1x") good := a.listing(t, "u1xjhx") goodBytes, _ := good.Bytes() validate := func(region string, data []byte) pubsub.ValidationResult { v := a.listingValidator(region) return v(context.Background(), "", &pubsub.Message{Message: &pb.Message{Data: data}}) } if r := validate("u1x", goodBytes); r != pubsub.ValidationAccept { t.Fatalf("good listing: %v", r) } if r := validate("u30", goodBytes); r != pubsub.ValidationReject { t.Fatalf("listing on the wrong region topic: %v", r) } if r := validate("u1x", []byte(`{"v":1`)); r != pubsub.ValidationReject { t.Fatalf("garbage: %v", r) } tampered := *good tampered.Title = "Betrug" tb, _ := tampered.Bytes() if r := validate("u1x", tb); r != pubsub.ValidationReject { t.Fatalf("tampered listing: %v", r) } // Valid content, but not in canonical form (extra whitespace). var m map[string]any _ = json.Unmarshal(goodBytes, &m) pretty, _ := json.MarshalIndent(m, "", " ") if r := validate("u1x", pretty); r != pubsub.ValidationReject { t.Fatalf("non-canonical encoding: %v", r) } // Expired: ignored (clock difference), not penalized. old := a.listing(t, "u1xjhx") a.clock = func() time.Time { return time.Now().Add(30 * 24 * time.Hour) } ob, _ := old.Bytes() if r := validate("u1x", ob); r != pubsub.ValidationIgnore { t.Fatalf("expired listing: %v", r) } } func TestRedialsBootstrapPeerAfterDisconnect(t *testing.T) { a := startNode(t, nil, "u1x") b := startNodeWith(t, nil, func(c *Config) { c.Bootstrap = []string{a.Addrs()[0]} }, "u1x") eventually(t, "b connected to a", func() bool { return b.PeerCount() == 1 }) if err := b.host.Network().ClosePeer(a.ID()); err != nil { t.Fatal(err) } eventually(t, "b redials its bootstrap peer", func() bool { return b.PeerCount() == 1 }) } func TestEveryNewConnectionCatchesUp(t *testing.T) { a := startNode(t, nil, "u1x") b := startNode(t, nil, "u1x") connect(t, b, a) eventually(t, "first connection settled", func() bool { return len(b.RegionPeers("u1x")) == 1 }) // The link drops, and a gains a listing that is never gossiped to b. l := a.listing(t, "u1xjhx") // sealed up front: proof-of-work is slow under -race if err := b.host.Network().ClosePeer(a.ID()); err != nil { t.Fatal(err) } eventually(t, "link is down", func() bool { return b.PeerCount() == 0 }) if _, err := a.s.Put(context.Background(), l); err != nil { t.Fatal(err) } // A reconnect, however soon after the last sync, must catch up. connect(t, b, a) eventually(t, "b catches up after reconnecting", func() bool { return count(b) == 1 }) } func TestBadBootstrapAddressRejectedUpFront(t *testing.T) { root, _, _ := identity.NewRoot() dev, _ := identity.Enroll(root, time.Now().Add(-time.Hour), 24*time.Hour) s, _ := store.Open(":memory:", store.Options{Difficulty: difficulty}) defer s.Close() _, err := New(context.Background(), Config{ Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, Bootstrap: []string{"not-an-address"}, }) if err == nil { t.Fatal("malformed bootstrap address accepted") } } func TestRegionsChangeWhileRunning(t *testing.T) { a := startNode(t, nil, "u1x") b := startNode(t, nil, "u30") connect(t, b, a) first := a.listing(t, "u1xjhx") if err := a.Publish(context.Background(), first); err != nil { t.Fatal(err) } time.Sleep(500 * time.Millisecond) if count(b) != 0 { t.Fatal("b received a listing of a region it does not follow") } // Following u1x as well: what was published before arrives by sync, what // is published from now on by gossip. if err := b.SetRegions([]string{"u30", "u1x", "u1x"}); err != nil { t.Fatal(err) } if got := b.Regions(); len(got) != 2 || got[0] != "u30" || got[1] != "u1x" { t.Fatalf("regions = %v", got) } eventually(t, "b catches up on u1x", func() bool { return count(b) == 1 }) eventually(t, "a sees b on the u1x topic", func() bool { return len(a.RegionPeers("u1x")) == 1 }) if err := a.Publish(context.Background(), a.listing(t, "u1xjhy")); err != nil { t.Fatal(err) } eventually(t, "b receives gossip of the new region", func() bool { return count(b) == 2 }) // Dropping it again: b leaves the topic, nothing more arrives, and what // was stored stays. if err := b.SetRegions([]string{"u30"}); err != nil { t.Fatal(err) } if got := b.Regions(); len(got) != 1 || got[0] != "u30" { t.Fatalf("regions = %v", got) } eventually(t, "a no longer sees b on u1x", func() bool { return len(a.RegionPeers("u1x")) == 0 }) if err := a.Publish(context.Background(), a.listing(t, "u1xjhz")); err != nil { t.Fatal(err) } time.Sleep(500 * time.Millisecond) if count(b) != 2 { t.Fatalf("b has %d listings, want the 2 it had", count(b)) } // And back: the region can be followed again. if err := b.SetRegions([]string{"u30", "u1x"}); err != nil { t.Fatal(err) } eventually(t, "b follows u1x again and catches up", func() bool { return count(b) == 3 }) // Nothing changes on a bad region. if err := b.SetRegions([]string{"u1x", "no"}); err == nil { t.Fatal("an invalid region was accepted") } if got := b.Regions(); len(got) != 2 { t.Fatalf("regions changed to %v", got) } } func TestANodeWithoutRegionsFollowsTheFirstOneWhenChosen(t *testing.T) { a := startNode(t, nil, "u1x") b := startNode(t, nil) // no region yet connect(t, b, a) if got := b.Regions(); len(got) != 0 { t.Fatalf("regions = %v", got) } l := a.listing(t, "u1xjhx") if err := a.Publish(context.Background(), l); err != nil { t.Fatal(err) } time.Sleep(300 * time.Millisecond) if count(b) != 0 { t.Fatal("a node without regions stored a listing") } if err := b.SetRegions([]string{"u1x"}); err != nil { t.Fatal(err) } eventually(t, "the first region is followed and caught up", func() bool { return count(b) == 1 }) } func TestAnnouncedAddressesReplaceTheLocalOnes(t *testing.T) { const want = "/dns4/node.example.org/tcp/4001" n := startNodeWith(t, nil, func(c *Config) { c.Announce = []string{want} }, "u1x") addrs := n.Addrs() if len(addrs) != 1 || !strings.HasPrefix(addrs[0], want+"/p2p/") { t.Fatalf("a node behind a router announces only what it was told: %v", addrs) } } func TestABadAnnounceAddressIsRefused(t *testing.T) { dev, _ := identity.Enroll(mustRoot(t), time.Now().Add(-time.Hour), 90*24*time.Hour) s, err := store.Open(":memory:", store.Options{}) if err != nil { t.Fatal(err) } defer s.Close() _, err = New(context.Background(), Config{Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, Announce: []string{"not an address"}}) if err == nil || !strings.Contains(err.Error(), "announce address") { t.Fatalf("err = %v", err) } } func mustRoot(t *testing.T) *identity.Identity { t.Helper() root, _, err := identity.NewRoot() if err != nil { t.Fatal(err) } return root }