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