github.com/klaytn/klaytn@v1.10.2/consensus/clique/clique.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/clique.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package clique
    22  
    23  import (
    24  	"bytes"
    25  	"errors"
    26  	"math/big"
    27  	"math/rand"
    28  	"sync"
    29  	"time"
    30  
    31  	lru "github.com/hashicorp/golang-lru"
    32  	"github.com/klaytn/klaytn/accounts"
    33  	"github.com/klaytn/klaytn/blockchain/state"
    34  	"github.com/klaytn/klaytn/blockchain/types"
    35  	"github.com/klaytn/klaytn/common"
    36  	"github.com/klaytn/klaytn/common/hexutil"
    37  	"github.com/klaytn/klaytn/consensus"
    38  	"github.com/klaytn/klaytn/crypto"
    39  	"github.com/klaytn/klaytn/crypto/sha3"
    40  	"github.com/klaytn/klaytn/governance"
    41  	"github.com/klaytn/klaytn/log"
    42  	"github.com/klaytn/klaytn/networks/rpc"
    43  	"github.com/klaytn/klaytn/params"
    44  	"github.com/klaytn/klaytn/rlp"
    45  	"github.com/klaytn/klaytn/storage/database"
    46  )
    47  
    48  const (
    49  	checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database
    50  	inmemorySnapshots  = 128  // Number of recent vote snapshots to keep in memory
    51  	inmemorySignatures = 4096 // Number of recent block signatures to keep in memory
    52  
    53  	wiggleTime = 500 * time.Millisecond // Random delay (per signer) to allow concurrent signers
    54  )
    55  
    56  // Clique proof-of-authority protocol constants.
    57  var (
    58  	epochLength = uint64(30000) // Default number of blocks after which to checkpoint and reset the pending votes
    59  	blockPeriod = uint64(15)    // Default minimum difference between two consecutive block's timestamps
    60  
    61  	ExtraVanity = 32                     // Fixed number of extra-data prefix bytes reserved for signer vanity
    62  	ExtraSeal   = crypto.SignatureLength // Fixed number of extra-data suffix bytes reserved for signer seal
    63  
    64  	nonceAuthVote = hexutil.MustDecode("0xffffffffffffffff") // Magic nonce number to vote on adding a new signer
    65  	nonceDropVote = hexutil.MustDecode("0x0000000000000000") // Magic nonce number to vote on removing a signer.
    66  
    67  	scoreInTurn = big.NewInt(2) // Block blockscore for in-turn signatures
    68  	scoreNoTurn = big.NewInt(1) // Block blockscore for out-of-turn signatures
    69  )
    70  
    71  var logger = log.NewModuleLogger(log.ConsensusClique)
    72  
    73  // Various error messages to mark blocks invalid. These should be private to
    74  // prevent engine specific errors from being referenced in the remainder of the
    75  // codebase, inherently breaking if the engine is swapped out. Please put common
    76  // error types into the consensus package.
    77  var (
    78  	// errUnknownBlock is returned when the list of signers is requested for a block
    79  	// that is not part of the local blockchain.
    80  	errUnknownBlock = errors.New("unknown block")
    81  
    82  	// errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition
    83  	// block has a beneficiary set to non-zeroes.
    84  	errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero")
    85  
    86  	// errInvalidVote is returned if a nonce value is something else that the two
    87  	// allowed constants of 0x00..0 or 0xff..f.
    88  	errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f")
    89  
    90  	// errInvalidCheckpointVote is returned if a checkpoint/epoch transition block
    91  	// has a vote nonce set to non-zeroes.
    92  	errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero")
    93  
    94  	// errMissingVanity is returned if a block's extra-data section is shorter than
    95  	// 32 bytes, which is required to store the signer vanity.
    96  	errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
    97  
    98  	// errMissingSignature is returned if a block's extra-data section doesn't seem
    99  	// to contain a 65 byte secp256k1 signature.
   100  	errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
   101  
   102  	// errExtraSigners is returned if non-checkpoint block contain signer data in
   103  	// their extra-data fields.
   104  	errExtraSigners = errors.New("non-checkpoint block contains extra signer list")
   105  
   106  	// errInvalidCheckpointSigners is returned if a checkpoint block contains an
   107  	// invalid list of signers (i.e. non divisible by 20 bytes).
   108  	errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block")
   109  
   110  	// errMismatchingCheckpointSigners is returned if a checkpoint block contains a
   111  	// list of signers different than the one the local node calculated.
   112  	errMismatchingCheckpointSigners = errors.New("mismatching signer list on checkpoint block")
   113  
   114  	// errInvalidBlockScore is returned if the blockScore of a block neither 1 or 2.
   115  	errInvalidBlockScore = errors.New("invalid blockscore")
   116  
   117  	// errWrongBlockScore is returned if the blockScore of a block doesn't match the
   118  	// turn of the signer.
   119  	errWrongBlockScore = errors.New("wrong blockScore")
   120  
   121  	// ErrInvalidTimestamp is returned if the timestamp of a block is lower than
   122  	// the previous block's timestamp + the minimum block period.
   123  	ErrInvalidTimestamp = errors.New("invalid timestamp")
   124  
   125  	// errInvalidVotingChain is returned if an authorization list is attempted to
   126  	// be modified via out-of-range or non-contiguous headers.
   127  	errInvalidVotingChain = errors.New("invalid voting chain")
   128  
   129  	// errUnauthorizedSigner is returned if a header is signed by a non-authorized entity.
   130  	errUnauthorizedSigner = errors.New("unauthorized signer")
   131  
   132  	// errRecentlySigned is returned if a header is signed by an authorized entity
   133  	// that already signed a header recently, thus is temporarily not allowed to.
   134  	errRecentlySigned = errors.New("recently signed")
   135  
   136  	// errWaitTransactions is returned if an empty block is attempted to be sealed
   137  	// on an instant chain (0 second period). It's important to refuse these as the
   138  	// block reward is zero, so an empty block just bloats the chain... fast.
   139  	errWaitTransactions = errors.New("waiting for transactions")
   140  )
   141  
   142  // SignerFn is a signer callback function to request a hash to be signed by a
   143  // backing account.
   144  type SignerFn func(accounts.Account, []byte) ([]byte, error)
   145  
   146  // sigHash returns the hash which is used as input for the proof-of-authority
   147  // signing. It is the hash of the entire header apart from the 65 byte signature
   148  // contained at the end of the extra data.
   149  //
   150  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   151  // panics. This is done to avoid accidentally using both forms (signature present
   152  // or not), which could be abused to produce different hashes for the same header.
   153  func sigHash(header *types.Header) (hash common.Hash) {
   154  	hasher := sha3.NewKeccak256()
   155  
   156  	rlp.Encode(hasher, []interface{}{
   157  		header.ParentHash,
   158  		header.Root,
   159  		header.TxHash,
   160  		header.ReceiptHash,
   161  		header.Bloom,
   162  		header.BlockScore,
   163  		header.Number,
   164  		header.GasUsed,
   165  		header.Time,
   166  		header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short
   167  	})
   168  	hasher.Sum(hash[:0])
   169  	return hash
   170  }
   171  
   172  // ecrecover extracts the Klaytn account address from a signed header.
   173  func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) {
   174  	// If the signature's already cached, return that
   175  	hash := header.Hash()
   176  	if address, known := sigcache.Get(hash); known {
   177  		return address.(common.Address), nil
   178  	}
   179  	// Retrieve the signature from the header extra-data
   180  	if len(header.Extra) < ExtraSeal {
   181  		return common.Address{}, errMissingSignature
   182  	}
   183  	signature := header.Extra[len(header.Extra)-ExtraSeal:]
   184  
   185  	// Recover the public key and the Klaytn address
   186  	pubkey, err := crypto.Ecrecover(sigHash(header).Bytes(), signature)
   187  	if err != nil {
   188  		return common.Address{}, err
   189  	}
   190  	var signer common.Address
   191  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
   192  
   193  	sigcache.Add(hash, signer)
   194  	return signer, nil
   195  }
   196  
   197  // Clique is the proof-of-authority consensus engine proposed to support the
   198  // Klaytn testnet following the Baobab attacks.
   199  type Clique struct {
   200  	config *params.CliqueConfig // Consensus engine configuration parameters
   201  	db     database.DBManager   // Database to store and retrieve snapshot checkpoints
   202  
   203  	recents    *lru.ARCCache // Snapshots for recent block to speed up reorgs
   204  	signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
   205  
   206  	proposals map[common.Address]bool // Current list of proposals we are pushing
   207  
   208  	signer common.Address // Klaytn address of the signing key
   209  	signFn SignerFn       // Signer function to authorize hashes with
   210  	lock   sync.RWMutex   // Protects the signer fields
   211  
   212  	// The fields below are for testing only
   213  	fakeBlockScore bool // Skip blockScore verifications
   214  }
   215  
   216  // New creates a Clique proof-of-authority consensus engine with the initial
   217  // signers set to the ones provided by the user.
   218  func New(config *params.CliqueConfig, db database.DBManager) *Clique {
   219  	// Set any missing consensus parameters to their defaults
   220  	conf := *config
   221  	if conf.Epoch == 0 {
   222  		conf.Epoch = epochLength
   223  	}
   224  	// Allocate the snapshot caches and create the engine
   225  	recents, _ := lru.NewARC(inmemorySnapshots)
   226  	signatures, _ := lru.NewARC(inmemorySignatures)
   227  
   228  	return &Clique{
   229  		config:     &conf,
   230  		db:         db,
   231  		recents:    recents,
   232  		signatures: signatures,
   233  		proposals:  make(map[common.Address]bool),
   234  	}
   235  }
   236  
   237  // Author implements consensus.Engine, returning the Klaytn address recovered
   238  // from the signature in the header's extra-data section.
   239  func (c *Clique) Author(header *types.Header) (common.Address, error) {
   240  	return ecrecover(header, c.signatures)
   241  }
   242  
   243  // CanVerifyHeadersConcurrently returns true if concurrent header verification possible, otherwise returns false.
   244  func (c *Clique) CanVerifyHeadersConcurrently() bool {
   245  	return true
   246  }
   247  
   248  // PreprocessHeaderVerification prepares header verification for heavy computation before synchronous header verification such as ecrecover.
   249  func (c *Clique) PreprocessHeaderVerification(headers []*types.Header) (chan<- struct{}, <-chan error) {
   250  	panic("this method is not used for Clique engine")
   251  }
   252  
   253  // VerifyHeader checks whether a header conforms to the consensus rules.
   254  func (c *Clique) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
   255  	return c.verifyHeader(chain, header, nil)
   256  }
   257  
   258  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   259  // method returns a quit channel to abort the operations and a results channel to
   260  // retrieve the async verifications (the order is that of the input slice).
   261  func (c *Clique) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   262  	abort := make(chan struct{})
   263  	results := make(chan error, len(headers))
   264  
   265  	go func() {
   266  		for i, header := range headers {
   267  			err := c.verifyHeader(chain, header, headers[:i])
   268  
   269  			select {
   270  			case <-abort:
   271  				return
   272  			case results <- err:
   273  			}
   274  		}
   275  	}()
   276  	return abort, results
   277  }
   278  
   279  // verifyHeader checks whether a header conforms to the consensus rules.The
   280  // caller may optionally pass in a batch of parents (ascending order) to avoid
   281  // looking those up from the database. This is useful for concurrently verifying
   282  // a batch of new headers.
   283  func (c *Clique) verifyHeader(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   284  	if header.Number == nil {
   285  		return errUnknownBlock
   286  	}
   287  	number := header.Number.Uint64()
   288  
   289  	// Don't waste time checking blocks from the future
   290  	if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
   291  		return consensus.ErrFutureBlock
   292  	}
   293  	// Check that the extra-data contains both the vanity and signature
   294  	if len(header.Extra) < ExtraVanity {
   295  		return errMissingVanity
   296  	}
   297  	if len(header.Extra) < ExtraVanity+ExtraSeal {
   298  		return errMissingSignature
   299  	}
   300  	// Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
   301  	signersBytes := len(header.Extra) - ExtraVanity - ExtraSeal
   302  	checkpoint := (number % c.config.Epoch) == 0
   303  	if !checkpoint && signersBytes != 0 {
   304  		return errExtraSigners
   305  	}
   306  	if checkpoint && signersBytes%common.AddressLength != 0 {
   307  		return errInvalidCheckpointSigners
   308  	}
   309  	// Ensure that the block's blockScore is meaningful (may not be correct at this point)
   310  	if number > 0 {
   311  		if header.BlockScore == nil || (header.BlockScore.Cmp(scoreInTurn) != 0 && header.BlockScore.Cmp(scoreNoTurn) != 0) {
   312  			return errInvalidBlockScore
   313  		}
   314  	}
   315  	// All basic checks passed, verify cascading fields
   316  	return c.verifyCascadingFields(chain, header, parents)
   317  }
   318  
   319  // verifyCascadingFields verifies all the header fields that are not standalone,
   320  // rather depend on a batch of previous headers. The caller may optionally pass
   321  // in a batch of parents (ascending order) to avoid looking those up from the
   322  // database. This is useful for concurrently verifying a batch of new headers.
   323  func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   324  	// The genesis block is the always valid dead-end
   325  	number := header.Number.Uint64()
   326  	if number == 0 {
   327  		return nil
   328  	}
   329  	// Ensure that the block's timestamp isn't too close to it's parent
   330  	var parent *types.Header
   331  	if len(parents) > 0 {
   332  		parent = parents[len(parents)-1]
   333  	} else {
   334  		parent = chain.GetHeader(header.ParentHash, number-1)
   335  	}
   336  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   337  		return consensus.ErrUnknownAncestor
   338  	}
   339  	if parent.Time.Uint64()+c.config.Period > header.Time.Uint64() {
   340  		return ErrInvalidTimestamp
   341  	}
   342  	// Retrieve the snapshot needed to verify this header and cache it
   343  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   344  	if err != nil {
   345  		return err
   346  	}
   347  	// If the block is a checkpoint block, verify the signer list
   348  	if number%c.config.Epoch == 0 {
   349  		signers := make([]byte, len(snap.Signers)*common.AddressLength)
   350  		for i, signer := range snap.signers() {
   351  			copy(signers[i*common.AddressLength:], signer[:])
   352  		}
   353  		extraSuffix := len(header.Extra) - ExtraSeal
   354  		if !bytes.Equal(header.Extra[ExtraVanity:extraSuffix], signers) {
   355  			return errInvalidCheckpointSigners
   356  		}
   357  	}
   358  	// All basic checks passed, verify the seal and return
   359  	return c.verifySeal(chain, header, parents)
   360  }
   361  
   362  // CreateSnapshot does not return a snapshot but creates a new snapshot at a given point in time.
   363  func (c *Clique) CreateSnapshot(chain consensus.ChainReader, number uint64, hash common.Hash, parents []*types.Header) error {
   364  	_, err := c.snapshot(chain, number, hash, parents)
   365  	return err
   366  }
   367  
   368  // snapshot retrieves the authorization snapshot at a given point in time.
   369  func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   370  	// Search for a snapshot in memory or on disk for checkpoints
   371  	var (
   372  		headers []*types.Header
   373  		snap    *Snapshot
   374  	)
   375  	for snap == nil {
   376  		// If an in-memory snapshot was found, use that
   377  		if s, ok := c.recents.Get(hash); ok {
   378  			snap = s.(*Snapshot)
   379  			break
   380  		}
   381  		// If an on-disk checkpoint snapshot can be found, use that
   382  		if number%checkpointInterval == 0 {
   383  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil {
   384  				logger.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash)
   385  				snap = s
   386  				break
   387  			}
   388  		}
   389  		// If we're at block zero, make a snapshot
   390  		if number == 0 {
   391  			genesis := chain.GetHeaderByNumber(0)
   392  			if err := c.VerifyHeader(chain, genesis, false); err != nil {
   393  				return nil, err
   394  			}
   395  			signers := make([]common.Address, (len(genesis.Extra)-ExtraVanity-ExtraSeal)/common.AddressLength)
   396  			for i := 0; i < len(signers); i++ {
   397  				copy(signers[i][:], genesis.Extra[ExtraVanity+i*common.AddressLength:])
   398  			}
   399  			snap = newSnapshot(c.config, c.signatures, 0, genesis.Hash(), signers)
   400  			if err := snap.store(c.db); err != nil {
   401  				return nil, err
   402  			}
   403  			logger.Trace("Stored genesis voting snapshot to disk")
   404  			break
   405  		}
   406  		// No snapshot for this header, gather the header and move backward
   407  		var header *types.Header
   408  		if len(parents) > 0 {
   409  			// If we have explicit parents, pick from there (enforced)
   410  			header = parents[len(parents)-1]
   411  			if header.Hash() != hash || header.Number.Uint64() != number {
   412  				return nil, consensus.ErrUnknownAncestor
   413  			}
   414  			parents = parents[:len(parents)-1]
   415  		} else {
   416  			// No explicit parents (or no more left), reach out to the database
   417  			header = chain.GetHeader(hash, number)
   418  			if header == nil {
   419  				return nil, consensus.ErrUnknownAncestor
   420  			}
   421  		}
   422  		headers = append(headers, header)
   423  		number, hash = number-1, header.ParentHash
   424  	}
   425  	// Previous snapshot found, apply any pending headers on top of it
   426  	for i := 0; i < len(headers)/2; i++ {
   427  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   428  	}
   429  	snap, err := snap.apply(headers)
   430  	if err != nil {
   431  		return nil, err
   432  	}
   433  	c.recents.Add(snap.Hash, snap)
   434  
   435  	// If we've generated a new checkpoint snapshot, save to disk
   436  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   437  		if err = snap.store(c.db); err != nil {
   438  			return nil, err
   439  		}
   440  		logger.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   441  	}
   442  	return snap, err
   443  }
   444  
   445  // GetConsensusInfo is not used for Clique engine
   446  func (c *Clique) GetConsensusInfo(block *types.Block) (consensus.ConsensusInfo, error) {
   447  	return consensus.ConsensusInfo{}, nil
   448  }
   449  
   450  // VerifySeal implements consensus.Engine, checking whether the signature contained
   451  // in the header satisfies the consensus protocol requirements.
   452  func (c *Clique) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   453  	return c.verifySeal(chain, header, nil)
   454  }
   455  
   456  // verifySeal checks whether the signature contained in the header satisfies the
   457  // consensus protocol requirements. The method accepts an optional list of parent
   458  // headers that aren't yet part of the local blockchain to generate the snapshots
   459  // from.
   460  func (c *Clique) verifySeal(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   461  	// Verifying the genesis block is not supported
   462  	number := header.Number.Uint64()
   463  	if number == 0 {
   464  		return errUnknownBlock
   465  	}
   466  	// Retrieve the snapshot needed to verify this header and cache it
   467  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   468  	if err != nil {
   469  		return err
   470  	}
   471  
   472  	// Resolve the authorization key and check against signers
   473  	signer, err := ecrecover(header, c.signatures)
   474  	if err != nil {
   475  		logger.Error("ecrecover signer", "addr", signer, "err", err)
   476  		return err
   477  	}
   478  	if _, ok := snap.Signers[signer]; !ok {
   479  		return errUnauthorizedSigner
   480  	}
   481  	for seen, recent := range snap.Recents {
   482  		if recent == signer {
   483  			// Signer is among recents, only fail if the current block doesn't shift it out
   484  			if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit {
   485  				return errRecentlySigned
   486  			}
   487  		}
   488  	}
   489  	// Ensure that the blockScore corresponds to the turn-ness of the signer
   490  	if !c.fakeBlockScore {
   491  		inturn := snap.inturn(header.Number.Uint64(), signer)
   492  		if inturn && header.BlockScore.Cmp(scoreInTurn) != 0 {
   493  			return errInvalidBlockScore
   494  		}
   495  		if !inturn && header.BlockScore.Cmp(scoreNoTurn) != 0 {
   496  			return errInvalidBlockScore
   497  		}
   498  	}
   499  	return nil
   500  }
   501  
   502  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   503  // header for running the transactions on top.
   504  func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) error {
   505  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   506  	number := header.Number.Uint64()
   507  	// Assemble the voting snapshot to check which votes make sense
   508  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   509  	if err != nil {
   510  		return err
   511  	}
   512  	if number%c.config.Epoch != 0 {
   513  		c.lock.RLock()
   514  
   515  		// Gather all the proposals that make sense voting on
   516  		addresses := make([]common.Address, 0, len(c.proposals))
   517  		for address, authorize := range c.proposals {
   518  			if snap.validVote(address, authorize) {
   519  				addresses = append(addresses, address)
   520  			}
   521  		}
   522  		// If there's pending proposals, cast a vote on them
   523  		if len(addresses) > 0 {
   524  			vote := new(governance.GovernanceVote)
   525  			addr := addresses[rand.Intn(len(addresses))]
   526  			if c.proposals[addr] == true {
   527  				vote.Key = "addvalidator"
   528  			} else {
   529  				vote.Key = "removevalidator"
   530  			}
   531  			vote.Value = addr
   532  			encoded, err := rlp.EncodeToBytes(vote)
   533  			if err != nil {
   534  				logger.Error("Failed to RLP Encode a vote", "vote", vote)
   535  			}
   536  			header.Vote = encoded
   537  		}
   538  		c.lock.RUnlock()
   539  	}
   540  	// Set the correct blockScore
   541  	header.BlockScore = CalcBlockScore(snap, c.signer)
   542  
   543  	// Ensure the extra data has all it's components
   544  	if len(header.Extra) < ExtraVanity {
   545  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, ExtraVanity-len(header.Extra))...)
   546  	}
   547  	header.Extra = header.Extra[:ExtraVanity]
   548  
   549  	if number%c.config.Epoch == 0 {
   550  		for _, signer := range snap.signers() {
   551  			header.Extra = append(header.Extra, signer[:]...)
   552  		}
   553  	}
   554  	header.Extra = append(header.Extra, make([]byte, ExtraSeal)...)
   555  
   556  	// Ensure the timestamp has the correct delay
   557  	parent := chain.GetHeader(header.ParentHash, number-1)
   558  	if parent == nil {
   559  		return consensus.ErrUnknownAncestor
   560  	}
   561  	// set header's timestamp
   562  	header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period))
   563  	header.TimeFoS = parent.TimeFoS
   564  	if header.Time.Int64() < time.Now().Unix() {
   565  		t := time.Now()
   566  		header.Time = big.NewInt(t.Unix())
   567  		header.TimeFoS = uint8((t.UnixNano() / 1000 / 1000 / 10) % 100)
   568  	}
   569  	return nil
   570  }
   571  
   572  // Finalize implements consensus.Engine and returns the final block.
   573  func (c *Clique) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, receipts []*types.Receipt) (*types.Block, error) {
   574  	// No block rewards in PoA, so the state remains as is
   575  	header.Root = state.IntermediateRoot(true)
   576  
   577  	// Assemble and return the final block for sealing
   578  	return types.NewBlock(header, txs, receipts), nil
   579  }
   580  
   581  // Authorize injects a private key into the consensus engine to mint new blocks
   582  // with.
   583  func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
   584  	c.lock.Lock()
   585  	defer c.lock.Unlock()
   586  
   587  	c.signer = signer
   588  	c.signFn = signFn
   589  }
   590  
   591  // Seal implements consensus.Engine, attempting to create a sealed block using
   592  // the local signing credentials.
   593  func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
   594  	header := block.Header()
   595  
   596  	// Sealing the genesis block is not supported
   597  	number := header.Number.Uint64()
   598  	if number == 0 {
   599  		return nil, errUnknownBlock
   600  	}
   601  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   602  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   603  		return nil, errWaitTransactions
   604  	}
   605  	// Don't hold the signer fields for the entire sealing procedure
   606  	c.lock.RLock()
   607  	signer, signFn := c.signer, c.signFn
   608  	c.lock.RUnlock()
   609  
   610  	// Bail out if we're unauthorized to sign a block
   611  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   612  	if err != nil {
   613  		return nil, err
   614  	}
   615  	if _, authorized := snap.Signers[signer]; !authorized {
   616  		return nil, errUnauthorizedSigner
   617  	}
   618  	// If we're amongst the recent signers, wait for the next block
   619  	for seen, recent := range snap.Recents {
   620  		if recent == signer {
   621  			// Signer is among recents, only wait if the current block doesn't shift it out
   622  			if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
   623  				logger.Info("Signed recently, must wait for others")
   624  				<-stop
   625  				return nil, nil
   626  			}
   627  		}
   628  	}
   629  	// Sweet, the protocol permits us to sign the block, wait for our time
   630  	delay := time.Unix(header.Time.Int64(), 0).Sub(time.Now()) // nolint: gosimple
   631  	if header.BlockScore.Cmp(scoreNoTurn) == 0 {
   632  		// It's not our turn explicitly to sign, delay it a bit
   633  		wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime
   634  		delay += time.Duration(rand.Int63n(int64(wiggle)))
   635  
   636  		logger.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
   637  	}
   638  	logger.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   639  
   640  	select {
   641  	case <-stop:
   642  		return nil, nil
   643  	case <-time.After(delay):
   644  	}
   645  	// Sign all the things!
   646  	sighash, err := signFn(accounts.Account{Address: signer}, sigHash(header).Bytes())
   647  	if err != nil {
   648  		return nil, err
   649  	}
   650  	copy(header.Extra[len(header.Extra)-ExtraSeal:], sighash)
   651  
   652  	return block.WithSeal(header), nil
   653  }
   654  
   655  // CalcBlockScore is the blockScore adjustment algorithm. It returns the blockScore
   656  // that a new block should have based on the previous blocks in the chain and the
   657  // current signer.
   658  func (c *Clique) CalcBlockScore(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   659  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   660  	if err != nil {
   661  		return nil
   662  	}
   663  	return CalcBlockScore(snap, c.signer)
   664  }
   665  
   666  // CalcBlockScore is the blockScore adjustment algorithm. It returns the blockScore
   667  // that a new block should have based on the previous blocks in the chain and the
   668  // current signer.
   669  func CalcBlockScore(snap *Snapshot, signer common.Address) *big.Int {
   670  	if snap.inturn(snap.Number+1, signer) {
   671  		return new(big.Int).Set(scoreInTurn)
   672  	}
   673  	return new(big.Int).Set(scoreNoTurn)
   674  }
   675  
   676  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   677  // controlling the signer voting.
   678  func (c *Clique) APIs(chain consensus.ChainReader) []rpc.API {
   679  	return []rpc.API{{
   680  		Namespace: "clique",
   681  		Version:   "1.0",
   682  		Service:   &API{chain: chain, clique: c},
   683  		Public:    false,
   684  	}}
   685  }
   686  
   687  // Protocol implements consensus.Engine.Protocol
   688  func (c *Clique) Protocol() consensus.Protocol {
   689  	return consensus.KlayProtocol
   690  }