github.com/Elemental-core/elementalcore@v0.0.0-20191206075037-63891242267a/consensus/clique/clique.go (about)

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