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