github.com/alanchchen/go-ethereum@v1.6.6-0.20170601190819-6171d01b1195/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  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/core/types"
    25  	"github.com/ethereum/go-ethereum/ethdb"
    26  	"github.com/ethereum/go-ethereum/params"
    27  	lru "github.com/hashicorp/golang-lru"
    28  )
    29  
    30  // Vote represents a single vote that an authorized signer made to modify the
    31  // list of authorizations.
    32  type Vote struct {
    33  	Signer    common.Address `json:"signer"`    // Authorized signer that cast this vote
    34  	Block     uint64         `json:"block"`     // Block number the vote was cast in (expire old votes)
    35  	Address   common.Address `json:"address"`   // Account being voted on to change its authorization
    36  	Authorize bool           `json:"authorize"` // Whether to authorize or deauthorize the voted account
    37  }
    38  
    39  // Tally is a simple vote tally to keep the current score of votes. Votes that
    40  // go against the proposal aren't counted since it's equivalent to not voting.
    41  type Tally struct {
    42  	Authorize bool `json:"authorize"` // Whether the vote it about authorizing or kicking someone
    43  	Votes     int  `json:"votes"`     // Number of votes until now wanting to pass the proposal
    44  }
    45  
    46  // Snapshot is the state of the authorization voting at a given point in time.
    47  type Snapshot struct {
    48  	config   *params.CliqueConfig // Consensus engine parameters to fine tune behavior
    49  	sigcache *lru.ARCCache        // Cache of recent block signatures to speed up ecrecover
    50  
    51  	Number  uint64                      `json:"number"`  // Block number where the snapshot was created
    52  	Hash    common.Hash                 `json:"hash"`    // Block hash where the snapshot was created
    53  	Signers map[common.Address]struct{} `json:"signers"` // Set of authorized signers at this moment
    54  	Recents map[uint64]common.Address   `json:"recents"` // Set of recent signers for spam protections
    55  	Votes   []*Vote                     `json:"votes"`   // List of votes cast in chronological order
    56  	Tally   map[common.Address]Tally    `json:"tally"`   // Current vote tally to avoid recalculating
    57  }
    58  
    59  // newSnapshot create 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, sigcache *lru.ARCCache, number uint64, hash common.Hash, signers []common.Address) *Snapshot {
    63  	snap := &Snapshot{
    64  		config:   config,
    65  		sigcache: sigcache,
    66  		Number:   number,
    67  		Hash:     hash,
    68  		Signers:  make(map[common.Address]struct{}),
    69  		Recents:  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, sigcache *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.sigcache = sigcache
    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  		sigcache: s.sigcache,
   108  		Number:   s.Number,
   109  		Hash:     s.Hash,
   110  		Signers:  make(map[common.Address]struct{}),
   111  		Recents:  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.Recents {
   119  		cpy.Recents[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  // cast adds a new vote into the tally.
   130  func (s *Snapshot) cast(address common.Address, authorize bool) bool {
   131  	// Ensure the vote is meaningful
   132  	_, signer := s.Signers[address]
   133  	if (signer && authorize) || (!signer && !authorize) {
   134  		return false
   135  	}
   136  	// Cast the vote into an existing or new tally
   137  	if old, ok := s.Tally[address]; ok {
   138  		old.Votes++
   139  		s.Tally[address] = old
   140  	} else {
   141  		s.Tally[address] = Tally{Authorize: authorize, Votes: 1}
   142  	}
   143  	return true
   144  }
   145  
   146  // uncast removes a previously cast vote from the tally.
   147  func (s *Snapshot) uncast(address common.Address, authorize bool) bool {
   148  	// If there's no tally, it's a dangling vote, just drop
   149  	tally, ok := s.Tally[address]
   150  	if !ok {
   151  		return false
   152  	}
   153  	// Ensure we only revert counted votes
   154  	if tally.Authorize != authorize {
   155  		return false
   156  	}
   157  	// Otherwise revert the vote
   158  	if tally.Votes > 1 {
   159  		tally.Votes--
   160  		s.Tally[address] = tally
   161  	} else {
   162  		delete(s.Tally, address)
   163  	}
   164  	return true
   165  }
   166  
   167  // apply creates a new authorization snapshot by applying the given headers to
   168  // the original one.
   169  func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
   170  	// Allow passing in no headers for cleaner code
   171  	if len(headers) == 0 {
   172  		return s, nil
   173  	}
   174  	// Sanity check that the headers can be applied
   175  	for i := 0; i < len(headers)-1; i++ {
   176  		if headers[i+1].Number.Uint64() != headers[i].Number.Uint64()+1 {
   177  			return nil, errInvalidVotingChain
   178  		}
   179  	}
   180  	if headers[0].Number.Uint64() != s.Number+1 {
   181  		return nil, errInvalidVotingChain
   182  	}
   183  	// Iterate through the headers and create a new snapshot
   184  	snap := s.copy()
   185  
   186  	for _, header := range headers {
   187  		// Remove any votes on checkpoint blocks
   188  		number := header.Number.Uint64()
   189  		if number%s.config.Epoch == 0 {
   190  			snap.Votes = nil
   191  			snap.Tally = make(map[common.Address]Tally)
   192  		}
   193  		// Delete the oldest signer from the recent list to allow it signing again
   194  		if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
   195  			delete(snap.Recents, number-limit)
   196  		}
   197  		// Resolve the authorization key and check against signers
   198  		signer, err := ecrecover(header, s.sigcache)
   199  		if err != nil {
   200  			return nil, err
   201  		}
   202  		if _, ok := snap.Signers[signer]; !ok {
   203  			return nil, errUnauthorized
   204  		}
   205  		for _, recent := range snap.Recents {
   206  			if recent == signer {
   207  				return nil, errUnauthorized
   208  			}
   209  		}
   210  		snap.Recents[number] = signer
   211  
   212  		// Header authorized, discard any previous votes from the signer
   213  		for i, vote := range snap.Votes {
   214  			if vote.Signer == signer && vote.Address == header.Coinbase {
   215  				// Uncast the vote from the cached tally
   216  				snap.uncast(vote.Address, vote.Authorize)
   217  
   218  				// Uncast the vote from the chronological list
   219  				snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
   220  				break // only one vote allowed
   221  			}
   222  		}
   223  		// Tally up the new vote from the signer
   224  		var authorize bool
   225  		switch {
   226  		case bytes.Compare(header.Nonce[:], nonceAuthVote) == 0:
   227  			authorize = true
   228  		case bytes.Compare(header.Nonce[:], nonceDropVote) == 0:
   229  			authorize = false
   230  		default:
   231  			return nil, errInvalidVote
   232  		}
   233  		if snap.cast(header.Coinbase, authorize) {
   234  			snap.Votes = append(snap.Votes, &Vote{
   235  				Signer:    signer,
   236  				Block:     number,
   237  				Address:   header.Coinbase,
   238  				Authorize: authorize,
   239  			})
   240  		}
   241  		// If the vote passed, update the list of signers
   242  		if tally := snap.Tally[header.Coinbase]; tally.Votes > len(snap.Signers)/2 {
   243  			if tally.Authorize {
   244  				snap.Signers[header.Coinbase] = struct{}{}
   245  			} else {
   246  				delete(snap.Signers, header.Coinbase)
   247  
   248  				// Signer list shrunk, delete any leftover recent caches
   249  				if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
   250  					delete(snap.Recents, number-limit)
   251  				}
   252  				// Discard any previous votes the deauthorized signer cast
   253  				for i := 0; i < len(snap.Votes); i++ {
   254  					if snap.Votes[i].Signer == header.Coinbase {
   255  						// Uncast the vote from the cached tally
   256  						snap.uncast(snap.Votes[i].Address, snap.Votes[i].Authorize)
   257  
   258  						// Uncast the vote from the chronological list
   259  						snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
   260  
   261  						i--
   262  					}
   263  				}
   264  			}
   265  			// Discard any previous votes around the just changed account
   266  			for i := 0; i < len(snap.Votes); i++ {
   267  				if snap.Votes[i].Address == header.Coinbase {
   268  					snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
   269  					i--
   270  				}
   271  			}
   272  			delete(snap.Tally, header.Coinbase)
   273  		}
   274  	}
   275  	snap.Number += uint64(len(headers))
   276  	snap.Hash = headers[len(headers)-1].Hash()
   277  
   278  	return snap, nil
   279  }
   280  
   281  // signers retrieves the list of authorized signers in ascending order.
   282  func (s *Snapshot) signers() []common.Address {
   283  	signers := make([]common.Address, 0, len(s.Signers))
   284  	for signer := range s.Signers {
   285  		signers = append(signers, signer)
   286  	}
   287  	for i := 0; i < len(signers); i++ {
   288  		for j := i + 1; j < len(signers); j++ {
   289  			if bytes.Compare(signers[i][:], signers[j][:]) > 0 {
   290  				signers[i], signers[j] = signers[j], signers[i]
   291  			}
   292  		}
   293  	}
   294  	return signers
   295  }
   296  
   297  // inturn returns if a signer at a given block height is in-turn or not.
   298  func (s *Snapshot) inturn(number uint64, signer common.Address) bool {
   299  	signers, offset := s.signers(), 0
   300  	for offset < len(signers) && signers[offset] != signer {
   301  		offset++
   302  	}
   303  	return (number % uint64(len(signers))) == uint64(offset)
   304  }