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