github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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  	lru "github.com/hashicorp/golang-lru"
    31  	"golang.org/x/crypto/sha3"
    32  
    33  	"github.com/scroll-tech/go-ethereum/accounts"
    34  	"github.com/scroll-tech/go-ethereum/common"
    35  	"github.com/scroll-tech/go-ethereum/common/hexutil"
    36  	"github.com/scroll-tech/go-ethereum/consensus"
    37  	"github.com/scroll-tech/go-ethereum/consensus/misc"
    38  	"github.com/scroll-tech/go-ethereum/core/state"
    39  	"github.com/scroll-tech/go-ethereum/core/types"
    40  	"github.com/scroll-tech/go-ethereum/crypto"
    41  	"github.com/scroll-tech/go-ethereum/ethdb"
    42  	"github.com/scroll-tech/go-ethereum/log"
    43  	"github.com/scroll-tech/go-ethereum/params"
    44  	"github.com/scroll-tech/go-ethereum/rlp"
    45  	"github.com/scroll-tech/go-ethereum/rpc"
    46  	"github.com/scroll-tech/go-ethereum/trie"
    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 *lru.ARCCache) (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.(common.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.ARCCache // Snapshots for recent block to speed up reorgs
   178  	signatures *lru.ARCCache // 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 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.NewARC(inmemorySnapshots)
   200  	signatures, _ := lru.NewARC(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, seal bool) 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, seals []bool) (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  	cap := uint64(0x7fffffffffffffff)
   300  	if header.GasLimit > cap {
   301  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   302  	}
   303  	// If all checks passed, validate any special fields for hard forks
   304  	if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
   305  		return err
   306  	}
   307  	// All basic checks passed, verify cascading fields
   308  	return c.verifyCascadingFields(chain, header, parents)
   309  }
   310  
   311  // verifyCascadingFields verifies all the header fields that are not standalone,
   312  // rather depend on a batch of previous headers. The caller may optionally pass
   313  // in a batch of parents (ascending order) to avoid looking those up from the
   314  // database. This is useful for concurrently verifying a batch of new headers.
   315  func (c *Clique) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   316  	// The genesis block is the always valid dead-end
   317  	number := header.Number.Uint64()
   318  	if number == 0 {
   319  		return nil
   320  	}
   321  	// Ensure that the block's timestamp isn't too close to its parent
   322  	var parent *types.Header
   323  	if len(parents) > 0 {
   324  		parent = parents[len(parents)-1]
   325  	} else {
   326  		parent = chain.GetHeader(header.ParentHash, number-1)
   327  	}
   328  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   329  		return consensus.ErrUnknownAncestor
   330  	}
   331  	if parent.Time+c.config.Period > header.Time {
   332  		return errInvalidTimestamp
   333  	}
   334  	// Verify that the gasUsed is <= gasLimit
   335  	if header.GasUsed > header.GasLimit {
   336  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   337  	}
   338  	if !chain.Config().IsLondon(header.Number) {
   339  		// Verify BaseFee not present before EIP-1559 fork.
   340  		if header.BaseFee != nil {
   341  			return fmt.Errorf("invalid baseFee before fork: have %d, want <nil>", header.BaseFee)
   342  		}
   343  		if err := misc.VerifyGaslimit(parent.GasLimit, header.GasLimit); err != nil {
   344  			return err
   345  		}
   346  	} else if err := misc.VerifyEip1559Header(chain.Config(), parent, header); err != nil {
   347  		// Verify the header's EIP-1559 attributes.
   348  		return err
   349  	}
   350  	// Retrieve the snapshot needed to verify this header and cache it
   351  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   352  	if err != nil {
   353  		return err
   354  	}
   355  	// If the block is a checkpoint block, verify the signer list
   356  	if number%c.config.Epoch == 0 {
   357  		signers := make([]byte, len(snap.Signers)*common.AddressLength)
   358  		for i, signer := range snap.signers() {
   359  			copy(signers[i*common.AddressLength:], signer[:])
   360  		}
   361  		extraSuffix := len(header.Extra) - extraSeal
   362  		if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) {
   363  			return errMismatchingCheckpointSigners
   364  		}
   365  	}
   366  	// All basic checks passed, verify the seal and return
   367  	return c.verifySeal(snap, header, parents)
   368  }
   369  
   370  // snapshot retrieves the authorization snapshot at a given point in time.
   371  func (c *Clique) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   372  	// Search for a snapshot in memory or on disk for checkpoints
   373  	var (
   374  		headers []*types.Header
   375  		snap    *Snapshot
   376  	)
   377  	for snap == nil {
   378  		// If an in-memory snapshot was found, use that
   379  		if s, ok := c.recents.Get(hash); ok {
   380  			snap = s.(*Snapshot)
   381  			break
   382  		}
   383  		// If an on-disk checkpoint snapshot can be found, use that
   384  		if number%checkpointInterval == 0 {
   385  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil {
   386  				log.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash)
   387  				snap = s
   388  				break
   389  			}
   390  		}
   391  		// If we're at the genesis, snapshot the initial state. Alternatively if we're
   392  		// at a checkpoint block without a parent (light client CHT), or we have piled
   393  		// up more headers than allowed to be reorged (chain reinit from a freezer),
   394  		// consider the checkpoint trusted and snapshot it.
   395  		if number == 0 || (number%c.config.Epoch == 0 && (len(headers) > params.FullImmutabilityThreshold || chain.GetHeaderByNumber(number-1) == nil)) {
   396  			checkpoint := chain.GetHeaderByNumber(number)
   397  			if checkpoint != nil {
   398  				hash := checkpoint.Hash()
   399  
   400  				signers := make([]common.Address, (len(checkpoint.Extra)-extraVanity-extraSeal)/common.AddressLength)
   401  				for i := 0; i < len(signers); i++ {
   402  					copy(signers[i][:], checkpoint.Extra[extraVanity+i*common.AddressLength:])
   403  				}
   404  				snap = newSnapshot(c.config, c.signatures, number, hash, signers)
   405  				if err := snap.store(c.db); err != nil {
   406  					return nil, err
   407  				}
   408  				log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash)
   409  				break
   410  			}
   411  		}
   412  		// No snapshot for this header, gather the header and move backward
   413  		var header *types.Header
   414  		if len(parents) > 0 {
   415  			// If we have explicit parents, pick from there (enforced)
   416  			header = parents[len(parents)-1]
   417  			if header.Hash() != hash || header.Number.Uint64() != number {
   418  				return nil, consensus.ErrUnknownAncestor
   419  			}
   420  			parents = parents[:len(parents)-1]
   421  		} else {
   422  			// No explicit parents (or no more left), reach out to the database
   423  			header = chain.GetHeader(hash, number)
   424  			if header == nil {
   425  				return nil, consensus.ErrUnknownAncestor
   426  			}
   427  		}
   428  		headers = append(headers, header)
   429  		number, hash = number-1, header.ParentHash
   430  	}
   431  	// Previous snapshot found, apply any pending headers on top of it
   432  	for i := 0; i < len(headers)/2; i++ {
   433  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   434  	}
   435  	snap, err := snap.apply(headers)
   436  	if err != nil {
   437  		return nil, err
   438  	}
   439  	c.recents.Add(snap.Hash, snap)
   440  
   441  	// If we've generated a new checkpoint snapshot, save to disk
   442  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   443  		if err = snap.store(c.db); err != nil {
   444  			return nil, err
   445  		}
   446  		log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   447  	}
   448  	return snap, err
   449  }
   450  
   451  // VerifyUncles implements consensus.Engine, always returning an error for any
   452  // uncles as this consensus mechanism doesn't permit uncles.
   453  func (c *Clique) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   454  	if len(block.Uncles()) > 0 {
   455  		return errors.New("uncles not allowed")
   456  	}
   457  	return nil
   458  }
   459  
   460  // verifySeal checks whether the signature contained in the header satisfies the
   461  // consensus protocol requirements. The method accepts an optional list of parent
   462  // headers that aren't yet part of the local blockchain to generate the snapshots
   463  // from.
   464  func (c *Clique) verifySeal(snap *Snapshot, header *types.Header, parents []*types.Header) error {
   465  	// Verifying the genesis block is not supported
   466  	number := header.Number.Uint64()
   467  	if number == 0 {
   468  		return errUnknownBlock
   469  	}
   470  	// Resolve the authorization key and check against signers
   471  	signer, err := ecrecover(header, c.signatures)
   472  	if err != nil {
   473  		return err
   474  	}
   475  	if _, ok := snap.Signers[signer]; !ok {
   476  		return errUnauthorizedSigner
   477  	}
   478  	for seen, recent := range snap.Recents {
   479  		if recent == signer {
   480  			// Signer is among recents, only fail if the current block doesn't shift it out
   481  			if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit {
   482  				return errRecentlySigned
   483  			}
   484  		}
   485  	}
   486  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   487  	if !c.fakeDiff {
   488  		inturn := snap.inturn(header.Number.Uint64(), signer)
   489  		if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
   490  			return errWrongDifficulty
   491  		}
   492  		if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
   493  			return errWrongDifficulty
   494  		}
   495  	}
   496  	return nil
   497  }
   498  
   499  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   500  // header for running the transactions on top.
   501  func (c *Clique) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   502  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   503  	header.Coinbase = common.Address{}
   504  	header.Nonce = types.BlockNonce{}
   505  
   506  	number := header.Number.Uint64()
   507  	// Assemble the voting snapshot to check which votes make sense
   508  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   509  	if err != nil {
   510  		return err
   511  	}
   512  	if number%c.config.Epoch != 0 {
   513  		c.lock.RLock()
   514  
   515  		// Gather all the proposals that make sense voting on
   516  		addresses := make([]common.Address, 0, len(c.proposals))
   517  		for address, authorize := range c.proposals {
   518  			if snap.validVote(address, authorize) {
   519  				addresses = append(addresses, address)
   520  			}
   521  		}
   522  		// If there's pending proposals, cast a vote on them
   523  		if len(addresses) > 0 {
   524  			header.Coinbase = addresses[rand.Intn(len(addresses))]
   525  			if c.proposals[header.Coinbase] {
   526  				copy(header.Nonce[:], nonceAuthVote)
   527  			} else {
   528  				copy(header.Nonce[:], nonceDropVote)
   529  			}
   530  		}
   531  		c.lock.RUnlock()
   532  	}
   533  	// Set the correct difficulty
   534  	header.Difficulty = calcDifficulty(snap, c.signer)
   535  
   536  	// Ensure the extra data has all its components
   537  	if len(header.Extra) < extraVanity {
   538  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   539  	}
   540  	header.Extra = header.Extra[:extraVanity]
   541  
   542  	if number%c.config.Epoch == 0 {
   543  		for _, signer := range snap.signers() {
   544  			header.Extra = append(header.Extra, signer[:]...)
   545  		}
   546  	}
   547  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   548  
   549  	// Mix digest is reserved for now, set to empty
   550  	header.MixDigest = common.Hash{}
   551  
   552  	// Ensure the timestamp has the correct delay
   553  	parent := chain.GetHeader(header.ParentHash, number-1)
   554  	if parent == nil {
   555  		return consensus.ErrUnknownAncestor
   556  	}
   557  	header.Time = parent.Time + c.config.Period
   558  	if header.Time < uint64(time.Now().Unix()) {
   559  		header.Time = uint64(time.Now().Unix())
   560  	}
   561  	return nil
   562  }
   563  
   564  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   565  // rewards given.
   566  func (c *Clique) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
   567  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   568  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   569  	header.UncleHash = types.CalcUncleHash(nil)
   570  }
   571  
   572  // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
   573  // nor block rewards given, and returns the final block.
   574  func (c *Clique) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
   575  	// Finalize block
   576  	c.Finalize(chain, header, state, txs, uncles)
   577  
   578  	// Assemble and return the final block for sealing
   579  	return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil
   580  }
   581  
   582  // Authorize injects a private key into the consensus engine to mint new blocks
   583  // with.
   584  func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
   585  	c.lock.Lock()
   586  	defer c.lock.Unlock()
   587  
   588  	c.signer = signer
   589  	c.signFn = signFn
   590  }
   591  
   592  // Seal implements consensus.Engine, attempting to create a sealed block using
   593  // the local signing credentials.
   594  func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
   595  	header := block.Header()
   596  
   597  	// Sealing the genesis block is not supported
   598  	number := header.Number.Uint64()
   599  	if number == 0 {
   600  		return errUnknownBlock
   601  	}
   602  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   603  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   604  		return errors.New("sealing paused while waiting for transactions")
   605  	}
   606  	// Don't hold the signer fields for the entire sealing procedure
   607  	c.lock.RLock()
   608  	signer, signFn := c.signer, c.signFn
   609  	c.lock.RUnlock()
   610  
   611  	// Bail out if we're unauthorized to sign a block
   612  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   613  	if err != nil {
   614  		return err
   615  	}
   616  	if _, authorized := snap.Signers[signer]; !authorized {
   617  		return errUnauthorizedSigner
   618  	}
   619  	// If we're amongst the recent signers, wait for the next block
   620  	for seen, recent := range snap.Recents {
   621  		if recent == signer {
   622  			// Signer is among recents, only wait if the current block doesn't shift it out
   623  			if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
   624  				return errors.New("signed recently, must wait for others")
   625  			}
   626  		}
   627  	}
   628  	// Sweet, the protocol permits us to sign the block, wait for our time
   629  	delay := time.Unix(int64(header.Time), 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  	// Sign all the things!
   638  	sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeClique, CliqueRLP(header))
   639  	if err != nil {
   640  		return err
   641  	}
   642  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   643  	// Wait until sealing is terminated or delay timeout.
   644  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   645  	go func() {
   646  		select {
   647  		case <-stop:
   648  			return
   649  		case <-time.After(delay):
   650  		}
   651  
   652  		select {
   653  		case results <- block.WithSeal(header):
   654  		default:
   655  			log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header))
   656  		}
   657  	}()
   658  
   659  	return nil
   660  }
   661  
   662  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   663  // that a new block should have:
   664  // * DIFF_NOTURN(2) if BLOCK_NUMBER % SIGNER_COUNT != SIGNER_INDEX
   665  // * DIFF_INTURN(1) if BLOCK_NUMBER % SIGNER_COUNT == SIGNER_INDEX
   666  func (c *Clique) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   667  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   668  	if err != nil {
   669  		return nil
   670  	}
   671  	return calcDifficulty(snap, c.signer)
   672  }
   673  
   674  func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
   675  	if snap.inturn(snap.Number+1, signer) {
   676  		return new(big.Int).Set(diffInTurn)
   677  	}
   678  	return new(big.Int).Set(diffNoTurn)
   679  }
   680  
   681  // SealHash returns the hash of a block prior to it being sealed.
   682  func (c *Clique) SealHash(header *types.Header) common.Hash {
   683  	return SealHash(header)
   684  }
   685  
   686  // Close implements consensus.Engine. It's a noop for clique as there are no background threads.
   687  func (c *Clique) Close() error {
   688  	return nil
   689  }
   690  
   691  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   692  // controlling the signer voting.
   693  func (c *Clique) APIs(chain consensus.ChainHeaderReader) []rpc.API {
   694  	return []rpc.API{{
   695  		Namespace: "clique",
   696  		Version:   "1.0",
   697  		Service:   &API{chain: chain, clique: c},
   698  		Public:    false,
   699  	}}
   700  }
   701  
   702  // SealHash returns the hash of a block prior to it being sealed.
   703  func SealHash(header *types.Header) (hash common.Hash) {
   704  	hasher := sha3.NewLegacyKeccak256()
   705  	encodeSigHeader(hasher, header)
   706  	hasher.(crypto.KeccakState).Read(hash[:])
   707  	return hash
   708  }
   709  
   710  // CliqueRLP returns the rlp bytes which needs to be signed for the proof-of-authority
   711  // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
   712  // contained at the end of the extra data.
   713  //
   714  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   715  // panics. This is done to avoid accidentally using both forms (signature present
   716  // or not), which could be abused to produce different hashes for the same header.
   717  func CliqueRLP(header *types.Header) []byte {
   718  	b := new(bytes.Buffer)
   719  	encodeSigHeader(b, header)
   720  	return b.Bytes()
   721  }
   722  
   723  func encodeSigHeader(w io.Writer, header *types.Header) {
   724  	enc := []interface{}{
   725  		header.ParentHash,
   726  		header.UncleHash,
   727  		header.Coinbase,
   728  		header.Root,
   729  		header.TxHash,
   730  		header.ReceiptHash,
   731  		header.Bloom,
   732  		header.Difficulty,
   733  		header.Number,
   734  		header.GasLimit,
   735  		header.GasUsed,
   736  		header.Time,
   737  		header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short
   738  		header.MixDigest,
   739  		header.Nonce,
   740  	}
   741  	if header.BaseFee != nil {
   742  		enc = append(enc, header.BaseFee)
   743  	}
   744  	if err := rlp.Encode(w, enc); err != nil {
   745  		panic("can't encode: " + err.Error())
   746  	}
   747  }