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