Skip to content

Commit db6e695

Browse files
committed
consensus/clique: choose valid votes
1 parent 6171d01 commit db6e695

File tree

2 files changed

+23
-11
lines changed

2 files changed

+23
-11
lines changed

consensus/clique/clique.go

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -504,14 +504,23 @@ func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) erro
504504
header.Nonce = types.BlockNonce{}
505505

506506
number := header.Number.Uint64()
507+
// Assemble the voting snapshot
508+
snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
509+
if err != nil {
510+
return err
511+
}
507512
if number%c.config.Epoch != 0 {
513+
// Get valid votes
508514
c.lock.RLock()
509-
if len(c.proposals) > 0 {
510-
addresses := make([]common.Address, 0, len(c.proposals))
511-
for address := range c.proposals {
515+
var addresses []common.Address
516+
for address, authorize := range c.proposals {
517+
if snap.validVote(address, authorize) {
512518
addresses = append(addresses, address)
513519
}
514-
header.Coinbase = addresses[rand.Intn(len(addresses))]
520+
}
521+
if len(addresses) > 0 {
522+
index := rand.Intn(len(addresses))
523+
header.Coinbase = addresses[index]
515524
if c.proposals[header.Coinbase] {
516525
copy(header.Nonce[:], nonceAuthVote)
517526
} else {
@@ -520,11 +529,8 @@ func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) erro
520529
}
521530
c.lock.RUnlock()
522531
}
523-
// Assemble the voting snapshot and set the correct difficulty
524-
snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
525-
if err != nil {
526-
return err
527-
}
532+
533+
// Set the correct difficulty
528534
header.Difficulty = diffNoTurn
529535
if snap.inturn(header.Number.Uint64(), c.signer) {
530536
header.Difficulty = diffInTurn

consensus/clique/snapshot.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,11 +126,17 @@ func (s *Snapshot) copy() *Snapshot {
126126
return cpy
127127
}
128128

129+
// validVote returns whether it makes sense to cast the specified vote in the
130+
// given snapshot context (e.g. don't try to add an already authorized signer).
131+
func (s *Snapshot) validVote(address common.Address, authorize bool) bool {
132+
_, signer := s.Signers[address]
133+
return (signer && !authorize) || (!signer && authorize)
134+
}
135+
129136
// cast adds a new vote into the tally.
130137
func (s *Snapshot) cast(address common.Address, authorize bool) bool {
131138
// Ensure the vote is meaningful
132-
_, signer := s.Signers[address]
133-
if (signer && authorize) || (!signer && !authorize) {
139+
if !s.validVote(address, authorize) {
134140
return false
135141
}
136142
// Cast the vote into an existing or new tally

0 commit comments

Comments
 (0)