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