github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/consensus/clique/snapshot.go (about)

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