github.com/beyonderyue/gochain@v2.2.26+incompatible/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  	"context"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  	"math/rand"
    27  	"sync"
    28  	"time"
    29  
    30  	"github.com/hashicorp/golang-lru"
    31  	"go.opencensus.io/trace"
    32  
    33  	"github.com/gochain-io/gochain/accounts"
    34  	"github.com/gochain-io/gochain/common"
    35  	"github.com/gochain-io/gochain/common/hexutil"
    36  	"github.com/gochain-io/gochain/consensus"
    37  	"github.com/gochain-io/gochain/core/types"
    38  	"github.com/gochain-io/gochain/crypto"
    39  	"github.com/gochain-io/gochain/crypto/sha3"
    40  	"github.com/gochain-io/gochain/log"
    41  	"github.com/gochain-io/gochain/params"
    42  	"github.com/gochain-io/gochain/rlp"
    43  	"github.com/gochain-io/gochain/rpc"
    44  )
    45  
    46  const (
    47  	checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database
    48  	inmemorySnapshots  = 128  // Number of recent vote snapshots to keep in memory
    49  	inmemorySignatures = 4096 // Number of recent block signatures to keep in memory
    50  
    51  	wiggleTime = 200 * time.Millisecond // Delay step for out-of-turn signers.
    52  )
    53  
    54  // Clique proof-of-authority protocol constants.
    55  var (
    56  	signatureLength = 65
    57  
    58  	extraVanity  = 32                       // Fixed number of extra-data prefix bytes reserved for signer vanity.
    59  	extraPropose = common.AddressLength + 1 // Number of extra-data suffix bytes reserved for a proposal vote.
    60  
    61  	voterElection  byte = 0xff
    62  	signerElection byte = 0x00
    63  
    64  	nonceAuthVote = hexutil.MustDecode("0xffffffffffffffff") // Magic nonce number to vote on adding a new signer
    65  	nonceDropVote = hexutil.MustDecode("0x0000000000000000") // Magic nonce number to vote on removing a signer.
    66  
    67  	uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW.
    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  	// errInvalidVote is returned if a nonce value is something else that the two
    80  	// allowed constants of 0x00..0 or 0xff..f.
    81  	errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f")
    82  
    83  	// errInvalidCheckpointVote is returned if a checkpoint/epoch transition block
    84  	// has a vote nonce set to non-zeroes.
    85  	errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero")
    86  
    87  	// errMissingVanity is returned if a block's extra-data section is shorter than
    88  	// 32 bytes, which is required to store the signer vanity.
    89  	errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
    90  
    91  	// errMissingSignature is returned if a block's signer section doesn't seem
    92  	// to contain a 65 byte secp256k1 signature.
    93  	errMissingSignature = errors.New("signer signature missing")
    94  
    95  	// errMissingSigners is returned if a block's signers section is empty
    96  	errMissingSigners = errors.New("signers list missing")
    97  
    98  	// errMissingVoters is returned if a block's voters section is empty
    99  	errMissingVoters = errors.New("voters list missing")
   100  
   101  	// errInvalidCheckpointSigners is returned if a checkpoint block contains an
   102  	// invalid list of signers
   103  	errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block")
   104  
   105  	// errInvalidCheckpointVoters is returned if a checkpoint block contains an
   106  	// invalid list of voters
   107  	errInvalidCheckpointVoters = errors.New("invalid voter list on checkpoint block")
   108  
   109  	// errInvalidMixDigest is returned if a block's mix digest is non-zero.
   110  	errInvalidMixDigest = errors.New("non-zero mix digest")
   111  
   112  	// errInvalidUncleHash is returned if a block contains an non-empty uncle list.
   113  	errInvalidUncleHash = errors.New("non empty uncle hash")
   114  
   115  	// errInvalidDifficulty is returned if the difficulty of a block is missing or 0,
   116  	// or if the value does not match the turn of the signer.
   117  	errInvalidDifficulty = errors.New("invalid difficulty")
   118  
   119  	// ErrInvalidTimestamp is returned if the timestamp of a block is lower than
   120  	// the previous block's timestamp + the minimum block period.
   121  	ErrInvalidTimestamp = errors.New("invalid timestamp")
   122  
   123  	// errInvalidVotingChain is returned if an authorization list is attempted to
   124  	// be modified via out-of-range or non-contiguous headers.
   125  	errInvalidVotingChain = errors.New("invalid voting chain")
   126  
   127  	// errWaitTransactions is returned if an empty block is attempted to be sealed
   128  	// on an instant chain (0 second period). It's important to refuse these as the
   129  	// block reward is zero, so an empty block just bloats the chain... fast.
   130  	errWaitTransactions = errors.New("waiting for transactions")
   131  
   132  	// ErrIneligibleSigner is returned if a signer is authorized to sign, but not
   133  	// eligible to sign this block. It has either signed too recently, or the chain
   134  	// has just started and it is not yet its turn.
   135  	ErrIneligibleSigner = errors.New("signer is not eligible to sign this block")
   136  )
   137  
   138  // sigHash returns the hash which is used as input for the proof-of-authority
   139  // signing. It is the hash of the entire header apart from the 65 byte signature
   140  // contained at the end of the extra data.
   141  //
   142  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   143  // panics. This is done to avoid accidentally using both forms (signature present
   144  // or not), which could be abused to produce different hashes for the same header.
   145  func sigHash(header *types.Header) (hash common.Hash) {
   146  	hasher := sha3.NewKeccak256SingleSum()
   147  
   148  	rlp.Encode(hasher, []interface{}{
   149  		header.ParentHash,
   150  		header.UncleHash,
   151  		header.Coinbase,
   152  		header.Root,
   153  		header.TxHash,
   154  		header.ReceiptHash,
   155  		header.Bloom,
   156  		header.Difficulty,
   157  		header.Number,
   158  		header.GasLimit,
   159  		header.GasUsed,
   160  		header.Time,
   161  		header.Signers,
   162  		header.Voters,
   163  		header.Extra, // Yes, this will panic if extra is too short
   164  		header.MixDigest,
   165  		header.Nonce,
   166  	})
   167  	hasher.Sum(hash[:0])
   168  	return hash
   169  }
   170  
   171  // ecrecover extracts the Ethereum account address from a signed header.
   172  func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) {
   173  	// If the signature's already cached, return that
   174  	hash := header.Hash()
   175  	if address, known := sigcache.Get(hash); known {
   176  		return address.(common.Address), nil
   177  	}
   178  	// Retrieve the signature from the header
   179  	if len(header.Signer) < signatureLength {
   180  		return common.Address{}, errMissingSignature
   181  	}
   182  	signature := header.Signer
   183  
   184  	// Recover the public key and the Ethereum address
   185  	pubkey, err := crypto.Ecrecover(sigHash(header).Bytes(), signature)
   186  	if err != nil {
   187  		return common.Address{}, err
   188  	}
   189  	h := crypto.Keccak256Hash(pubkey[1:])
   190  	var signer common.Address
   191  	copy(signer[:], h[12:])
   192  
   193  	sigcache.Add(hash, signer)
   194  	return signer, nil
   195  }
   196  
   197  type propose struct {
   198  	Authorize     bool
   199  	VoterElection bool
   200  }
   201  
   202  // Clique is the proof-of-authority consensus engine proposed to support the
   203  // Ethereum testnet following the Ropsten attacks.
   204  type Clique struct {
   205  	config *params.CliqueConfig // Consensus engine configuration parameters
   206  	db     common.Database      // Database to store and retrieve snapshot checkpoints
   207  
   208  	recents    *lru.ARCCache // Snapshots for recent block to speed up reorgs
   209  	signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
   210  
   211  	proposals map[common.Address]propose // Current list of proposals we are pushing
   212  
   213  	signer common.Address     // Address of the signing key
   214  	signFn consensus.SignerFn // Signer function to authorize hashes with
   215  	lock   sync.RWMutex       // Protects the signer fields
   216  }
   217  
   218  // New creates a Clique proof-of-authority consensus engine with the initial
   219  // signers set to the ones provided by the user.
   220  func New(config *params.CliqueConfig, db common.Database) *Clique {
   221  	// Set any missing consensus parameters to their defaults
   222  	conf := *config
   223  	if conf.Epoch == 0 {
   224  		conf.Epoch = params.DefaultCliqueEpoch
   225  	}
   226  	// Allocate the snapshot caches and create the engine
   227  	recents, _ := lru.NewARC(inmemorySnapshots)
   228  	signatures, _ := lru.NewARC(inmemorySignatures)
   229  
   230  	return &Clique{
   231  		config:     &conf,
   232  		db:         db,
   233  		recents:    recents,
   234  		signatures: signatures,
   235  		proposals:  make(map[common.Address]propose),
   236  	}
   237  }
   238  
   239  // Author implements consensus.Engine, returning the address recovered
   240  // from the signature in the header's extra-data section.
   241  func (c *Clique) Author(header *types.Header) (common.Address, error) {
   242  	return ecrecover(header, c.signatures)
   243  }
   244  
   245  // VerifyHeader checks whether a header conforms to the consensus rules.
   246  func (c *Clique) VerifyHeader(ctx context.Context, chain consensus.ChainReader, header *types.Header) error {
   247  	ctx, span := trace.StartSpan(ctx, "Clique.VerifyHeader")
   248  	defer span.End()
   249  	if err := c.verifyHeader(ctx, chain, header, nil); err != nil {
   250  		return err
   251  	}
   252  	if err := c.verifyCascadingFields(ctx, chain, header, nil); err != nil {
   253  		return err
   254  	}
   255  	return c.verifySeal(ctx, chain, header, nil)
   256  }
   257  
   258  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   259  // method returns a quit channel to abort the operations and a results channel to
   260  // retrieve the async verifications (the order is that of the input slice).
   261  func (c *Clique) VerifyHeaders(ctx context.Context, chain consensus.ChainReader, headers []*types.Header) (chan<- struct{}, <-chan error) {
   262  	verify := []verifyFn{c.verifyHeader, c.verifyCascadingFields, c.verifySeal}
   263  	return c.verifyHeaders(ctx, chain, headers, verify)
   264  }
   265  
   266  func (c *Clique) verifyHeaders(ctx context.Context, chain consensus.ChainReader, headers []*types.Header, verify []verifyFn) (chan<- struct{}, <-chan error) {
   267  	abort := make(chan struct{})
   268  	results := make(chan error, len(headers))
   269  
   270  	go func() {
   271  		ctx, span := trace.StartSpan(context.Background(), "Clique.verifyHeaders")
   272  		defer span.End()
   273  		defer close(results)
   274  		for i, header := range headers {
   275  			parents := headers[:i]
   276  			var err error
   277  			for _, fn := range verify {
   278  				err = fn(ctx, chain, header, parents)
   279  				if err != nil {
   280  					break
   281  				}
   282  			}
   283  
   284  			select {
   285  			case <-abort:
   286  				return
   287  			case results <- err:
   288  			}
   289  		}
   290  	}()
   291  	return abort, results
   292  }
   293  
   294  type verifyFn func(ctx context.Context, chain consensus.ChainReader, header *types.Header, parents []*types.Header) error
   295  
   296  // verifyHeader checks whether a header conforms to the consensus rules.The
   297  // caller may optionally pass in a batch of parents (ascending order) to avoid
   298  // looking those up from the database. This is useful for concurrently verifying
   299  // a batch of new headers.
   300  func (c *Clique) verifyHeader(ctx context.Context, chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   301  	ctx, span := trace.StartSpan(ctx, "Clique.verifyHeader")
   302  	defer span.End()
   303  
   304  	if header.Number == nil {
   305  		return errUnknownBlock
   306  	}
   307  	number := header.Number.Uint64()
   308  
   309  	checkpoint := (number % c.config.Epoch) == 0
   310  	if checkpoint && len(header.Extra) > extraVanity {
   311  		return errInvalidVote
   312  	}
   313  	// Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints
   314  	if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) {
   315  		return errInvalidVote
   316  	}
   317  	if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) {
   318  		return errInvalidCheckpointVote
   319  	}
   320  	// Check that the extra-data contains the vanity
   321  	//if len(header.Extra) < extraVanity {
   322  	//	return errMissingVanity
   323  	//}
   324  
   325  	// Check if header contains signers and voters
   326  	if checkpoint {
   327  		if len(header.Signers) < 1 {
   328  			return errMissingSigners
   329  		}
   330  		if len(header.Voters) < 1 {
   331  			return errMissingVoters
   332  		}
   333  	}
   334  	// Check if block was signed
   335  	if len(header.Signer) < signatureLength {
   336  		return errMissingSignature
   337  	}
   338  	// Ensure that the mix digest is zero as we don't have fork protection currently
   339  	if header.MixDigest != (common.Hash{}) {
   340  		return errInvalidMixDigest
   341  	}
   342  	// Ensure that the block doesn't contain any uncles which are meaningless in PoA
   343  	if header.UncleHash != uncleHash {
   344  		return errInvalidUncleHash
   345  	}
   346  	if number > 0 {
   347  		// Ensure that the block's difficulty is meaningful (may not be correct at this point)
   348  		if header.Difficulty == nil || header.Difficulty.Uint64() == 0 {
   349  			return errInvalidDifficulty
   350  		}
   351  	}
   352  	// If all checks passed, validate any special fields for hard forks
   353  	if err := verifyForkHashes(chain.Config(), header); err != nil {
   354  		return err
   355  	}
   356  	return nil
   357  }
   358  
   359  // verifyForkHashes verifies that blocks conforming to network hard-forks do have
   360  // the correct hashes, to avoid clients going off on different chains. This is an
   361  // optional feature.
   362  func verifyForkHashes(config *params.ChainConfig, header *types.Header) error {
   363  	// If the homestead reprice hash is set, validate it
   364  	if config.EIP150Block != nil && config.EIP150Block.Cmp(header.Number) == 0 {
   365  		if config.EIP150Hash != (common.Hash{}) && config.EIP150Hash != header.Hash() {
   366  			return fmt.Errorf("homestead gas reprice fork: have 0x%x, want 0x%x", header.Hash(), config.EIP150Hash)
   367  		}
   368  	}
   369  	// All ok, return
   370  	return nil
   371  }
   372  
   373  // verifyCascadingFields verifies all the header fields that are not standalone,
   374  // rather depend on a batch of previous headers. The caller may optionally pass
   375  // in a batch of parents (ascending order) to avoid looking those up from the
   376  // database. This is useful for concurrently verifying a batch of new headers.
   377  func (c *Clique) verifyCascadingFields(ctx context.Context, chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   378  	ctx, span := trace.StartSpan(ctx, "Clique.verifyCascadingFields")
   379  	defer span.End()
   380  
   381  	// Don't waste time checking blocks from the future
   382  	if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
   383  		return consensus.ErrFutureBlock
   384  	}
   385  	// The genesis block is the always valid dead-end
   386  	number := header.Number.Uint64()
   387  	if number == 0 {
   388  		return nil
   389  	}
   390  	// Ensure that the block's timestamp isn't too close to it's parent
   391  	var parent *types.Header
   392  	if len(parents) > 0 {
   393  		parent = parents[len(parents)-1]
   394  	} else {
   395  		parent = chain.GetHeader(header.ParentHash, number-1)
   396  	}
   397  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   398  		return consensus.ErrUnknownAncestor
   399  	}
   400  	if parent.Time.Uint64()+c.config.Period > header.Time.Uint64() {
   401  		return ErrInvalidTimestamp
   402  	}
   403  	// Retrieve the snapshot needed to verify this header and cache it
   404  	snap, err := c.snapshot(ctx, chain, number-1, header.ParentHash, parents)
   405  	if err != nil {
   406  		return err
   407  	}
   408  	// If the block is a checkpoint block, verify the signer list
   409  	if number%c.config.Epoch == 0 {
   410  		for i, signer := range snap.signers() {
   411  			if signer != header.Signers[i] {
   412  				return errInvalidCheckpointSigners
   413  			}
   414  		}
   415  		for i, voter := range snap.voters() {
   416  			if voter != header.Voters[i] {
   417  				return errInvalidCheckpointVoters
   418  			}
   419  		}
   420  	}
   421  	return nil
   422  }
   423  
   424  // snapshot retrieves the authorization snapshot at a given point in time.
   425  func (c *Clique) snapshot(ctx context.Context, chain consensus.ChainReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   426  	ctx, span := trace.StartSpan(ctx, "Clique.snapshot")
   427  	defer span.End()
   428  
   429  	// Search for a snapshot in memory or on disk for checkpoints
   430  	var (
   431  		headers []*types.Header
   432  		snap    *Snapshot
   433  	)
   434  	for snap == nil {
   435  		// If an in-memory snapshot was found, use that
   436  		if s, ok := c.recents.Get(hash); ok {
   437  			snap = s.(*Snapshot)
   438  			break
   439  		}
   440  		// If an on-disk checkpoint snapshot can be found, use that
   441  		if number%checkpointInterval == 0 {
   442  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil {
   443  				log.Trace("Loaded voting snapshot form disk", "number", number, "hash", hash)
   444  				snap = s
   445  				break
   446  			}
   447  		}
   448  		// If we're at block zero, make a snapshot
   449  		if number == 0 {
   450  			genesis := chain.GetHeaderByNumber(0)
   451  			if genesis == nil {
   452  				return nil, errors.New("no genesis block found")
   453  			}
   454  			if err := c.VerifyHeader(ctx, chain, genesis); err != nil {
   455  				return nil, err
   456  			}
   457  			snap = newGenesisSnapshot(c.config, c.signatures, 0, genesis.Hash(), genesis.Signers, genesis.Voters)
   458  			if err := snap.store(c.db); err != nil {
   459  				return nil, err
   460  			}
   461  			log.Trace("Stored genesis voting snapshot to disk")
   462  			break
   463  		}
   464  		// No snapshot for this header, gather the header and move backward
   465  		var header *types.Header
   466  		if len(parents) > 0 {
   467  			// If we have explicit parents, pick from there (enforced)
   468  			header = parents[len(parents)-1]
   469  			if header.Hash() != hash || header.Number.Uint64() != number {
   470  				return nil, consensus.ErrUnknownAncestor
   471  			}
   472  			parents = parents[:len(parents)-1]
   473  		} else {
   474  			// No explicit parents (or no more left), reach out to the database
   475  			header = chain.GetHeader(hash, number)
   476  			if header == nil {
   477  				return nil, consensus.ErrUnknownAncestor
   478  			}
   479  		}
   480  		headers = append(headers, header)
   481  		number, hash = number-1, header.ParentHash
   482  	}
   483  	// Previous snapshot found, apply any pending headers on top of it
   484  	for i := 0; i < len(headers)/2; i++ {
   485  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   486  	}
   487  	snap, err := snap.apply(ctx, headers)
   488  	if err != nil {
   489  		return nil, err
   490  	}
   491  	c.recents.Add(snap.Hash, snap)
   492  
   493  	// If we've generated a new checkpoint snapshot, save to disk
   494  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   495  		if err = snap.store(c.db); err != nil {
   496  			return nil, err
   497  		}
   498  		log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   499  	}
   500  	return snap, err
   501  }
   502  
   503  // verifySeal checks whether the signature contained in the header satisfies the
   504  // consensus protocol requirements. The method accepts an optional list of parent
   505  // headers that aren't yet part of the local blockchain to generate the snapshots
   506  // from.
   507  func (c *Clique) verifySeal(ctx context.Context, chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   508  	ctx, span := trace.StartSpan(ctx, "Clique.verifySeal")
   509  	defer span.End()
   510  
   511  	// The genesis block is the always valid dead-end
   512  	number := header.Number.Uint64()
   513  	if number == 0 {
   514  		return nil
   515  	}
   516  	// Retrieve the snapshot needed to verify this header and cache it
   517  	snap, err := c.snapshot(ctx, chain, number-1, header.ParentHash, parents)
   518  	if err != nil {
   519  		return err
   520  	}
   521  	// Resolve the authorization key and check against signers
   522  	signer, err := ecrecover(header, c.signatures)
   523  	if err != nil {
   524  		return err
   525  	}
   526  	lastBlockSigned, authorized := snap.Signers[signer]
   527  	if !authorized {
   528  		return fmt.Errorf("%s not authorized to sign", signer.Hex())
   529  	}
   530  
   531  	if lastBlockSigned > 0 {
   532  		if next := snap.nextSignableBlockNumber(lastBlockSigned); number < next {
   533  			return fmt.Errorf("%s not authorized to sign %d: signed recently %d, next eligible signature %d", signer.Hex(), number, lastBlockSigned, next)
   534  		}
   535  	}
   536  
   537  	if header.Difficulty.Uint64() != CalcDifficulty(snap.Signers, signer) {
   538  		return errInvalidDifficulty
   539  	}
   540  
   541  	return nil
   542  }
   543  
   544  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   545  // header for running the transactions on top.
   546  func (c *Clique) Prepare(ctx context.Context, chain consensus.ChainReader, header *types.Header) error {
   547  	ctx, span := trace.StartSpan(ctx, "Clique.Prepare")
   548  	defer span.End()
   549  
   550  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   551  	header.Nonce = types.BlockNonce{}
   552  
   553  	number := header.Number.Uint64()
   554  	// Assemble the voting snapshot to check which votes make sense
   555  	snap, err := c.snapshot(ctx, chain, number-1, header.ParentHash, nil)
   556  	if err != nil {
   557  		return err
   558  	}
   559  	if c.signer != (common.Address{}) {
   560  		// Check that we can sign.
   561  		if _, ok := snap.Signers[c.signer]; !ok {
   562  			return fmt.Errorf("not authorized to sign: %s", c.signer.Hex())
   563  		}
   564  	}
   565  	// Calculate and validate the difficulty.
   566  	diff := CalcDifficulty(snap.Signers, c.signer)
   567  	if c.signer != (common.Address{}) && diff == 0 {
   568  		return ErrIneligibleSigner
   569  	}
   570  	header.Difficulty = new(big.Int).SetUint64(diff)
   571  
   572  	header.Extra = ExtraEnsureVanity(header.Extra)
   573  	//if not checkpoint
   574  	if number%c.config.Epoch != 0 {
   575  		c.lock.RLock()
   576  
   577  		// Gather all the proposals that make sense voting on
   578  		addresses := make([]common.Address, 0, len(c.proposals))
   579  		for address, propose := range c.proposals {
   580  			if snap.validVote(address, propose.Authorize, propose.VoterElection) {
   581  				addresses = append(addresses, address)
   582  			}
   583  		}
   584  		// If there's pending proposals, cast a vote on them
   585  		if len(addresses) > 0 {
   586  			candidate := addresses[rand.Intn(len(addresses))]
   587  			propose := c.proposals[candidate]
   588  			header.Extra = ExtraAppendVote(header.Extra, candidate, propose.VoterElection)
   589  			if propose.Authorize {
   590  				copy(header.Nonce[:], nonceAuthVote)
   591  			} else {
   592  				copy(header.Nonce[:], nonceDropVote)
   593  			}
   594  			log.Info("propose", "Candidate", candidate, "vote", propose.Authorize, "voterElection", propose.VoterElection)
   595  		}
   596  		c.lock.RUnlock()
   597  	}
   598  
   599  	if number%c.config.Epoch == 0 {
   600  		header.Signers = snap.signers()
   601  		header.Voters = snap.voters()
   602  	}
   603  
   604  	// Mix digest is reserved for now, set to empty
   605  	header.MixDigest = common.Hash{}
   606  
   607  	// Ensure the timestamp has the correct delay
   608  	parent := chain.GetHeader(header.ParentHash, number-1)
   609  	if parent == nil {
   610  		return consensus.ErrUnknownAncestor
   611  	}
   612  	header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period))
   613  	if header.Time.Int64() < time.Now().Unix() {
   614  		header.Time = big.NewInt(time.Now().Unix())
   615  	}
   616  	if c.config.Period == 0 {
   617  		return nil
   618  	}
   619  	return nil
   620  }
   621  
   622  func (c *Clique) Authorize(signer common.Address, signFn consensus.SignerFn) {
   623  	c.lock.Lock()
   624  	defer c.lock.Unlock()
   625  
   626  	c.signer = signer
   627  	c.signFn = signFn
   628  }
   629  
   630  // Seal implements consensus.Engine, attempting to create a sealed block using
   631  // the local signing credentials.
   632  func (c *Clique) Seal(ctx context.Context, chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, *time.Time, error) {
   633  	ctx, span := trace.StartSpan(ctx, "Clique.Seal")
   634  	defer span.End()
   635  
   636  	header := block.Header()
   637  
   638  	// Sealing the genesis block is not supported
   639  	number := header.Number.Uint64()
   640  	if number == 0 {
   641  		return nil, nil, errUnknownBlock
   642  	}
   643  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   644  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   645  		return nil, nil, errWaitTransactions
   646  	}
   647  	// Don't hold the signer fields for the entire sealing procedure
   648  	c.lock.RLock()
   649  	signer, signFn := c.signer, c.signFn
   650  	c.lock.RUnlock()
   651  
   652  	// Bail out if we're unauthorized to sign a block
   653  	snap, err := c.snapshot(ctx, chain, number-1, header.ParentHash, nil)
   654  	if err != nil {
   655  		return nil, nil, err
   656  	}
   657  	lastBlockSigned, authorized := snap.Signers[signer]
   658  	if !authorized {
   659  		return nil, nil, fmt.Errorf("%s not authorized to sign", signer.Hex())
   660  	}
   661  
   662  	if lastBlockSigned > 0 {
   663  		if next := snap.nextSignableBlockNumber(lastBlockSigned); number < next {
   664  			log.Info("Signed recently, must wait for others", "number", number, "signed", lastBlockSigned, "next", next)
   665  			<-stop
   666  			return nil, nil, nil
   667  		}
   668  	}
   669  
   670  	// Sign all the things!
   671  	sighash, err := signFn(accounts.Account{Address: signer}, sigHash(header).Bytes())
   672  	if err != nil {
   673  		return nil, nil, err
   674  	}
   675  	header.Signer = sighash
   676  	wSeal := block.WithSeal(header)
   677  
   678  	// Maybe delay.
   679  	var (
   680  		n    = uint64(len(snap.Signers))
   681  		diff = header.Difficulty.Uint64()
   682  	)
   683  	// Wait until header.Time plus a delay based on difficulty.
   684  	// Since diff is in the range [n/2+1,n], delay is [wiggleTime,n/2*wiggleTime].
   685  	delay := time.Duration(n-diff) * wiggleTime
   686  	until := time.Unix(header.Time.Int64(), 0).Add(delay)
   687  
   688  	return wSeal, &until, nil
   689  }
   690  
   691  func (c *Clique) SealHash(header *types.Header) common.Hash {
   692  	return sigHash(header)
   693  }
   694  
   695  // CalcDifficulty returns the difficulty for signer, given all signers and their most recently signed block numbers,
   696  // with 0 meaning 'has not signed'. With n signers, it will always return values from n/2+1 to n, inclusive, or 0.
   697  //
   698  // Difficulty for ineligible signers (too recent) is always 0. For eligible signers, difficulty is defined as 1 plus the
   699  // number of lower priority signers, with more recent signers have lower priority. If multiple signers have not yet
   700  // signed (0), then addresses which lexicographically sort later have lower priority.
   701  func CalcDifficulty(lastSigned map[common.Address]uint64, signer common.Address) uint64 {
   702  	last := lastSigned[signer]
   703  	difficulty := 1
   704  	// Note that signer's entry is implicitly skipped by the condition in both loops, so it never counts itself.
   705  	if last > 0 {
   706  		for _, n := range lastSigned {
   707  			if n > last {
   708  				difficulty++
   709  			}
   710  		}
   711  	} else {
   712  		// Haven't signed yet. If there are others, fall back to address sort.
   713  		for addr, n := range lastSigned {
   714  			if n > 0 || bytes.Compare(addr[:], signer[:]) > 0 {
   715  				difficulty++
   716  			}
   717  		}
   718  	}
   719  	if difficulty <= len(lastSigned)/2 {
   720  		// [1,n/2]: Too recent to sign again.
   721  		return 0
   722  	}
   723  	// [n/2+1,n]
   724  	return uint64(difficulty)
   725  }
   726  
   727  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   728  // controlling the signer voting.
   729  func (c *Clique) APIs(chain consensus.ChainReader) []rpc.API {
   730  	return []rpc.API{{
   731  		Namespace: "clique",
   732  		Version:   "1.0",
   733  		Service:   &API{chain: chain, clique: c},
   734  		Public:    false,
   735  	}}
   736  }
   737  
   738  // ExtraEnsureVanity returns a slice of length 32, trimming extra or filling with 0s as necessary.
   739  func ExtraEnsureVanity(extra []byte) []byte {
   740  	if len(extra) < extraVanity {
   741  		return append(extra, make([]byte, extraVanity-len(extra))...)
   742  	}
   743  	return extra[:extraVanity]
   744  }
   745  
   746  // ExtraVanity returns a slice of the vanity portion of extra (up to 32). It may still contain trailing 0s.
   747  func ExtraVanity(extra []byte) []byte {
   748  	if len(extra) < extraVanity {
   749  		return extra
   750  	}
   751  	return extra[:extraVanity]
   752  }
   753  
   754  // ExtraAppendVote appends a vote to extra data as 20 bytes of address and a single byte for voter or signer election.
   755  func ExtraAppendVote(extra []byte, candidate common.Address, voter bool) []byte {
   756  	extra = append(extra, candidate[:]...)
   757  	election := signerElection
   758  	if voter {
   759  		election = voterElection
   760  	}
   761  	return append(extra, election)
   762  }
   763  
   764  // ExtraHasVote returns true if extra contains a proposal vote.
   765  func ExtraHasVote(extra []byte) bool {
   766  	return len(extra) == extraVanity+extraPropose
   767  }
   768  
   769  // ExtraCandidate returns the candidate address of the proposal vote, or the zero value if one is not present.
   770  func ExtraCandidate(extra []byte) common.Address {
   771  	if len(extra) < extraVanity+common.AddressLength {
   772  		return common.Address{}
   773  	}
   774  	return common.BytesToAddress(extra[extraVanity : extraVanity+common.AddressLength])
   775  }
   776  
   777  // IsVoterElection returns true if extra votes on a voter election, or false if it votes on a signer election or does
   778  // not contain a vote.
   779  func ExtraIsVoterElection(extra []byte) bool {
   780  	if len(extra) < extraVanity+extraPropose {
   781  		return false
   782  	}
   783  	switch extra[extraVanity+common.AddressLength] {
   784  	case voterElection:
   785  		return true
   786  	case signerElection:
   787  		return false
   788  	}
   789  	return false
   790  }