Skip to content

p2p: Switch.OnStop uses stale and already mutated PeerSet.List() which could have data race consequences due to a leaky abstraction of using .List() #2158

Closed

Description

@odeke-em

Bug Report

The code in p2p/Switch.OnStop invokes sw.peers.List() per

for _, p := range sw.peers.List() {

and if we look at the code for .List()

cometbft/p2p/peer_set.go

Lines 153 to 156 in f4d73cd

func (ps *PeerSet) List() []Peer {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return ps.list
which returns a copy of the slice while under a lock but after handing it over, it is no longer under a lock and is modified by .Remove() which causes .OnStop() to read stale data.

I found this problem while working on the correct fix for #2157 in which the correct way to shorten a slice is to ensure you insert a nil at the last element before reslicing to ensure that there are no references to it and that the backing array can be garbage collected i.e.

endItem := slice[len(slice)-1]
slice[len(slice)-1] = nil // nil it so that it'll be garbage collected

I can reliably reproduce this issue when I apply the fix for the referenced issue

Remedy

Check and ensure that the peer is non-nil.

Activity

  1. added
    bug
    needs-triage
    on Jan 28, 2024
  2. odeke-em commented on Jan 29, 2024

    @odeke-em
    ContributorAuthor

    And indeed, the data race is exposed in https://github.com/cometbft/cometbft/actions/runs/7692838534/job/20960454814?pr=2159 in which this code uses a stale version of the peerSet's list in

    cometbft/p2p/switch.go

    Lines 276 to 281 in 940378c

    peers := sw.peers.List()
    var wg sync.WaitGroup
    wg.Add(len(peers))
    successChan := make(chan bool, len(peers))
    for _, peer := range peers {

  3. removed
    needs-triage
    on Jan 29, 2024
  4. cason commented on Jan 29, 2024

    @cason

    Indeed, we need to return a copy of the list of peers here.

    This method is actually called in several parts of the p2p package and needs to be reconsidered.

  5. added this to the 2024-Q1 milestone on Jan 30, 2024
  6. moved this from Todo to Ready for Review in CometBFTon Jan 31, 2024
  7. added a commit that references this issue on Feb 12, 2024
    e1ee71c
  8. moved this from Ready for Review to Done in CometBFTon Feb 12, 2024
  9. added 2 commits that reference this issue on Feb 12, 2024
    3fafa5e
    acebbc4
  10. added a commit that references this issue on Sep 5, 2025
    48674c7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugp2p

    Type

    No type

    Projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions