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