github.com/amazechain/amc@v0.1.3/internal/consensus/apoa/snapshot.go (about)

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