package p2p import ( "context" "encoding/json" "errors" "io" "log/slog" "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 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() 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}) if err != nil { t.Fatal(err) } n, err := New(context.Background(), Config{ Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, Regions: regions, Difficulty: difficulty, SyncPageSize: 3, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), }) 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) 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) } }