github.com/calmw/ethereum@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/calmw/ethereum/accounts"
    31  	"github.com/calmw/ethereum/common"
    32  	"github.com/calmw/ethereum/common/hexutil"
    33  	lru "github.com/calmw/ethereum/common/lru"
    34  	"github.com/calmw/ethereum/consensus"
    35  	"github.com/calmw/ethereum/consensus/misc"
    36  	"github.com/calmw/ethereum/core/state"
    37  	"github.com/calmw/ethereum/core/types"
    38  	"github.com/calmw/ethereum/crypto"
    39  	"github.com/calmw/ethereum/ethdb"
    40  	"github.com/calmw/ethereum/log"
    41  	"github.com/calmw/ethereum/params"
    42  	"github.com/calmw/ethereum/rlp"
    43  	"github.com/calmw/ethereum/rpc"
    44  	"github.com/calmw/ethereum/trie"
    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 *sigLRU) (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, 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.Cache[common.Hash, *Snapshot] // Snapshots for recent block to speed up reorgs
   177  	signatures *sigLRU                            // 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.NewCache[common.Hash, *Snapshot](inmemorySnapshots)
   199  	signatures := lru.NewCache[common.Hash, common.Address](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) 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) (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 chain.Config().IsShanghai(header.Time) {
   302  		return fmt.Errorf("clique does not support shanghai fork")
   303  	}
   304  	if chain.Config().IsCancun(header.Time) {
   305  		return fmt.Errorf("clique does not support cancun fork")
   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
   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  	c.lock.RLock()
   513  	if number%c.config.Epoch != 0 {
   514  		// Gather all the proposals that make sense voting on
   515  		addresses := make([]common.Address, 0, len(c.proposals))
   516  		for address, authorize := range c.proposals {
   517  			if snap.validVote(address, authorize) {
   518  				addresses = append(addresses, address)
   519  			}
   520  		}
   521  		// If there's pending proposals, cast a vote on them
   522  		if len(addresses) > 0 {
   523  			header.Coinbase = addresses[rand.Intn(len(addresses))]
   524  			if c.proposals[header.Coinbase] {
   525  				copy(header.Nonce[:], nonceAuthVote)
   526  			} else {
   527  				copy(header.Nonce[:], nonceDropVote)
   528  			}
   529  		}
   530  	}
   531  
   532  	// Copy signer protected by mutex to avoid race condition
   533  	signer := c.signer
   534  	c.lock.RUnlock()
   535  
   536  	// Set the correct difficulty
   537  	header.Difficulty = calcDifficulty(snap, signer)
   538  
   539  	// Ensure the extra data has all its components
   540  	if len(header.Extra) < extraVanity {
   541  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   542  	}
   543  	header.Extra = header.Extra[:extraVanity]
   544  
   545  	if number%c.config.Epoch == 0 {
   546  		for _, signer := range snap.signers() {
   547  			header.Extra = append(header.Extra, signer[:]...)
   548  		}
   549  	}
   550  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   551  
   552  	// Mix digest is reserved for now, set to empty
   553  	header.MixDigest = common.Hash{}
   554  
   555  	// Ensure the timestamp has the correct delay
   556  	parent := chain.GetHeader(header.ParentHash, number-1)
   557  	if parent == nil {
   558  		return consensus.ErrUnknownAncestor
   559  	}
   560  	header.Time = parent.Time + c.config.Period
   561  	if header.Time < uint64(time.Now().Unix()) {
   562  		header.Time = uint64(time.Now().Unix())
   563  	}
   564  	return nil
   565  }
   566  
   567  // Finalize implements consensus.Engine. There is no post-transaction
   568  // consensus rules in clique, do nothing here.
   569  func (c *Clique) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, withdrawals []*types.Withdrawal) {
   570  	// No block rewards in PoA, so the state remains as is
   571  }
   572  
   573  // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
   574  // nor block rewards given, and returns the final block.
   575  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) {
   576  	if len(withdrawals) > 0 {
   577  		return nil, errors.New("clique does not support withdrawals")
   578  	}
   579  	// Finalize block
   580  	c.Finalize(chain, header, state, txs, uncles, nil)
   581  
   582  	// Assign the final state root to header.
   583  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   584  
   585  	// Assemble and return the final block for sealing.
   586  	return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil
   587  }
   588  
   589  // Authorize injects a private key into the consensus engine to mint new blocks
   590  // with.
   591  func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
   592  	c.lock.Lock()
   593  	defer c.lock.Unlock()
   594  
   595  	c.signer = signer
   596  	c.signFn = signFn
   597  }
   598  
   599  // Seal implements consensus.Engine, attempting to create a sealed block using
   600  // the local signing credentials.
   601  func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
   602  	header := block.Header()
   603  
   604  	// Sealing the genesis block is not supported
   605  	number := header.Number.Uint64()
   606  	if number == 0 {
   607  		return errUnknownBlock
   608  	}
   609  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   610  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   611  		return errors.New("sealing paused while waiting for transactions")
   612  	}
   613  	// Don't hold the signer fields for the entire sealing procedure
   614  	c.lock.RLock()
   615  	signer, signFn := c.signer, c.signFn
   616  	c.lock.RUnlock()
   617  
   618  	// Bail out if we're unauthorized to sign a block
   619  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   620  	if err != nil {
   621  		return err
   622  	}
   623  	if _, authorized := snap.Signers[signer]; !authorized {
   624  		return errUnauthorizedSigner
   625  	}
   626  	// If we're amongst the recent signers, wait for the next block
   627  	for seen, recent := range snap.Recents {
   628  		if recent == signer {
   629  			// Signer is among recents, only wait if the current block doesn't shift it out
   630  			if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
   631  				return errors.New("signed recently, must wait for others")
   632  			}
   633  		}
   634  	}
   635  	// Sweet, the protocol permits us to sign the block, wait for our time
   636  	delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple
   637  	if header.Difficulty.Cmp(diffNoTurn) == 0 {
   638  		// It's not our turn explicitly to sign, delay it a bit
   639  		wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime
   640  		delay += time.Duration(rand.Int63n(int64(wiggle)))
   641  
   642  		log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
   643  	}
   644  	// Sign all the things!
   645  	sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeClique, CliqueRLP(header))
   646  	if err != nil {
   647  		return err
   648  	}
   649  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   650  	// Wait until sealing is terminated or delay timeout.
   651  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   652  	go func() {
   653  		select {
   654  		case <-stop:
   655  			return
   656  		case <-time.After(delay):
   657  		}
   658  
   659  		select {
   660  		case results <- block.WithSeal(header):
   661  		default:
   662  			log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header))
   663  		}
   664  	}()
   665  
   666  	return nil
   667  }
   668  
   669  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   670  // that a new block should have:
   671  // * DIFF_NOTURN(2) if BLOCK_NUMBER % SIGNER_COUNT != SIGNER_INDEX
   672  // * DIFF_INTURN(1) if BLOCK_NUMBER % SIGNER_COUNT == SIGNER_INDEX
   673  func (c *Clique) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   674  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   675  	if err != nil {
   676  		return nil
   677  	}
   678  	c.lock.RLock()
   679  	signer := c.signer
   680  	c.lock.RUnlock()
   681  	return calcDifficulty(snap, signer)
   682  }
   683  
   684  func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
   685  	if snap.inturn(snap.Number+1, signer) {
   686  		return new(big.Int).Set(diffInTurn)
   687  	}
   688  	return new(big.Int).Set(diffNoTurn)
   689  }
   690  
   691  // SealHash returns the hash of a block prior to it being sealed.
   692  func (c *Clique) SealHash(header *types.Header) common.Hash {
   693  	return SealHash(header)
   694  }
   695  
   696  // Close implements consensus.Engine. It's a noop for clique as there are no background threads.
   697  func (c *Clique) Close() error {
   698  	return nil
   699  }
   700  
   701  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   702  // controlling the signer voting.
   703  func (c *Clique) APIs(chain consensus.ChainHeaderReader) []rpc.API {
   704  	return []rpc.API{{
   705  		Namespace: "clique",
   706  		Service:   &API{chain: chain, clique: c},
   707  	}}
   708  }
   709  
   710  // SealHash returns the hash of a block prior to it being sealed.
   711  func SealHash(header *types.Header) (hash common.Hash) {
   712  	hasher := sha3.NewLegacyKeccak256()
   713  	encodeSigHeader(hasher, header)
   714  	hasher.(crypto.KeccakState).Read(hash[:])
   715  	return hash
   716  }
   717  
   718  // CliqueRLP returns the rlp bytes which needs to be signed for the proof-of-authority
   719  // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
   720  // contained at the end of the extra data.
   721  //
   722  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   723  // panics. This is done to avoid accidentally using both forms (signature present
   724  // or not), which could be abused to produce different hashes for the same header.
   725  func CliqueRLP(header *types.Header) []byte {
   726  	b := new(bytes.Buffer)
   727  	encodeSigHeader(b, header)
   728  	return b.Bytes()
   729  }
   730  
   731  func encodeSigHeader(w io.Writer, header *types.Header) {
   732  	enc := []interface{}{
   733  		header.ParentHash,
   734  		header.UncleHash,
   735  		header.Coinbase,
   736  		header.Root,
   737  		header.TxHash,
   738  		header.ReceiptHash,
   739  		header.Bloom,
   740  		header.Difficulty,
   741  		header.Number,
   742  		header.GasLimit,
   743  		header.GasUsed,
   744  		header.Time,
   745  		header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short
   746  		header.MixDigest,
   747  		header.Nonce,
   748  	}
   749  	if header.BaseFee != nil {
   750  		enc = append(enc, header.BaseFee)
   751  	}
   752  	if header.WithdrawalsHash != nil {
   753  		panic("unexpected withdrawal hash value in clique")
   754  	}
   755  	if err := rlp.Encode(w, enc); err != nil {
   756  		panic("can't encode: " + err.Error())
   757  	}
   758  }