github.com/Ankr-network/go-ethereum@v1.9.7/consensus/clique/snapshot.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package clique
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"sort"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/ethdb"
    28  	"github.com/ethereum/go-ethereum/log"
    29  	"github.com/ethereum/go-ethereum/params"
    30  	lru "github.com/hashicorp/golang-lru"
    31  )
    32  
    33  // Vote represents a single vote that an authorized signer made to modify the
    34  // list of authorizations.
    35  type Vote struct {
    36  	Signer    common.Address `json:"signer"`    // Authorized signer that cast this vote
    37  	Block     uint64         `json:"block"`     // Block number the vote was cast in (expire old votes)
    38  	Address   common.Address `json:"address"`   // Account being voted on to change its authorization
    39  	Authorize bool           `json:"authorize"` // Whether to authorize or deauthorize the voted account
    40  }
    41  
    42  // Tally is a simple vote tally to keep the current score of votes. Votes that
    43  // go against the proposal aren't counted since it's equivalent to not voting.
    44  type Tally struct {
    45  	Authorize bool `json:"authorize"` // Whether the vote is about authorizing or kicking someone
    46  	Votes     int  `json:"votes"`     // Number of votes until now wanting to pass the proposal
    47  }
    48  
    49  // Snapshot is the state of the authorization voting at a given point in time.
    50  type Snapshot struct {
    51  	config   *params.CliqueConfig // Consensus engine parameters to fine tune behavior
    52  	sigcache *lru.ARCCache        // Cache of recent block signatures to speed up ecrecover
    53  
    54  	Number  uint64                      `json:"number"`  // Block number where the snapshot was created
    55  	Hash    common.Hash                 `json:"hash"`    // Block hash where the snapshot was created
    56  	Signers map[common.Address]struct{} `json:"signers"` // Set of authorized signers at this moment
    57  	Recents map[uint64]common.Address   `json:"recents"` // Set of recent signers for spam protections
    58  	Votes   []*Vote                     `json:"votes"`   // List of votes cast in chronological order
    59  	Tally   map[common.Address]Tally    `json:"tally"`   // Current vote tally to avoid recalculating
    60  }
    61  
    62  // signersAscending implements the sort interface to allow sorting a list of addresses
    63  type signersAscending []common.Address
    64  
    65  func (s signersAscending) Len() int           { return len(s) }
    66  func (s signersAscending) Less(i, j int) bool { return bytes.Compare(s[i][:], s[j][:]) < 0 }
    67  func (s signersAscending) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    68  
    69  // newSnapshot creates a new snapshot with the specified startup parameters. This
    70  // method does not initialize the set of recent signers, so only ever use if for
    71  // the genesis block.
    72  func newSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, number uint64, hash common.Hash, signers []common.Address) *Snapshot {
    73  	snap := &Snapshot{
    74  		config:   config,
    75  		sigcache: sigcache,
    76  		Number:   number,
    77  		Hash:     hash,
    78  		Signers:  make(map[common.Address]struct{}),
    79  		Recents:  make(map[uint64]common.Address),
    80  		Tally:    make(map[common.Address]Tally),
    81  	}
    82  	for _, signer := range signers {
    83  		snap.Signers[signer] = struct{}{}
    84  	}
    85  	return snap
    86  }
    87  
    88  // loadSnapshot loads an existing snapshot from the database.
    89  func loadSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, db ethdb.Database, hash common.Hash) (*Snapshot, error) {
    90  	blob, err := db.Get(append([]byte("clique-"), hash[:]...))
    91  	if err != nil {
    92  		return nil, err
    93  	}
    94  	snap := new(Snapshot)
    95  	if err := json.Unmarshal(blob, snap); err != nil {
    96  		return nil, err
    97  	}
    98  	snap.config = config
    99  	snap.sigcache = sigcache
   100  
   101  	return snap, nil
   102  }
   103  
   104  // store inserts the snapshot into the database.
   105  func (s *Snapshot) store(db ethdb.Database) error {
   106  	blob, err := json.Marshal(s)
   107  	if err != nil {
   108  		return err
   109  	}
   110  	return db.Put(append([]byte("clique-"), s.Hash[:]...), blob)
   111  }
   112  
   113  // copy creates a deep copy of the snapshot, though not the individual votes.
   114  func (s *Snapshot) copy() *Snapshot {
   115  	cpy := &Snapshot{
   116  		config:   s.config,
   117  		sigcache: s.sigcache,
   118  		Number:   s.Number,
   119  		Hash:     s.Hash,
   120  		Signers:  make(map[common.Address]struct{}),
   121  		Recents:  make(map[uint64]common.Address),
   122  		Votes:    make([]*Vote, len(s.Votes)),
   123  		Tally:    make(map[common.Address]Tally),
   124  	}
   125  	for signer := range s.Signers {
   126  		cpy.Signers[signer] = struct{}{}
   127  	}
   128  	for block, signer := range s.Recents {
   129  		cpy.Recents[block] = signer
   130  	}
   131  	for address, tally := range s.Tally {
   132  		cpy.Tally[address] = tally
   133  	}
   134  	copy(cpy.Votes, s.Votes)
   135  
   136  	return cpy
   137  }
   138  
   139  // validVote returns whether it makes sense to cast the specified vote in the
   140  // given snapshot context (e.g. don't try to add an already authorized signer).
   141  func (s *Snapshot) validVote(address common.Address, authorize bool) bool {
   142  	_, signer := s.Signers[address]
   143  	return (signer && !authorize) || (!signer && authorize)
   144  }
   145  
   146  // cast adds a new vote into the tally.
   147  func (s *Snapshot) cast(address common.Address, authorize bool) bool {
   148  	// Ensure the vote is meaningful
   149  	if !s.validVote(address, authorize) {
   150  		return false
   151  	}
   152  	// Cast the vote into an existing or new tally
   153  	if old, ok := s.Tally[address]; ok {
   154  		old.Votes++
   155  		s.Tally[address] = old
   156  	} else {
   157  		s.Tally[address] = Tally{Authorize: authorize, Votes: 1}
   158  	}
   159  	return true
   160  }
   161  
   162  // uncast removes a previously cast vote from the tally.
   163  func (s *Snapshot) uncast(address common.Address, authorize bool) bool {
   164  	// If there's no tally, it's a dangling vote, just drop
   165  	tally, ok := s.Tally[address]
   166  	if !ok {
   167  		return false
   168  	}
   169  	// Ensure we only revert counted votes
   170  	if tally.Authorize != authorize {
   171  		return false
   172  	}
   173  	// Otherwise revert the vote
   174  	if tally.Votes > 1 {
   175  		tally.Votes--
   176  		s.Tally[address] = tally
   177  	} else {
   178  		delete(s.Tally, address)
   179  	}
   180  	return true
   181  }
   182  
   183  // apply creates a new authorization snapshot by applying the given headers to
   184  // the original one.
   185  func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
   186  	// Allow passing in no headers for cleaner code
   187  	if len(headers) == 0 {
   188  		return s, nil
   189  	}
   190  	// Sanity check that the headers can be applied
   191  	for i := 0; i < len(headers)-1; i++ {
   192  		if headers[i+1].Number.Uint64() != headers[i].Number.Uint64()+1 {
   193  			return nil, errInvalidVotingChain
   194  		}
   195  	}
   196  	if headers[0].Number.Uint64() != s.Number+1 {
   197  		return nil, errInvalidVotingChain
   198  	}
   199  	// Iterate through the headers and create a new snapshot
   200  	snap := s.copy()
   201  
   202  	var (
   203  		start  = time.Now()
   204  		logged = time.Now()
   205  	)
   206  	for i, header := range headers {
   207  		// Remove any votes on checkpoint blocks
   208  		number := header.Number.Uint64()
   209  		if number%s.config.Epoch == 0 {
   210  			snap.Votes = nil
   211  			snap.Tally = make(map[common.Address]Tally)
   212  		}
   213  		// Delete the oldest signer from the recent list to allow it signing again
   214  		if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
   215  			delete(snap.Recents, number-limit)
   216  		}
   217  		// Resolve the authorization key and check against signers
   218  		signer, err := ecrecover(header, s.sigcache)
   219  		if err != nil {
   220  			return nil, err
   221  		}
   222  		if _, ok := snap.Signers[signer]; !ok {
   223  			return nil, errUnauthorizedSigner
   224  		}
   225  		for _, recent := range snap.Recents {
   226  			if recent == signer {
   227  				return nil, errRecentlySigned
   228  			}
   229  		}
   230  		snap.Recents[number] = signer
   231  
   232  		// Header authorized, discard any previous votes from the signer
   233  		for i, vote := range snap.Votes {
   234  			if vote.Signer == signer && vote.Address == header.Coinbase {
   235  				// Uncast the vote from the cached tally
   236  				snap.uncast(vote.Address, vote.Authorize)
   237  
   238  				// Uncast the vote from the chronological list
   239  				snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
   240  				break // only one vote allowed
   241  			}
   242  		}
   243  		// Tally up the new vote from the signer
   244  		var authorize bool
   245  		switch {
   246  		case bytes.Equal(header.Nonce[:], nonceAuthVote):
   247  			authorize = true
   248  		case bytes.Equal(header.Nonce[:], nonceDropVote):
   249  			authorize = false
   250  		default:
   251  			return nil, errInvalidVote
   252  		}
   253  		if snap.cast(header.Coinbase, authorize) {
   254  			snap.Votes = append(snap.Votes, &Vote{
   255  				Signer:    signer,
   256  				Block:     number,
   257  				Address:   header.Coinbase,
   258  				Authorize: authorize,
   259  			})
   260  		}
   261  		// If the vote passed, update the list of signers
   262  		if tally := snap.Tally[header.Coinbase]; tally.Votes > len(snap.Signers)/2 {
   263  			if tally.Authorize {
   264  				snap.Signers[header.Coinbase] = struct{}{}
   265  			} else {
   266  				delete(snap.Signers, header.Coinbase)
   267  
   268  				// Signer list shrunk, delete any leftover recent caches
   269  				if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
   270  					delete(snap.Recents, number-limit)
   271  				}
   272  				// Discard any previous votes the deauthorized signer cast
   273  				for i := 0; i < len(snap.Votes); i++ {
   274  					if snap.Votes[i].Signer == header.Coinbase {
   275  						// Uncast the vote from the cached tally
   276  						snap.uncast(snap.Votes[i].Address, snap.Votes[i].Authorize)
   277  
   278  						// Uncast the vote from the chronological list
   279  						snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
   280  
   281  						i--
   282  					}
   283  				}
   284  			}
   285  			// Discard any previous votes around the just changed account
   286  			for i := 0; i < len(snap.Votes); i++ {
   287  				if snap.Votes[i].Address == header.Coinbase {
   288  					snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
   289  					i--
   290  				}
   291  			}
   292  			delete(snap.Tally, header.Coinbase)
   293  		}
   294  		// If we're taking too much time (ecrecover), notify the user once a while
   295  		if time.Since(logged) > 8*time.Second {
   296  			log.Info("Reconstructing voting history", "processed", i, "total", len(headers), "elapsed", common.PrettyDuration(time.Since(start)))
   297  			logged = time.Now()
   298  		}
   299  	}
   300  	if time.Since(start) > 8*time.Second {
   301  		log.Info("Reconstructed voting history", "processed", len(headers), "elapsed", common.PrettyDuration(time.Since(start)))
   302  	}
   303  	snap.Number += uint64(len(headers))
   304  	snap.Hash = headers[len(headers)-1].Hash()
   305  
   306  	return snap, nil
   307  }
   308  
   309  // signers retrieves the list of authorized signers in ascending order.
   310  func (s *Snapshot) signers() []common.Address {
   311  	sigs := make([]common.Address, 0, len(s.Signers))
   312  	for sig := range s.Signers {
   313  		sigs = append(sigs, sig)
   314  	}
   315  	sort.Sort(signersAscending(sigs))
   316  	return sigs
   317  }
   318  
   319  // inturn returns if a signer at a given block height is in-turn or not.
   320  func (s *Snapshot) inturn(number uint64, signer common.Address) bool {
   321  	signers, offset := s.signers(), 0
   322  	for offset < len(signers) && signers[offset] != signer {
   323  		offset++
   324  	}
   325  	return (number % uint64(len(signers))) == uint64(offset)
   326  }