Skip to content

Commit

Permalink
consensus/clique: fix race condition (#24957) (#4313)
Browse files Browse the repository at this point in the history
* consensus/clique: remove race condition

* consensus/clique: fix one more signer data race

Co-authored-by: Gary Rong <garyrong0905@gmail.com>

Co-authored-by: Harry Kalodner <harry.kalodner@gmail.com>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
  • Loading branch information
3 people committed May 31, 2022
1 parent 4b117e6 commit 5fd0da0
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions consensus/clique/clique.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ type Clique struct {

signer common.Address // Ethereum address of the signing key
signFn SignerFn // Signer function to authorize hashes with
lock sync.RWMutex // Protects the signer fields
lock sync.RWMutex // Protects the signer and proposals fields

// The fields below are for testing only
FakeDiff bool // Skip difficulty verifications
Expand Down Expand Up @@ -299,9 +299,8 @@ func (c *Clique) Prepare(chain consensus.ChainHeaderReader, header *types.Header
if err != nil {
return err
}
c.lock.RLock()
if number%c.config.Epoch != 0 {
c.lock.RLock()

// Gather all the proposals that make sense voting on
addresses := make([]common.Address, 0, len(c.proposals))
for address, authorize := range c.proposals {
Expand All @@ -318,10 +317,14 @@ func (c *Clique) Prepare(chain consensus.ChainHeaderReader, header *types.Header
copy(header.Nonce[:], nonceDropVote)
}
}
c.lock.RUnlock()
}

// Copy signer protected by mutex to avoid race condition
signer := c.signer
c.lock.RUnlock()

// Set the correct difficulty
header.Difficulty = calcDifficulty(snap, c.signer)
header.Difficulty = calcDifficulty(snap, signer)

// Ensure the extra data has all its components
if len(header.Extra) < ExtraVanity {
Expand Down Expand Up @@ -479,7 +482,10 @@ func (c *Clique) CalcDifficulty(chain consensus.ChainHeaderReader, _, _ uint64,
if err != nil {
return nil
}
return calcDifficulty(snap, c.signer)
c.lock.RLock()
signer := c.signer
c.lock.RUnlock()
return calcDifficulty(snap, signer)
}

func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
Expand Down

0 comments on commit 5fd0da0

Please sign in to comment.