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