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