github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/consensus/clique/clique.go (about)

     1  // Copyright 2017 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum 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/SmartMeshFoundation/Spectrum/accounts"
    29  	"github.com/SmartMeshFoundation/Spectrum/common"
    30  	"github.com/SmartMeshFoundation/Spectrum/common/hexutil"
    31  	"github.com/SmartMeshFoundation/Spectrum/consensus"
    32  	"github.com/SmartMeshFoundation/Spectrum/consensus/misc"
    33  	"github.com/SmartMeshFoundation/Spectrum/core/state"
    34  	"github.com/SmartMeshFoundation/Spectrum/core/types"
    35  	"github.com/SmartMeshFoundation/Spectrum/crypto"
    36  	"github.com/SmartMeshFoundation/Spectrum/crypto/sha3"
    37  	"github.com/SmartMeshFoundation/Spectrum/ethdb"
    38  	"github.com/SmartMeshFoundation/Spectrum/log"
    39  	"github.com/SmartMeshFoundation/Spectrum/params"
    40  	"github.com/SmartMeshFoundation/Spectrum/rlp"
    41  	"github.com/SmartMeshFoundation/Spectrum/rpc"
    42  	"github.com/hashicorp/golang-lru"
    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  	debug("New clique :", config.Period, config.Epoch)
   216  	conf := *config
   217  	if conf.Epoch == 0 {
   218  		conf.Epoch = epochLength
   219  	}
   220  	// Allocate the snapshot caches and create the engine
   221  	recents, _ := lru.NewARC(inmemorySnapshots)
   222  	signatures, _ := lru.NewARC(inmemorySignatures)
   223  
   224  	return &Clique{
   225  		config:     &conf,
   226  		db:         db,
   227  		recents:    recents,
   228  		signatures: signatures,
   229  		proposals:  make(map[common.Address]bool),
   230  	}
   231  }
   232  
   233  // Author implements consensus.Engine, returning the Ethereum address recovered
   234  // from the signature in the header's extra-data section.
   235  func (c *Clique) Author(header *types.Header) (common.Address, error) {
   236  	return ecrecover(header, c.signatures)
   237  }
   238  
   239  // VerifyHeader checks whether a header conforms to the consensus rules.
   240  func (c *Clique) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
   241  	return c.verifyHeader(chain, header, nil)
   242  }
   243  
   244  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   245  // method returns a quit channel to abort the operations and a results channel to
   246  // retrieve the async verifications (the order is that of the input slice).
   247  func (c *Clique) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   248  	abort := make(chan struct{})
   249  	results := make(chan error, len(headers))
   250  
   251  	go func() {
   252  		for i, header := range headers {
   253  			err := c.verifyHeader(chain, header, headers[:i])
   254  
   255  			select {
   256  			case <-abort:
   257  				return
   258  			case results <- err:
   259  			}
   260  		}
   261  	}()
   262  	return abort, results
   263  }
   264  
   265  // verifyHeader checks whether a header conforms to the consensus rules.The
   266  // caller may optionally pass in a batch of parents (ascending order) to avoid
   267  // looking those up from the database. This is useful for concurrently verifying
   268  // a batch of new headers.
   269  func (c *Clique) verifyHeader(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   270  	if header.Number == nil {
   271  		return errUnknownBlock
   272  	}
   273  	number := header.Number.Uint64()
   274  
   275  	// Don't waste time checking blocks from the future
   276  	if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
   277  		return consensus.ErrFutureBlock
   278  	}
   279  	// Checkpoint blocks need to enforce zero beneficiary
   280  	checkpoint := (number % c.config.Epoch) == 0
   281  	if checkpoint && header.Coinbase != (common.Address{}) {
   282  		return errInvalidCheckpointBeneficiary
   283  	}
   284  	// Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints
   285  	if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) {
   286  		return errInvalidVote
   287  	}
   288  	if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) {
   289  		return errInvalidCheckpointVote
   290  	}
   291  	// Check that the extra-data contains both the vanity and signature
   292  	if len(header.Extra) < extraVanity {
   293  		return errMissingVanity
   294  	}
   295  	if len(header.Extra) < extraVanity+extraSeal {
   296  		return errMissingSignature
   297  	}
   298  	// Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
   299  	signersBytes := len(header.Extra) - extraVanity - extraSeal
   300  	if !checkpoint && signersBytes != 0 {
   301  		return errExtraSigners
   302  	}
   303  	if checkpoint && signersBytes%common.AddressLength != 0 {
   304  		return errInvalidCheckpointSigners
   305  	}
   306  	// Ensure that the mix digest is zero as we don't have fork protection currently
   307  	if header.MixDigest != (common.Hash{}) {
   308  		return errInvalidMixDigest
   309  	}
   310  	// Ensure that the block doesn't contain any uncles which are meaningless in PoA
   311  	if header.UncleHash != uncleHash {
   312  		return errInvalidUncleHash
   313  	}
   314  	// Ensure that the block's difficulty is meaningful (may not be correct at this point)
   315  	if number > 0 {
   316  		if header.Difficulty == nil || (header.Difficulty.Cmp(diffInTurn) != 0 && header.Difficulty.Cmp(diffNoTurn) != 0) {
   317  			return errInvalidDifficulty
   318  		}
   319  	}
   320  	// If all checks passed, validate any special fields for hard forks
   321  	if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
   322  		return err
   323  	}
   324  	// All basic checks passed, verify cascading fields
   325  	return c.verifyCascadingFields(chain, header, parents)
   326  }
   327  
   328  // verifyCascadingFields verifies all the header fields that are not standalone,
   329  // rather depend on a batch of previous headers. The caller may optionally pass
   330  // in a batch of parents (ascending order) to avoid looking those up from the
   331  // database. This is useful for concurrently verifying a batch of new headers.
   332  func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   333  	// The genesis block is the always valid dead-end
   334  	number := header.Number.Uint64()
   335  	if number == 0 {
   336  		return nil
   337  	}
   338  	// Ensure that the block's timestamp isn't too close to it's parent
   339  	var parent *types.Header
   340  	if len(parents) > 0 {
   341  		parent = parents[len(parents)-1]
   342  	} else {
   343  		parent = chain.GetHeader(header.ParentHash, number-1)
   344  	}
   345  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   346  		return consensus.ErrUnknownAncestor
   347  	}
   348  	if parent.Time.Uint64()+c.config.Period > header.Time.Uint64() {
   349  		return ErrInvalidTimestamp
   350  	}
   351  	// Retrieve the snapshot needed to verify this header and cache it
   352  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   353  	if err != nil {
   354  		return err
   355  	}
   356  	// If the block is a checkpoint block, verify the signer list
   357  	if number%c.config.Epoch == 0 {
   358  		signers := make([]byte, len(snap.Signers)*common.AddressLength)
   359  		for i, signer := range snap.signers() {
   360  			copy(signers[i*common.AddressLength:], signer[:])
   361  		}
   362  		extraSuffix := len(header.Extra) - extraSeal
   363  		if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) {
   364  			return errInvalidCheckpointSigners
   365  		}
   366  	}
   367  	// All basic checks passed, verify the seal and return
   368  	return c.verifySeal(chain, header, parents)
   369  }
   370  
   371  // snapshot retrieves the authorization snapshot at a given point in time.
   372  func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   373  	// Search for a snapshot in memory or on disk for checkpoints
   374  	var (
   375  		headers []*types.Header
   376  		snap    *Snapshot
   377  	)
   378  	for snap == nil {
   379  		// If an in-memory snapshot was found, use that
   380  		if s, ok := c.recents.Get(hash); ok {
   381  			snap = s.(*Snapshot)
   382  			break
   383  		}
   384  		// If an on-disk checkpoint snapshot can be found, use that
   385  		if number%checkpointInterval == 0 {
   386  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil {
   387  				log.Trace("Loaded voting snapshot form disk", "number", number, "hash", hash)
   388  				snap = s
   389  				break
   390  			}
   391  		}
   392  		// If we're at block zero, make a snapshot
   393  		if number == 0 {
   394  			genesis := chain.GetHeaderByNumber(0)
   395  			if err := c.VerifyHeader(chain, genesis, false); err != nil {
   396  				return nil, err
   397  			}
   398  			signers := make([]common.Address, (len(genesis.Extra)-extraVanity-extraSeal)/common.AddressLength)
   399  			for i := 0; i < len(signers); i++ {
   400  				copy(signers[i][:], genesis.Extra[extraVanity+i*common.AddressLength:])
   401  			}
   402  			snap = newSnapshot(c.config, c.signatures, 0, genesis.Hash(), signers)
   403  			if err := snap.store(c.db); err != nil {
   404  				return nil, err
   405  			}
   406  			log.Trace("Stored genesis voting snapshot to disk")
   407  			break
   408  		}
   409  		// No snapshot for this header, gather the header and move backward
   410  		var header *types.Header
   411  		if len(parents) > 0 {
   412  			// If we have explicit parents, pick from there (enforced)
   413  			header = parents[len(parents)-1]
   414  			if header.Hash() != hash || header.Number.Uint64() != number {
   415  				return nil, consensus.ErrUnknownAncestor
   416  			}
   417  			parents = parents[:len(parents)-1]
   418  		} else {
   419  			// No explicit parents (or no more left), reach out to the database
   420  			header = chain.GetHeader(hash, number)
   421  			if header == nil {
   422  				return nil, consensus.ErrUnknownAncestor
   423  			}
   424  		}
   425  		headers = append(headers, header)
   426  		number, hash = number-1, header.ParentHash
   427  	}
   428  	// Previous snapshot found, apply any pending headers on top of it
   429  	for i := 0; i < len(headers)/2; i++ {
   430  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   431  	}
   432  	snap, err := snap.apply(headers)
   433  	if err != nil {
   434  		return nil, err
   435  	}
   436  	c.recents.Add(snap.Hash, snap)
   437  
   438  	// If we've generated a new checkpoint snapshot, save to disk
   439  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   440  		if err = snap.store(c.db); err != nil {
   441  			return nil, err
   442  		}
   443  		log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   444  	}
   445  	return snap, err
   446  }
   447  
   448  // VerifyUncles implements consensus.Engine, always returning an error for any
   449  // uncles as this consensus mechanism doesn't permit uncles.
   450  func (c *Clique) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   451  	if len(block.Uncles()) > 0 {
   452  		return errors.New("uncles not allowed")
   453  	}
   454  	return nil
   455  }
   456  
   457  // VerifySeal implements consensus.Engine, checking whether the signature contained
   458  // in the header satisfies the consensus protocol requirements.
   459  func (c *Clique) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   460  	return c.verifySeal(chain, header, nil)
   461  }
   462  
   463  // verifySeal checks whether the signature contained in the header satisfies the
   464  // consensus protocol requirements. The method accepts an optional list of parent
   465  // headers that aren't yet part of the local blockchain to generate the snapshots
   466  // from.
   467  func (c *Clique) verifySeal(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   468  	// Verifying the genesis block is not supported
   469  	number := header.Number.Uint64()
   470  	if number == 0 {
   471  		return errUnknownBlock
   472  	}
   473  	// Retrieve the snapshot needed to verify this header and cache it
   474  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   475  	if err != nil {
   476  		return err
   477  	}
   478  
   479  	// Resolve the authorization key and check against signers
   480  	signer, err := ecrecover(header, c.signatures)
   481  	if err != nil {
   482  		return err
   483  	}
   484  	if _, ok := snap.Signers[signer]; !ok {
   485  		return errUnauthorized
   486  	}
   487  	for seen, recent := range snap.Recents {
   488  		if recent == signer {
   489  			// Signer is among recents, only fail if the current block doesn't shift it out
   490  			if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit {
   491  				return errUnauthorized
   492  			}
   493  		}
   494  	}
   495  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   496  	inturn := snap.inturn(header.Number.Uint64(), signer)
   497  	if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
   498  		return errInvalidDifficulty
   499  	}
   500  	if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
   501  		return errInvalidDifficulty
   502  	}
   503  	return nil
   504  }
   505  
   506  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   507  // header for running the transactions on top.
   508  func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) error {
   509  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   510  	header.Coinbase = common.Address{}
   511  	header.Nonce = types.BlockNonce{}
   512  
   513  	number := header.Number.Uint64()
   514  	// Assemble the voting snapshot to check which votes make sense
   515  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   516  	if err != nil {
   517  		return err
   518  	}
   519  	if number%c.config.Epoch != 0 {
   520  		c.lock.RLock()
   521  
   522  		// Gather all the proposals that make sense voting on
   523  		addresses := make([]common.Address, 0, len(c.proposals))
   524  		for address, authorize := range c.proposals {
   525  			if snap.validVote(address, authorize) {
   526  				addresses = append(addresses, address)
   527  			}
   528  		}
   529  		// If there's pending proposals, cast a vote on them
   530  		if len(addresses) > 0 {
   531  			header.Coinbase = addresses[rand.Intn(len(addresses))]
   532  			if c.proposals[header.Coinbase] {
   533  				copy(header.Nonce[:], nonceAuthVote)
   534  			} else {
   535  				copy(header.Nonce[:], nonceDropVote)
   536  			}
   537  		}
   538  		c.lock.RUnlock()
   539  	}
   540  	// Set the correct difficulty
   541  	header.Difficulty = CalcDifficulty(snap, c.signer)
   542  
   543  	// Ensure the extra data has all it's components
   544  	if len(header.Extra) < extraVanity {
   545  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   546  	}
   547  	header.Extra = header.Extra[:extraVanity]
   548  
   549  	if number%c.config.Epoch == 0 {
   550  		for _, signer := range snap.signers() {
   551  			header.Extra = append(header.Extra, signer[:]...)
   552  		}
   553  	}
   554  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   555  
   556  	// Mix digest is reserved for now, set to empty
   557  	header.MixDigest = common.Hash{}
   558  
   559  	// Ensure the timestamp has the correct delay
   560  	parent := chain.GetHeader(header.ParentHash, number-1)
   561  	if parent == nil {
   562  		return consensus.ErrUnknownAncestor
   563  	}
   564  	header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period))
   565  	if header.Time.Int64() < time.Now().Unix() {
   566  		header.Time = big.NewInt(time.Now().Unix())
   567  	}
   568  	return nil
   569  }
   570  
   571  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   572  // rewards given, and returns the final block.
   573  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) {
   574  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   575  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   576  	header.UncleHash = types.CalcUncleHash(nil)
   577  
   578  	// Assemble and return the final block for sealing
   579  	return types.NewBlock(header, txs, nil, receipts), nil
   580  }
   581  
   582  // Authorize injects a private key into the consensus engine to mint new blocks
   583  // with.
   584  func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
   585  	c.lock.Lock()
   586  	defer c.lock.Unlock()
   587  
   588  	c.signer = signer
   589  	c.signFn = signFn
   590  }
   591  
   592  // Seal implements consensus.Engine, attempting to create a sealed block using
   593  // the local signing credentials.
   594  func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
   595  	header := block.Header()
   596  	debug("seal 1", header)
   597  	// Sealing the genesis block is not supported
   598  	number := header.Number.Uint64()
   599  	if number == 0 {
   600  		return nil, errUnknownBlock
   601  	}
   602  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   603  	debug("seal 2", c.config.Period, len(block.Transactions()))
   604  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   605  		return nil, errWaitTransactions
   606  	}
   607  	// Don't hold the signer fields for the entire sealing procedure
   608  	c.lock.RLock()
   609  	signer, signFn := c.signer, c.signFn
   610  	c.lock.RUnlock()
   611  
   612  	// Bail out if we're unauthorized to sign a block
   613  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   614  	debug("seal 3", err)
   615  	if err != nil {
   616  		return nil, err
   617  	}
   618  	if _, authorized := snap.Signers[signer]; !authorized {
   619  		return nil, errUnauthorized
   620  	}
   621  	// If we're amongst the recent signers, wait for the next block
   622  	for seen, recent := range snap.Recents {
   623  		if recent == signer {
   624  			// Signer is among recents, only wait if the current block doesn't shift it out
   625  			if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
   626  				log.Info("Signed recently, must wait for others")
   627  				<-stop
   628  				return nil, nil
   629  			}
   630  		}
   631  	}
   632  	// Sweet, the protocol permits us to sign the block, wait for our time
   633  	delay := time.Unix(header.Time.Int64(), 0).Sub(time.Now()) // nolint: gosimple
   634  	debug("seal 4", delay)
   635  	if header.Difficulty.Cmp(diffNoTurn) == 0 {
   636  		// It's not our turn explicitly to sign, delay it a bit
   637  		wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime
   638  		delay += time.Duration(rand.Int63n(int64(wiggle)))
   639  
   640  		log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
   641  		debug("seal 5 out-of-turn", delay)
   642  	}
   643  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   644  
   645  	select {
   646  	case <-stop:
   647  		return nil, nil
   648  	case <-time.After(delay):
   649  	}
   650  	// Sign all the things!
   651  	sighash, err := signFn(accounts.Account{Address: signer}, sigHash(header).Bytes())
   652  	debug("seal 6", sighash, err)
   653  	if err != nil {
   654  		return nil, err
   655  	}
   656  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   657  	debug("seal 7")
   658  	return block.WithSeal(header), nil
   659  }
   660  
   661  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   662  // that a new block should have based on the previous blocks in the chain and the
   663  // current signer.
   664  func (c *Clique) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   665  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   666  	if err != nil {
   667  		return nil
   668  	}
   669  	return CalcDifficulty(snap, c.signer)
   670  }
   671  
   672  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   673  // that a new block should have based on the previous blocks in the chain and the
   674  // current signer.
   675  func CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
   676  	if snap.inturn(snap.Number+1, signer) {
   677  		return new(big.Int).Set(diffInTurn)
   678  	}
   679  	return new(big.Int).Set(diffNoTurn)
   680  }
   681  
   682  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   683  // controlling the signer voting.
   684  func (c *Clique) APIs(chain consensus.ChainReader) []rpc.API {
   685  	return []rpc.API{{
   686  		Namespace: "clique",
   687  		Version:   "1.0",
   688  		Service:   &API{chain: chain, clique: c},
   689  		Public:    false,
   690  	}}
   691  }
   692  
   693  func debug(msg ...interface{}) {
   694  	//msg = append([]interface{}{"<< liangc debug >> :"},msg...)
   695  	//fmt.Println(msg ...)
   696  }