github.com/klaytn/klaytn@v1.12.1/consensus/clique/snapshot.go (about)

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