github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/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   = 65 // 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.Cmp(big.NewInt(time.Now().Unix())) > 0 {
   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 it's 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.Uint64()+c.config.Period > header.Time.Uint64() {
   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 an checkpoint block, make a snapshot if it's known
   369  		if number == 0 || (number%c.config.Epoch == 0 && chain.GetHeaderByNumber(number-1) == nil) {
   370  			checkpoint := chain.GetHeaderByNumber(number)
   371  			if checkpoint != nil {
   372  				hash := checkpoint.Hash()
   373  
   374  				signers := make([]common.Address, (len(checkpoint.Extra)-extraVanity-extraSeal)/common.AddressLength)
   375  				for i := 0; i < len(signers); i++ {
   376  					copy(signers[i][:], checkpoint.Extra[extraVanity+i*common.AddressLength:])
   377  				}
   378  				snap = newSnapshot(c.config, c.signatures, number, hash, signers)
   379  				if err := snap.store(c.db); err != nil {
   380  					return nil, err
   381  				}
   382  				log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash)
   383  				break
   384  			}
   385  		}
   386  		// No snapshot for this header, gather the header and move backward
   387  		var header *types.Header
   388  		if len(parents) > 0 {
   389  			// If we have explicit parents, pick from there (enforced)
   390  			header = parents[len(parents)-1]
   391  			if header.Hash() != hash || header.Number.Uint64() != number {
   392  				return nil, consensus.ErrUnknownAncestor
   393  			}
   394  			parents = parents[:len(parents)-1]
   395  		} else {
   396  			// No explicit parents (or no more left), reach out to the database
   397  			header = chain.GetHeader(hash, number)
   398  			if header == nil {
   399  				return nil, consensus.ErrUnknownAncestor
   400  			}
   401  		}
   402  		headers = append(headers, header)
   403  		number, hash = number-1, header.ParentHash
   404  	}
   405  	// Previous snapshot found, apply any pending headers on top of it
   406  	for i := 0; i < len(headers)/2; i++ {
   407  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   408  	}
   409  	snap, err := snap.apply(headers)
   410  	if err != nil {
   411  		return nil, err
   412  	}
   413  	c.recents.Add(snap.Hash, snap)
   414  
   415  	// If we've generated a new checkpoint snapshot, save to disk
   416  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   417  		if err = snap.store(c.db); err != nil {
   418  			return nil, err
   419  		}
   420  		log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   421  	}
   422  	return snap, err
   423  }
   424  
   425  // VerifyUncles implements consensus.Engine, always returning an error for any
   426  // uncles as this consensus mechanism doesn't permit uncles.
   427  func (c *Clique) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   428  	if len(block.Uncles()) > 0 {
   429  		return errors.New("uncles not allowed")
   430  	}
   431  	return nil
   432  }
   433  
   434  // VerifySeal implements consensus.Engine, checking whether the signature contained
   435  // in the header satisfies the consensus protocol requirements.
   436  func (c *Clique) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   437  	return c.verifySeal(chain, header, nil)
   438  }
   439  
   440  // verifySeal checks whether the signature contained in the header satisfies the
   441  // consensus protocol requirements. The method accepts an optional list of parent
   442  // headers that aren't yet part of the local blockchain to generate the snapshots
   443  // from.
   444  func (c *Clique) verifySeal(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   445  	// Verifying the genesis block is not supported
   446  	number := header.Number.Uint64()
   447  	if number == 0 {
   448  		return errUnknownBlock
   449  	}
   450  	// Retrieve the snapshot needed to verify this header and cache it
   451  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   452  	if err != nil {
   453  		return err
   454  	}
   455  
   456  	// Resolve the authorization key and check against signers
   457  	signer, err := ecrecover(header, c.signatures)
   458  	if err != nil {
   459  		return err
   460  	}
   461  	if _, ok := snap.Signers[signer]; !ok {
   462  		return errUnauthorizedSigner
   463  	}
   464  	for seen, recent := range snap.Recents {
   465  		if recent == signer {
   466  			// Signer is among recents, only fail if the current block doesn't shift it out
   467  			if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit {
   468  				return errRecentlySigned
   469  			}
   470  		}
   471  	}
   472  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   473  	if !c.fakeDiff {
   474  		inturn := snap.inturn(header.Number.Uint64(), signer)
   475  		if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
   476  			return errWrongDifficulty
   477  		}
   478  		if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
   479  			return errWrongDifficulty
   480  		}
   481  	}
   482  	return nil
   483  }
   484  
   485  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   486  // header for running the transactions on top.
   487  func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) error {
   488  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   489  	header.Coinbase = common.Address{}
   490  	header.Nonce = types.BlockNonce{}
   491  
   492  	number := header.Number.Uint64()
   493  	// Assemble the voting snapshot to check which votes make sense
   494  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   495  	if err != nil {
   496  		return err
   497  	}
   498  	if number%c.config.Epoch != 0 {
   499  		c.lock.RLock()
   500  
   501  		// Gather all the proposals that make sense voting on
   502  		addresses := make([]common.Address, 0, len(c.proposals))
   503  		for address, authorize := range c.proposals {
   504  			if snap.validVote(address, authorize) {
   505  				addresses = append(addresses, address)
   506  			}
   507  		}
   508  		// If there's pending proposals, cast a vote on them
   509  		if len(addresses) > 0 {
   510  			header.Coinbase = addresses[rand.Intn(len(addresses))]
   511  			if c.proposals[header.Coinbase] {
   512  				copy(header.Nonce[:], nonceAuthVote)
   513  			} else {
   514  				copy(header.Nonce[:], nonceDropVote)
   515  			}
   516  		}
   517  		c.lock.RUnlock()
   518  	}
   519  	// Set the correct difficulty
   520  	header.Difficulty = CalcDifficulty(snap, c.signer)
   521  
   522  	// Ensure the extra data has all it's components
   523  	if len(header.Extra) < extraVanity {
   524  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   525  	}
   526  	header.Extra = header.Extra[:extraVanity]
   527  
   528  	if number%c.config.Epoch == 0 {
   529  		for _, signer := range snap.signers() {
   530  			header.Extra = append(header.Extra, signer[:]...)
   531  		}
   532  	}
   533  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   534  
   535  	// Mix digest is reserved for now, set to empty
   536  	header.MixDigest = common.Hash{}
   537  
   538  	// Ensure the timestamp has the correct delay
   539  	parent := chain.GetHeader(header.ParentHash, number-1)
   540  	if parent == nil {
   541  		return consensus.ErrUnknownAncestor
   542  	}
   543  	header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period))
   544  	if header.Time.Int64() < time.Now().Unix() {
   545  		header.Time = big.NewInt(time.Now().Unix())
   546  	}
   547  	return nil
   548  }
   549  
   550  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   551  // rewards given, and returns the final block.
   552  func (c *Clique) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
   553  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   554  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   555  	header.UncleHash = types.CalcUncleHash(nil)
   556  
   557  	// Assemble and return the final block for sealing
   558  	return types.NewBlock(header, txs, nil, receipts), nil
   559  }
   560  
   561  // Authorize injects a private key into the consensus engine to mint new blocks
   562  // with.
   563  func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
   564  	c.lock.Lock()
   565  	defer c.lock.Unlock()
   566  
   567  	c.signer = signer
   568  	c.signFn = signFn
   569  }
   570  
   571  // Seal implements consensus.Engine, attempting to create a sealed block using
   572  // the local signing credentials.
   573  func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
   574  	header := block.Header()
   575  
   576  	// Sealing the genesis block is not supported
   577  	number := header.Number.Uint64()
   578  	if number == 0 {
   579  		return errUnknownBlock
   580  	}
   581  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   582  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   583  		log.Info("Sealing paused, waiting for transactions")
   584  		return nil
   585  	}
   586  	// Don't hold the signer fields for the entire sealing procedure
   587  	c.lock.RLock()
   588  	signer, signFn := c.signer, c.signFn
   589  	c.lock.RUnlock()
   590  
   591  	// Bail out if we're unauthorized to sign a block
   592  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   593  	if err != nil {
   594  		return err
   595  	}
   596  	if _, authorized := snap.Signers[signer]; !authorized {
   597  		return errUnauthorizedSigner
   598  	}
   599  	// If we're amongst the recent signers, wait for the next block
   600  	for seen, recent := range snap.Recents {
   601  		if recent == signer {
   602  			// Signer is among recents, only wait if the current block doesn't shift it out
   603  			if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
   604  				log.Info("Signed recently, must wait for others")
   605  				return nil
   606  			}
   607  		}
   608  	}
   609  	// Sweet, the protocol permits us to sign the block, wait for our time
   610  	delay := time.Unix(header.Time.Int64(), 0).Sub(time.Now()) // nolint: gosimple
   611  	if header.Difficulty.Cmp(diffNoTurn) == 0 {
   612  		// It's not our turn explicitly to sign, delay it a bit
   613  		wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime
   614  		delay += time.Duration(rand.Int63n(int64(wiggle)))
   615  
   616  		log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
   617  	}
   618  	// Sign all the things!
   619  	sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeClique, CliqueRLP(header))
   620  	if err != nil {
   621  		return err
   622  	}
   623  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   624  	// Wait until sealing is terminated or delay timeout.
   625  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   626  	go func() {
   627  		select {
   628  		case <-stop:
   629  			return
   630  		case <-time.After(delay):
   631  		}
   632  
   633  		select {
   634  		case results <- block.WithSeal(header):
   635  		default:
   636  			log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header))
   637  		}
   638  	}()
   639  
   640  	return nil
   641  }
   642  
   643  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   644  // that a new block should have based on the previous blocks in the chain and the
   645  // current signer.
   646  func (c *Clique) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   647  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   648  	if err != nil {
   649  		return nil
   650  	}
   651  	return CalcDifficulty(snap, c.signer)
   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 CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
   658  	if snap.inturn(snap.Number+1, signer) {
   659  		return new(big.Int).Set(diffInTurn)
   660  	}
   661  	return new(big.Int).Set(diffNoTurn)
   662  }
   663  
   664  // SealHash returns the hash of a block prior to it being sealed.
   665  func (c *Clique) SealHash(header *types.Header) common.Hash {
   666  	return SealHash(header)
   667  }
   668  
   669  // Close implements consensus.Engine. It's a noop for clique as there are no background threads.
   670  func (c *Clique) Close() error {
   671  	return nil
   672  }
   673  
   674  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   675  // controlling the signer voting.
   676  func (c *Clique) APIs(chain consensus.ChainReader) []rpc.API {
   677  	return []rpc.API{{
   678  		Namespace: "clique",
   679  		Version:   "1.0",
   680  		Service:   &API{chain: chain, clique: c},
   681  		Public:    false,
   682  	}}
   683  }
   684  
   685  // SealHash returns the hash of a block prior to it being sealed.
   686  func SealHash(header *types.Header) (hash common.Hash) {
   687  	hasher := sha3.NewLegacyKeccak256()
   688  	encodeSigHeader(hasher, header)
   689  	hasher.Sum(hash[:0])
   690  	return hash
   691  }
   692  
   693  // CliqueRLP returns the rlp bytes which needs to be signed for the proof-of-authority
   694  // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
   695  // contained at the end of the extra data.
   696  //
   697  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   698  // panics. This is done to avoid accidentally using both forms (signature present
   699  // or not), which could be abused to produce different hashes for the same header.
   700  func CliqueRLP(header *types.Header) []byte {
   701  	b := new(bytes.Buffer)
   702  	encodeSigHeader(b, header)
   703  	return b.Bytes()
   704  }
   705  
   706  func encodeSigHeader(w io.Writer, header *types.Header) {
   707  	err := rlp.Encode(w, []interface{}{
   708  		header.ParentHash,
   709  		header.UncleHash,
   710  		header.Coinbase,
   711  		header.Root,
   712  		header.TxHash,
   713  		header.ReceiptHash,
   714  		header.Bloom,
   715  		header.Difficulty,
   716  		header.Number,
   717  		header.GasLimit,
   718  		header.GasUsed,
   719  		header.Time,
   720  		header.Extra[:len(header.Extra)-65], // Yes, this will panic if extra is too short
   721  		header.MixDigest,
   722  		header.Nonce,
   723  	})
   724  	if err != nil {
   725  		panic("can't encode: " + err.Error())
   726  	}
   727  }