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