github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/consensus/poa/poa.go (about)

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