Skip to content
This repository has been archived by the owner on Feb 1, 2023. It is now read-only.

Commit

Permalink
fix: fix a map access race condition in the want index
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed Jul 30, 2021
1 parent 26c6c49 commit 942b608
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions internal/decision/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,7 @@ func (e *Engine) ReceiveFrom(from peer.ID, blks []blocks.Block) {

// Check each peer to see if it wants one of the blocks we received
var work bool
missingWants := make(map[peer.ID][]cid.Cid)
e.lock.RLock()
for _, b := range blks {
k := b.Cid()
Expand All @@ -613,15 +614,15 @@ func (e *Engine) ReceiveFrom(from peer.ID, blks []blocks.Block) {
ledger, ok := e.ledgerMap[p]
if !ok {
log.Errorw("failed to find peer in ledger", "peer", p)
e.peerLedger.CancelWant(p, k)
missingWants[p] = append(missingWants[p], k)
continue
}
ledger.lk.RLock()
entry, ok := ledger.WantListContains(k)
ledger.lk.RUnlock()
if !ok { // should never happen
log.Errorw("wantlist index doesn't match peer's wantlist", "peer", p)
e.peerLedger.CancelWant(p, k)
missingWants[p] = append(missingWants[p], k)
continue
}
work = true
Expand Down Expand Up @@ -649,6 +650,30 @@ func (e *Engine) ReceiveFrom(from peer.ID, blks []blocks.Block) {
}
e.lock.RUnlock()

// If we found missing wants (e.g., because the peer disconnected, we have some races here)
// remove them from the list. Unfortunately, we still have to re-check because the user
// could have re-connected in the meantime.
if len(missingWants) > 0 {
e.lock.Lock()
for p, wl := range missingWants {
if ledger, ok := e.ledgerMap[p]; ok {
ledger.lk.RLock()
for _, k := range wl {
if _, has := ledger.WantListContains(k); has {
continue
}
e.peerLedger.CancelWant(p, k)
}
ledger.lk.RUnlock()
} else {
for _, k := range wl {
e.peerLedger.CancelWant(p, k)
}
}
}
e.lock.Unlock()
}

if work {
e.signalNewWork()
}
Expand Down

0 comments on commit 942b608

Please sign in to comment.