package main // The harder scenarios of the simulator: conditions on the network, attackers, // the seeds going away, and repair of what gossip never delivered. import ( "context" "fmt" "math/rand/v2" "net" "sync/atomic" "time" "github.com/libp2p/go-libp2p" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/p2p/transport/tcp" ma "github.com/multiformats/go-multiaddr" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/message" ) // --- latency and connection loss ------------------------------------------------------ // netConditions puts a delay on every write of the connections a node dials, // and cuts those connections after a random time. TCP itself never loses // bytes, so this is what packet loss looks like to the layers above: slow // writes, and connections that die and have to be redialed and resynced. // Only dialed connections are touched, so a delay applies in one direction. type netConditions struct { latency, lifetime time.Duration cuts atomic.Int64 } func (c *netConditions) options() []libp2p.Option { return []libp2p.Option{libp2p.Transport(tcp.NewTCPTransport, tcp.WithDialerForAddr(func(ma.Multiaddr) (tcp.ContextDialer, error) { return &lossyDialer{c: c}, nil }))} } type lossyDialer struct{ c *netConditions } func (d *lossyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { conn, err := (&net.Dialer{}).DialContext(ctx, network, address) if err != nil { return nil, err } if d.c.lifetime > 0 { time.AfterFunc(time.Duration(rand.ExpFloat64()*float64(d.c.lifetime)), func() { d.c.cuts.Add(1) _ = conn.Close() }) } return &lossyConn{Conn: conn, c: d.c}, nil } type lossyConn struct { net.Conn c *netConditions } // The transport sets TCP keepalives on the connection it is given. func (l *lossyConn) SetKeepAlive(on bool) error { return l.Conn.(*net.TCPConn).SetKeepAlive(on) } func (l *lossyConn) SetKeepAlivePeriod(d time.Duration) error { return l.Conn.(*net.TCPConn).SetKeepAlivePeriod(d) } func (l *lossyConn) Write(p []byte) (int, error) { if d := l.c.latency; d > 0 { time.Sleep(d/2 + time.Duration(rand.Int64N(int64(d)))) // 50% to 150% } return l.Conn.Write(p) } // --- attackers ---------------------------------------------------------------------------- // attacker is a bare libp2p and gossipsub peer without any of the node's // validators, so it can put whatever it likes on a topic. type attacker struct { h host.Host topics map[string]*pubsub.Topic cancel context.CancelFunc } func (s *sim) newAttacker(targets []*simNode, topics ...string) *attacker { ctx, cancel := context.WithCancel(s.ctx) h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) s.must(err) ps, err := pubsub.NewGossipSub(ctx, h, pubsub.WithMaxMessageSize(1<<20), pubsub.WithFloodPublish(true)) s.must(err) a := &attacker{h: h, topics: map[string]*pubsub.Topic{}, cancel: cancel} for _, name := range topics { t, err := ps.Join(name) s.must(err) sub, err := t.Subscribe() s.must(err) go func() { for { if _, err := sub.Next(ctx); err != nil { return } } }() a.topics[name] = t } for _, n := range targets { ai, err := peer.AddrInfoFromString(n.node.Addrs()[0]) s.must(err) s.must(h.Connect(ctx, *ai)) } time.Sleep(2 * time.Second) // let the topic subscriptions reach the targets return a } func (a *attacker) publish(ctx context.Context, topic string, data []byte) { _ = a.topics[topic].Publish(ctx, data) // a refusal is the attacker's loss, not the test's } func (a *attacker) close() { a.cancel() _ = a.h.Close() } // totalListings counts the listings the running nodes hold. func (s *sim) totalListings() int { total := 0 for _, n := range s.nodes { if n.node == nil { continue } c, err := n.st.Count(s.ctx) s.must(err) total += c } return total } // hostile attacks one region: junk and forged listings, then a flood of valid // messages at one listing. It checks that nothing invalid is stored anywhere, // that honest traffic still gets through, and what the flood costs a sender. func (s *sim) hostile(regions []string, rep *reportTable) { region := regions[0] rep.phase("attack") fmt.Printf("attacking region %s: forged listings and a message flood ...\n", region) pool := s.followers(region) targets := pool[:min(10, len(pool))] lt := "/allmende/1/listings/" + region mt := "/allmende/1/messages/" + region atk := s.newAttacker(targets, lt, mt) defer atk.close() // 1. listings that must never be stored ident := &simNode{} s.must(s.makeIdentity(ident)) defer ident.st.Close() before := s.totalListings() sent := map[string]int{} send := func(kind string, data []byte) { atk.publish(s.ctx, lt, data) sent[kind]++ } for i := 0; i < 150; i++ { junk := make([]byte, 100+s.rng.IntN(400)) for j := range junk { junk[j] = byte(s.rng.IntN(256)) } send("garbage", junk) l := s.newListing(ident, region) // valid, then changed after signing l.Title = "Geaendert nach der Signatur" b, _ := l.Bytes() send("forged signature", b) weak := s.newListing(ident, region) // signed, with too little proof-of-work for tries := 0; tries < 50; tries++ { id, _ := listing.NewID() weak.ID = id s.must(weak.Seal(ident.dev, 1)) if weak.Check(time.Now(), s.difficulty) != nil { break } } if weak.Check(time.Now(), s.difficulty) != nil { b, _ = weak.Bytes() send("too little work", b) } } other := regions[len(regions)-1] for i := 0; i < 50 && other != region; i++ { l := s.newListing(ident, other) // valid, on the wrong region's topic b, _ := l.Bytes() send("wrong region", b) } time.Sleep(3 * time.Second) grew := s.totalListings() - before total := 0 for _, c := range sent { total += c } rep.row("attack 1", fmt.Sprintf("%d bad listings sent (%v): the nodes stored %d of them", total, sent, grew)) // honest listings must still arrive while the attacker is connected var pairs []*pair for i := 0; i < 10; i++ { owner := s.randomFollower(region) l := s.newListing(owner, region) must(owner.node.Publish(s.ctx, l)) s.made = append(s.made, l) at := time.Now() for _, f := range s.followers(region) { if f != owner { pairs = append(pairs, &pair{start: at, check: s.hasListing(f, l)}) } } poll(pairs, 100*time.Millisecond) } rep.latency("attack 1b", "honest listings published while the attacker is connected", await(pairs, s.timeout)) rep.row("attack 1c", fmt.Sprintf("the attacker is still connected to %d of %d nodes it dialed (there is no peer scoring: nobody cuts it off)", len(atk.h.Network().Peers()), len(targets))) // 2. a message flood at one listing, with real (cheap) proof-of-work var target *listing.Listing for _, l := range s.made { if listing.Region(l.Geohash) == region && s.byAuthor(l.Author) != nil && s.byAuthor(l.Author).node != nil { target = l break } } if target == nil { rep.row("attack 2", "no live listing in the region to flood") return } owner := s.byAuthor(target.Author) ref := message.Ref{Author: target.Author, ID: target.ID} queue := func(n *simNode) int { envs, err := n.st.OwnerMessages(s.ctx, target.Author) s.must(err) c := 0 for _, e := range envs { if e.Listing == ref { c++ } } return c } const flood = 400 for i := 0; i < flood; i++ { tk, err := message.NewThreadKey() s.must(err) env, err := message.SealToOwner(target, tk, &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "Kaufen Sie jetzt"}, time.Now(), s.msgDiff) s.must(err) b, _ := env.Bytes() atk.publish(s.ctx, mt, b) } time.Sleep(4 * time.Second) lo, hi := 1<<30, 0 for _, f := range s.followers(region) { q := queue(f) lo, hi = min(lo, q), max(hi, q) } ownerPrice, err := owner.st.RequiredWork(s.ctx, ref) s.must(err) rep.row("attack 2", fmt.Sprintf("%d valid envelopes at the base price (%d bits) flooded at one listing: queue at its owner %d (limit 200), across the region's nodes %d to %d; the price there is now %d bits", flood, s.msgDiff, queue(owner), lo, hi, ownerPrice)) // a real buyer asks the node it uses (not the owner) for the price and pays it via := s.randomFollower(region) for via == owner { via = s.randomFollower(region) } viaPrice, err := via.st.RequiredWork(s.ctx, ref) s.must(err) buy := func(bits int) (time.Duration, bool) { tk, err := message.NewThreadKey() s.must(err) env, err := message.SealToOwner(target, tk, &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "Ist die Wohnung noch frei?"}, time.Now(), bits) s.must(err) if err := via.node.PublishMessage(s.ctx, region, env); err != nil { return 0, false } p := &pair{start: time.Now(), check: s.ownerHas(owner, env)} await([]*pair{p}, 10*time.Second) return p.took, p.done } if took, ok := buy(viaPrice); ok { rep.row("attack 2b", fmt.Sprintf("a buyer paying its gateway's price (%d bits; the owner's is %d) reached the owner in %s", viaPrice, ownerPrice, round(took))) } else if took, ok := buy(max(viaPrice, ownerPrice)); ok { rep.row("attack 2b", fmt.Sprintf("a buyer paying its gateway's price (%d bits) did NOT reach the owner (whose price is %d); paying the owner's price did, in %s", viaPrice, ownerPrice, round(took))) } else { rep.row("attack 2b", fmt.Sprintf("a buyer did NOT reach the owner at the gateway's price (%d) nor the owner's (%d)", viaPrice, ownerPrice)) } } // --- anti-entropy ---------------------------------------------------------------------------- // repair puts listings into one node's store and tells nobody. Only // anti-entropy (or a new connection's sync) can carry them to the region. func (s *sim) repair(rep *reportTable) { rep.phase("repair") fmt.Println("anti-entropy: listings only one node has ...") var pairs []*pair for i := 0; i < 5; i++ { owner := s.randomFollower("") l := s.newListing(owner, owner.regions[0]) _, err := owner.st.Put(s.ctx, l) s.must(err) s.made = append(s.made, l) at := time.Now() for _, f := range s.followers(listing.Region(l.Geohash)) { if f != owner { pairs = append(pairs, &pair{start: at, check: s.hasListing(f, l)}) } } } rep.latency("repair", fmt.Sprintf("listings no one gossiped, spread by anti-entropy every %s (and by new connections)", s.antiEnt), await(pairs, s.timeout)) } // --- the seeds go away ----------------------------------------------------------------------- func (s *sim) killSeeds(regions []string, rep *reportTable) { rep.phase("seeds down") fmt.Println("shutting down the seeds ...") for _, n := range s.nodes { if n.seed && n.node != nil { _ = n.node.Close() n.node = nil } } time.Sleep(2 * time.Second) // the network goes on without them var pairs []*pair for i := 0; i < 15; i++ { owner := s.randomFollower("") l := s.newListing(owner, owner.regions[0]) must(owner.node.Publish(s.ctx, l)) s.made = append(s.made, l) at := time.Now() for _, f := range s.followers(listing.Region(l.Geohash)) { if f != owner { pairs = append(pairs, &pair{start: at, check: s.hasListing(f, l)}) } } poll(pairs, 100*time.Millisecond) } rep.latency("no seeds", "listings published after every seed is gone", await(pairs, s.timeout)) // A node that was here before remembers some peers (peers.json). Those are // mostly of its own regions; the unlucky case is that they are not. cachedIn := func(want func(*simNode) bool) []string { var addrs []string for _, n := range s.nodes { if !n.seed && n.node != nil && want(n) && len(addrs) < 2 { addrs = append(addrs, n.node.Addrs()[0]) } } return addrs } newcomers := func(row, what string, n int, pick func(region string) []string) []*simNode { var fresh []*simNode for i := 0; i < n; i++ { region := regions[i%len(regions)] fresh = append(fresh, s.spawn([]string{region}, pick(region))) } start := time.Now() var pairs []*pair for _, f := range fresh { for _, l := range s.made { if f.follows(listing.Region(l.Geohash)) { pairs = append(pairs, &pair{start: start, check: s.hasListing(f, l)}) } } } rep.latency(row, what, await(pairs, s.timeout)) return fresh } newcomers("newcomers", "10 new nodes that remember two live peers of their own region get every listing of it", 10, func(region string) []string { return cachedIn(func(n *simNode) bool { return n.follows(region) }) }) newcomers("newcomers 2", "6 new nodes whose two remembered peers are all in another region", 6, func(region string) []string { return cachedIn(func(n *simNode) bool { return !n.follows(region) }) }) // a newcomer that only knows the seeds var lost []*simNode for i := 0; i < 5; i++ { lost = append(lost, s.spawn([]string{regions[i%len(regions)]}, s.seedAddrs)) } time.Sleep(min(s.timeout, 15*time.Second)) joined := 0 for _, n := range lost { if n.node.PeerCount() > 0 { joined++ } _ = n.node.Close() // left out of the final comparison: they never joined n.node = nil } rep.row("lost", fmt.Sprintf("5 new nodes that only know the dead seeds: %d found a peer after 15 s", joined)) } // spawn starts one more node on a fresh identity. func (s *sim) spawn(regions, bootstrap []string) *simNode { n := &simNode{idx: len(s.nodes), regions: regions, bootstrap: bootstrap} s.must(s.makeIdentity(n)) s.mu.Lock() s.nodes = append(s.nodes, n) s.mu.Unlock() s.must(s.start(n)) return n }