github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/consensus/clique/snapshot.go (about)

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