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