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