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