github.com/core-coin/go-core/v2@v2.1.9/consensus/clique/snapshot.go (about)

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