github.com/core-coin/go-core/v2@v2.1.9/consensus/clique/clique.go (about)

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