github.com/quinndk/ethereum_read@v0.0.0-20181211143958-29c55eec3237/go-ethereum-master_read/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/ethereum/go-ethereum/accounts"
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/hexutil"
    31  	"github.com/ethereum/go-ethereum/consensus"
    32  	"github.com/ethereum/go-ethereum/consensus/misc"
    33  	"github.com/ethereum/go-ethereum/core/state"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/crypto"
    36  	"github.com/ethereum/go-ethereum/crypto/sha3"
    37  	"github.com/ethereum/go-ethereum/ethdb"
    38  	"github.com/ethereum/go-ethereum/log"
    39  	"github.com/ethereum/go-ethereum/params"
    40  	"github.com/ethereum/go-ethereum/rlp"
    41  	"github.com/ethereum/go-ethereum/rpc"
    42  	lru "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  // Clique是在Ropsten攻击之后支持Ethereum testnet的权威证明共识引擎
   198  type Clique struct {
   199  	// 共识引擎配置
   200  	config *params.CliqueConfig // Consensus engine configuration parameters
   201  	// 用于存取检索点快照的数据库
   202  	db     ethdb.Database       // Database to store and retrieve snapshot checkpoints
   203  
   204  	// 最近区块的快照,用于加速快照重组
   205  	recents    *lru.ARCCache // Snapshots for recent block to speed up reorgs
   206  	// 最近区块的签名,用于加速挖矿
   207  	signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
   208  
   209  	// 当前提出的proposals列表
   210  	proposals map[common.Address]bool // Current list of proposals we are pushing
   211  
   212  	// signer地址
   213  	signer common.Address // Ethereum address of the signing key
   214  	// 签名函数
   215  	signFn SignerFn       // Signer function to authorize hashes with
   216  	// 读写锁
   217  	lock   sync.RWMutex   // Protects the signer fields
   218  }
   219  
   220  // New creates a Clique proof-of-authority consensus engine with the initial
   221  // signers set to the ones provided by the user.
   222  func New(config *params.CliqueConfig, db ethdb.Database) *Clique {
   223  	// Set any missing consensus parameters to their defaults
   224  	conf := *config
   225  	if conf.Epoch == 0 {
   226  		conf.Epoch = epochLength
   227  	}
   228  	// Allocate the snapshot caches and create the engine
   229  	recents, _ := lru.NewARC(inmemorySnapshots)
   230  	signatures, _ := lru.NewARC(inmemorySignatures)
   231  
   232  	return &Clique{
   233  		config:     &conf,
   234  		db:         db,
   235  		recents:    recents,
   236  		signatures: signatures,
   237  		proposals:  make(map[common.Address]bool),
   238  	}
   239  }
   240  
   241  // Author implements consensus.Engine, returning the Ethereum address recovered
   242  // from the signature in the header's extra-data section.
   243  func (c *Clique) Author(header *types.Header) (common.Address, error) {
   244  	return ecrecover(header, c.signatures)
   245  }
   246  
   247  // VerifyHeader checks whether a header conforms to the consensus rules.
   248  func (c *Clique) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
   249  	return c.verifyHeader(chain, header, nil)
   250  }
   251  
   252  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   253  // method returns a quit channel to abort the operations and a results channel to
   254  // retrieve the async verifications (the order is that of the input slice).
   255  func (c *Clique) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   256  	abort := make(chan struct{})
   257  	results := make(chan error, len(headers))
   258  
   259  	go func() {
   260  		for i, header := range headers {
   261  			err := c.verifyHeader(chain, header, headers[:i])
   262  
   263  			select {
   264  			case <-abort:
   265  				return
   266  			case results <- err:
   267  			}
   268  		}
   269  	}()
   270  	return abort, results
   271  }
   272  
   273  // verifyHeader checks whether a header conforms to the consensus rules.The
   274  // caller may optionally pass in a batch of parents (ascending order) to avoid
   275  // looking those up from the database. This is useful for concurrently verifying
   276  // a batch of new headers.
   277  func (c *Clique) verifyHeader(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   278  	if header.Number == nil {
   279  		return errUnknownBlock
   280  	}
   281  	number := header.Number.Uint64()
   282  
   283  	// Don't waste time checking blocks from the future
   284  	if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
   285  		return consensus.ErrFutureBlock
   286  	}
   287  	// Checkpoint blocks need to enforce zero beneficiary
   288  	checkpoint := (number % c.config.Epoch) == 0
   289  	if checkpoint && header.Coinbase != (common.Address{}) {
   290  		return errInvalidCheckpointBeneficiary
   291  	}
   292  	// Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints
   293  	if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) {
   294  		return errInvalidVote
   295  	}
   296  	if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) {
   297  		return errInvalidCheckpointVote
   298  	}
   299  	// Check that the extra-data contains both the vanity and signature
   300  	if len(header.Extra) < extraVanity {
   301  		return errMissingVanity
   302  	}
   303  	if len(header.Extra) < extraVanity+extraSeal {
   304  		return errMissingSignature
   305  	}
   306  	// Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
   307  	signersBytes := len(header.Extra) - extraVanity - extraSeal
   308  	if !checkpoint && signersBytes != 0 {
   309  		return errExtraSigners
   310  	}
   311  	if checkpoint && signersBytes%common.AddressLength != 0 {
   312  		return errInvalidCheckpointSigners
   313  	}
   314  	// Ensure that the mix digest is zero as we don't have fork protection currently
   315  	if header.MixDigest != (common.Hash{}) {
   316  		return errInvalidMixDigest
   317  	}
   318  	// Ensure that the block doesn't contain any uncles which are meaningless in PoA
   319  	if header.UncleHash != uncleHash {
   320  		return errInvalidUncleHash
   321  	}
   322  	// Ensure that the block's difficulty is meaningful (may not be correct at this point)
   323  	if number > 0 {
   324  		if header.Difficulty == nil || (header.Difficulty.Cmp(diffInTurn) != 0 && header.Difficulty.Cmp(diffNoTurn) != 0) {
   325  			return errInvalidDifficulty
   326  		}
   327  	}
   328  	// If all checks passed, validate any special fields for hard forks
   329  	if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
   330  		return err
   331  	}
   332  	// All basic checks passed, verify cascading fields
   333  	return c.verifyCascadingFields(chain, header, parents)
   334  }
   335  
   336  // verifyCascadingFields verifies all the header fields that are not standalone,
   337  // rather depend on a batch of previous headers. The caller may optionally pass
   338  // in a batch of parents (ascending order) to avoid looking those up from the
   339  // database. This is useful for concurrently verifying a batch of new headers.
   340  func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   341  	// The genesis block is the always valid dead-end
   342  	number := header.Number.Uint64()
   343  	if number == 0 {
   344  		return nil
   345  	}
   346  	// Ensure that the block's timestamp isn't too close to it's parent
   347  	var parent *types.Header
   348  	if len(parents) > 0 {
   349  		parent = parents[len(parents)-1]
   350  	} else {
   351  		parent = chain.GetHeader(header.ParentHash, number-1)
   352  	}
   353  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   354  		return consensus.ErrUnknownAncestor
   355  	}
   356  	if parent.Time.Uint64()+c.config.Period > header.Time.Uint64() {
   357  		return ErrInvalidTimestamp
   358  	}
   359  	// Retrieve the snapshot needed to verify this header and cache it
   360  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   361  	if err != nil {
   362  		return err
   363  	}
   364  	// If the block is a checkpoint block, verify the signer list
   365  	if number%c.config.Epoch == 0 {
   366  		signers := make([]byte, len(snap.Signers)*common.AddressLength)
   367  		for i, signer := range snap.signers() {
   368  			copy(signers[i*common.AddressLength:], signer[:])
   369  		}
   370  		extraSuffix := len(header.Extra) - extraSeal
   371  		if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) {
   372  			return errInvalidCheckpointSigners
   373  		}
   374  	}
   375  	// All basic checks passed, verify the seal and return
   376  	return c.verifySeal(chain, header, parents)
   377  }
   378  
   379  // snapshot retrieves the authorization snapshot at a given point in time.
   380  // 获取投票状态快照
   381  func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   382  	// Search for a snapshot in memory or on disk for checkpoints
   383  	// 在内存或磁盘上检索一个快照以检查检查点
   384  	var (
   385  		// 区块头
   386  		headers []*types.Header
   387  		// 快照对象
   388  		snap    *Snapshot
   389  	)
   390  	for snap == nil {
   391  		// If an in-memory snapshot was found, use that
   392  		// 如果一个内存里的快照被找到
   393  		if s, ok := c.recents.Get(hash); ok {
   394  			snap = s.(*Snapshot)
   395  			break
   396  		}
   397  		// If an on-disk checkpoint snapshot can be found, use that
   398  		// 如果一个磁盘检查点的快照被找到
   399  		if number%checkpointInterval == 0 {
   400  			// 从数据库中加载一个快照
   401  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil {
   402  				log.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash)
   403  				snap = s
   404  				break
   405  			}
   406  		}
   407  		// If we're at block zero, make a snapshot
   408  		// 处于创世区块,创建一个快照
   409  		if number == 0 {
   410  			genesis := chain.GetHeaderByNumber(0)
   411  			if err := c.VerifyHeader(chain, genesis, false); err != nil {
   412  				return nil, err
   413  			}
   414  			signers := make([]common.Address, (len(genesis.Extra)-extraVanity-extraSeal)/common.AddressLength)
   415  			for i := 0; i < len(signers); i++ {
   416  				copy(signers[i][:], genesis.Extra[extraVanity+i*common.AddressLength:])
   417  			}
   418  			// 创建新快照
   419  			snap = newSnapshot(c.config, c.signatures, 0, genesis.Hash(), signers)
   420  			if err := snap.store(c.db); err != nil {
   421  				return nil, err
   422  			}
   423  			log.Trace("Stored genesis voting snapshot to disk")
   424  			break
   425  		}
   426  		// No snapshot for this header, gather the header and move backward
   427  		// 没有这个区块头的快照,则收集区块头并向后移动
   428  		var header *types.Header
   429  		if len(parents) > 0 {
   430  			// If we have explicit parents, pick from there (enforced)
   431  			// 如果有明确的父块,必须选出一个
   432  			header = parents[len(parents)-1]
   433  			if header.Hash() != hash || header.Number.Uint64() != number {
   434  				return nil, consensus.ErrUnknownAncestor
   435  			}
   436  			parents = parents[:len(parents)-1]
   437  		} else {
   438  			// No explicit parents (or no more left), reach out to the database
   439  			// 没有明确的父块
   440  			header = chain.GetHeader(hash, number)
   441  			if header == nil {
   442  				return nil, consensus.ErrUnknownAncestor
   443  			}
   444  		}
   445  		headers = append(headers, header)
   446  		number, hash = number-1, header.ParentHash
   447  	}
   448  	// Previous snapshot found, apply any pending headers on top of it
   449  	// 找到之前的快照,将所有pending的区块头放在它的前面
   450  	for i := 0; i < len(headers)/2; i++ {
   451  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   452  	}
   453  	// 通过区块头生成新的快照
   454  	snap, err := snap.apply(headers)
   455  	if err != nil {
   456  		return nil, err
   457  	}
   458  	// 将当前快照区块的hash存到recents中
   459  	c.recents.Add(snap.Hash, snap)
   460  
   461  	// If we've generated a new checkpoint snapshot, save to disk
   462  	// 如果生成了一个新的检查点快照,保存到磁盘上
   463  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   464  		if err = snap.store(c.db); err != nil {
   465  			return nil, err
   466  		}
   467  		log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   468  	}
   469  	return snap, err
   470  }
   471  
   472  // VerifyUncles implements consensus.Engine, always returning an error for any
   473  // uncles as this consensus mechanism doesn't permit uncles.
   474  func (c *Clique) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   475  	if len(block.Uncles()) > 0 {
   476  		return errors.New("uncles not allowed")
   477  	}
   478  	return nil
   479  }
   480  
   481  // VerifySeal implements consensus.Engine, checking whether the signature contained
   482  // in the header satisfies the consensus protocol requirements.
   483  func (c *Clique) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   484  	return c.verifySeal(chain, header, nil)
   485  }
   486  
   487  // verifySeal checks whether the signature contained in the header satisfies the
   488  // consensus protocol requirements. The method accepts an optional list of parent
   489  // headers that aren't yet part of the local blockchain to generate the snapshots
   490  // from.
   491  func (c *Clique) verifySeal(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error {
   492  	// Verifying the genesis block is not supported
   493  	number := header.Number.Uint64()
   494  	if number == 0 {
   495  		return errUnknownBlock
   496  	}
   497  	// Retrieve the snapshot needed to verify this header and cache it
   498  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   499  	if err != nil {
   500  		return err
   501  	}
   502  
   503  	// Resolve the authorization key and check against signers
   504  	signer, err := ecrecover(header, c.signatures)
   505  	if err != nil {
   506  		return err
   507  	}
   508  	if _, ok := snap.Signers[signer]; !ok {
   509  		return errUnauthorized
   510  	}
   511  	for seen, recent := range snap.Recents {
   512  		if recent == signer {
   513  			// Signer is among recents, only fail if the current block doesn't shift it out
   514  			if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit {
   515  				return errUnauthorized
   516  			}
   517  		}
   518  	}
   519  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   520  	inturn := snap.inturn(header.Number.Uint64(), signer)
   521  	if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
   522  		return errInvalidDifficulty
   523  	}
   524  	if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
   525  		return errInvalidDifficulty
   526  	}
   527  	return nil
   528  }
   529  
   530  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   531  // header for running the transactions on top.
   532  func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) error {
   533  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   534  	header.Coinbase = common.Address{}
   535  	header.Nonce = types.BlockNonce{}
   536  
   537  	number := header.Number.Uint64()
   538  	// Assemble the voting snapshot to check which votes make sense
   539  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   540  	if err != nil {
   541  		return err
   542  	}
   543  	if number%c.config.Epoch != 0 {
   544  		c.lock.RLock()
   545  
   546  		// Gather all the proposals that make sense voting on
   547  		addresses := make([]common.Address, 0, len(c.proposals))
   548  		for address, authorize := range c.proposals {
   549  			if snap.validVote(address, authorize) {
   550  				addresses = append(addresses, address)
   551  			}
   552  		}
   553  		// If there's pending proposals, cast a vote on them
   554  		if len(addresses) > 0 {
   555  			header.Coinbase = addresses[rand.Intn(len(addresses))]
   556  			if c.proposals[header.Coinbase] {
   557  				copy(header.Nonce[:], nonceAuthVote)
   558  			} else {
   559  				copy(header.Nonce[:], nonceDropVote)
   560  			}
   561  		}
   562  		c.lock.RUnlock()
   563  	}
   564  	// Set the correct difficulty
   565  	header.Difficulty = CalcDifficulty(snap, c.signer)
   566  
   567  	// Ensure the extra data has all it's components
   568  	if len(header.Extra) < extraVanity {
   569  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   570  	}
   571  	header.Extra = header.Extra[:extraVanity]
   572  
   573  	if number%c.config.Epoch == 0 {
   574  		for _, signer := range snap.signers() {
   575  			header.Extra = append(header.Extra, signer[:]...)
   576  		}
   577  	}
   578  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   579  
   580  	// Mix digest is reserved for now, set to empty
   581  	header.MixDigest = common.Hash{}
   582  
   583  	// Ensure the timestamp has the correct delay
   584  	parent := chain.GetHeader(header.ParentHash, number-1)
   585  	if parent == nil {
   586  		return consensus.ErrUnknownAncestor
   587  	}
   588  	header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period))
   589  	if header.Time.Int64() < time.Now().Unix() {
   590  		header.Time = big.NewInt(time.Now().Unix())
   591  	}
   592  	return nil
   593  }
   594  
   595  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   596  // rewards given, and returns the final block.
   597  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) {
   598  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   599  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   600  	header.UncleHash = types.CalcUncleHash(nil)
   601  
   602  	// Assemble and return the final block for sealing
   603  	return types.NewBlock(header, txs, nil, receipts), nil
   604  }
   605  
   606  // Authorize injects a private key into the consensus engine to mint new blocks
   607  // with.
   608  func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
   609  	c.lock.Lock()
   610  	defer c.lock.Unlock()
   611  
   612  	c.signer = signer
   613  	c.signFn = signFn
   614  }
   615  
   616  // Seal implements consensus.Engine, attempting to create a sealed block using
   617  // the local signing credentials.
   618  // 实现consensus.Engine
   619  func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
   620  	header := block.Header()
   621  
   622  	// Sealing the genesis block is not supported
   623  	number := header.Number.Uint64()
   624  	// 当前区块是创世区块
   625  	if number == 0 {
   626  		return nil, errUnknownBlock
   627  	}
   628  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   629  	// 不支持0-period的链
   630  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   631  		return nil, errWaitTransactions
   632  	}
   633  	// Don't hold the signer fields for the entire sealing procedure
   634  	// 不要在整个签名过程中持有签名字段
   635  	c.lock.RLock()
   636  	// 获取signer和签名方法
   637  	signer, signFn := c.signer, c.signFn
   638  	c.lock.RUnlock()
   639  
   640  	// Bail out if we're unauthorized to sign a block
   641  	// 获取快照
   642  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   643  	if err != nil {
   644  		return nil, err
   645  	}
   646  	if _, authorized := snap.Signers[signer]; !authorized {
   647  		return nil, errUnauthorized
   648  	}
   649  	// If we're amongst the recent signers, wait for the next block
   650  	// 如果是最近的signers中的一员,等待下一个块
   651  	for seen, recent := range snap.Recents {
   652  		if recent == signer {
   653  			// Signer is among recents, only wait if the current block doesn't shift it out
   654  			// 当前区块没有踢出Signer则继续等待
   655  			if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
   656  				log.Info("Signed recently, must wait for others")
   657  				<-stop
   658  				return nil, nil
   659  			}
   660  		}
   661  	}
   662  	// Sweet, the protocol permits us to sign the block, wait for our time
   663  	// 执行到这说明协议允许我们来签名这个区块
   664  	delay := time.Unix(header.Time.Int64(), 0).Sub(time.Now()) // nolint: gosimple
   665  	// 出块难度值判断
   666  	if header.Difficulty.Cmp(diffNoTurn) == 0 {
   667  		// It's not our turn explicitly to sign, delay it a bit
   668  		// 当前处于OUT-OF-TURN状态,随机一定时间延迟处理
   669  		wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime
   670  		delay += time.Duration(rand.Int63n(int64(wiggle)))
   671  
   672  		log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
   673  	}
   674  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   675  
   676  	select {
   677  	case <-stop:
   678  		// 停止信号
   679  		return nil, nil
   680  	case <-time.After(delay):
   681  	}
   682  	// Sign all the things!
   683  	// 签名工作
   684  	sighash, err := signFn(accounts.Account{Address: signer}, sigHash(header).Bytes())
   685  	if err != nil {
   686  		return nil, err
   687  	}
   688  	// 更新区块头的extra字段
   689  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   690  
   691  	// 通过区块头组装新区块
   692  	return block.WithSeal(header), nil
   693  }
   694  
   695  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   696  // that a new block should have based on the previous blocks in the chain and the
   697  // current signer.
   698  func (c *Clique) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   699  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   700  	if err != nil {
   701  		return nil
   702  	}
   703  	return CalcDifficulty(snap, c.signer)
   704  }
   705  
   706  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   707  // that a new block should have based on the previous blocks in the chain and the
   708  // current signer.
   709  // clique共识难度调整算法 当前块的难度基于前一个块和当前的签名者
   710  func CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
   711  	if snap.inturn(snap.Number+1, signer) {
   712  		return new(big.Int).Set(diffInTurn)
   713  	}
   714  	return new(big.Int).Set(diffNoTurn)
   715  }
   716  
   717  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   718  // controlling the signer voting.
   719  func (c *Clique) APIs(chain consensus.ChainReader) []rpc.API {
   720  	return []rpc.API{{
   721  		Namespace: "clique",
   722  		Version:   "1.0",
   723  		Service:   &API{chain: chain, clique: c},
   724  		Public:    false,
   725  	}}
   726  }