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