github.com/gilgames000/kcc-geth@v1.0.6/consensus/posa/posa.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 posa implements the proof-of-stake-authority consensus engine.
    18  package posa
    19  
    20  import (
    21  	"bytes"
    22  	"errors"
    23  	"io"
    24  	"math"
    25  	"math/big"
    26  	"math/rand"
    27  	"sort"
    28  	"sync"
    29  	"time"
    30  
    31  	"github.com/ethereum/go-ethereum/accounts"
    32  	"github.com/ethereum/go-ethereum/accounts/abi"
    33  	"github.com/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/consensus"
    35  	"github.com/ethereum/go-ethereum/consensus/misc"
    36  	"github.com/ethereum/go-ethereum/core/state"
    37  	"github.com/ethereum/go-ethereum/core/types"
    38  	"github.com/ethereum/go-ethereum/crypto"
    39  	"github.com/ethereum/go-ethereum/ethdb"
    40  	"github.com/ethereum/go-ethereum/log"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/rlp"
    43  	"github.com/ethereum/go-ethereum/rpc"
    44  	"github.com/ethereum/go-ethereum/trie"
    45  	lru "github.com/hashicorp/golang-lru"
    46  	"golang.org/x/crypto/sha3"
    47  )
    48  
    49  const (
    50  	checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database
    51  	inmemorySnapshots  = 128  // Number of recent vote snapshots to keep in memory
    52  	inmemorySignatures = 4096 // Number of recent block signatures to keep in memory
    53  
    54  	wiggleTime    = 500 * time.Millisecond // Random delay (per validator) to allow concurrent validators
    55  	maxValidators = 21                     // Max validators allowed to seal.
    56  )
    57  
    58  // proof-of-stake-authority protocol constants.
    59  var (
    60  	epochLength = uint64(30000) // Default number of blocks after which to checkpoint and reset the pending votes
    61  
    62  	extraVanity = 32                     // Fixed number of extra-data prefix bytes reserved for validator vanity
    63  	extraSeal   = crypto.SignatureLength // Fixed number of extra-data suffix bytes reserved for validator seal
    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  )
    70  
    71  // System contract address.
    72  var (
    73  	validatorsContractName = "validators"
    74  	punishContractName     = "punish"
    75  	proposalContractName   = "proposal"
    76  	validatorsContractAddr = common.HexToAddress("0x000000000000000000000000000000000000f000")
    77  	punishContractAddr     = common.HexToAddress("0x000000000000000000000000000000000000f111")
    78  	proposalAddr           = common.HexToAddress("0x000000000000000000000000000000000000f222")
    79  )
    80  
    81  // Various error messages to mark blocks invalid. These should be private to
    82  // prevent engine specific errors from being referenced in the remainder of the
    83  // codebase, inherently breaking if the engine is swapped out. Please put common
    84  // error types into the consensus package.
    85  var (
    86  	// errUnknownBlock is returned when the list of validators is requested for a block
    87  	// that is not part of the local blockchain.
    88  	errUnknownBlock = errors.New("unknown block")
    89  
    90  	// errMissingVanity is returned if a block's extra-data section is shorter than
    91  	// 32 bytes, which is required to store the validator vanity.
    92  	errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
    93  
    94  	// errMissingSignature is returned if a block's extra-data section doesn't seem
    95  	// to contain a 65 byte secp256k1 signature.
    96  	errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
    97  
    98  	// errExtraValidators is returned if non-checkpoint block contain validator data in
    99  	// their extra-data fields.
   100  	errExtraValidators = errors.New("non-checkpoint block contains extra validator list")
   101  
   102  	// errInvalidExtraValidators is returned if validator data in extra-data field is invalid.
   103  	errInvalidExtraValidators = errors.New("Invalid extra validators in extra data field")
   104  
   105  	// errInvalidMixDigest is returned if a block's mix digest is non-zero.
   106  	errInvalidMixDigest = errors.New("non-zero mix digest")
   107  
   108  	// errInvalidUncleHash is returned if a block contains an non-empty uncle list.
   109  	errInvalidUncleHash = errors.New("non empty uncle hash")
   110  
   111  	// errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2.
   112  	errInvalidDifficulty = errors.New("invalid difficulty")
   113  
   114  	// errWrongDifficulty is returned if the difficulty of a block doesn't match the
   115  	// turn of the validator.
   116  	errWrongDifficulty = errors.New("wrong 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  	// errUnauthorizedValidator is returned if a header is signed by a non-authorized entity.
   127  	errUnauthorizedValidator = errors.New("unauthorized validator")
   128  
   129  	// errRecentlySigned is returned if a header is signed by an authorized entity
   130  	// that already signed a header recently, thus is temporarily not allowed to.
   131  	errRecentlySigned = errors.New("recently signed")
   132  
   133  	// errInvalidValidatorLen is returned if validators length is zero or bigger than maxValidators.
   134  	errInvalidValidatorsLength = errors.New("Invalid validators length")
   135  
   136  	// errInvalidCoinbase is returned if the coinbase isn't the validator of the block.
   137  	errInvalidCoinbase = errors.New("Invalid coin base")
   138  )
   139  
   140  // StateFn gets state by the state root hash.
   141  type StateFn func(hash common.Hash) (*state.StateDB, error)
   142  
   143  // ValidatorFn hashes and signs the data to be signed by a backing account.
   144  type ValidatorFn func(validator accounts.Account, mimeType string, message []byte) ([]byte, error)
   145  
   146  // ecrecover extracts the Ethereum account address from a signed header.
   147  func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) {
   148  	// If the signature's already cached, return that
   149  	hash := header.Hash()
   150  	if address, known := sigcache.Get(hash); known {
   151  		return address.(common.Address), nil
   152  	}
   153  	// Retrieve the signature from the header extra-data
   154  	if len(header.Extra) < extraSeal {
   155  		return common.Address{}, errMissingSignature
   156  	}
   157  	signature := header.Extra[len(header.Extra)-extraSeal:]
   158  
   159  	// Recover the public key and the Ethereum address
   160  	pubkey, err := crypto.Ecrecover(SealHash(header).Bytes(), signature)
   161  	if err != nil {
   162  		return common.Address{}, err
   163  	}
   164  	var validator common.Address
   165  	copy(validator[:], crypto.Keccak256(pubkey[1:])[12:])
   166  
   167  	sigcache.Add(hash, validator)
   168  	return validator, nil
   169  }
   170  
   171  // The proof-of-stake-authority consensus engine proposed to support the
   172  // Ethereum testnet following the Ropsten attacks.
   173  type POSA struct {
   174  	chainConfig *params.ChainConfig // ChainConfig to execute evm
   175  	config      *params.POSAConfig  // Consensus engine configuration parameters
   176  	db          ethdb.Database      // Database to store and retrieve snapshot checkpoints
   177  
   178  	recents    *lru.ARCCache // Snapshots for recent block to speed up reorgs
   179  	signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
   180  
   181  	proposals map[common.Address]bool // Current list of proposals we are pushing
   182  
   183  	validator common.Address // Ethereum address of the signing key
   184  	signFn    ValidatorFn    // Validator function to authorize hashes with
   185  	lock      sync.RWMutex   // Protects the validator fields
   186  
   187  	stateFn StateFn // Function to get state by state root
   188  
   189  	abi map[string]abi.ABI // Interactive with system contracts
   190  
   191  	// The fields below are for testing only
   192  	fakeDiff bool // Skip difficulty verifications
   193  }
   194  
   195  // New creates a proof-of-stake-authority consensus engine with the initial
   196  // validators set to the ones provided by the user.
   197  func New(chainConfig *params.ChainConfig, db ethdb.Database) *POSA {
   198  	// Set any missing consensus parameters to their defaults
   199  	conf := *chainConfig.POSA
   200  	if conf.Epoch == 0 {
   201  		conf.Epoch = epochLength
   202  	}
   203  	// Allocate the snapshot caches and create the engine
   204  	recents, _ := lru.NewARC(inmemorySnapshots)
   205  	signatures, _ := lru.NewARC(inmemorySignatures)
   206  
   207  	interactiveABI := getInteractiveABI()
   208  
   209  	return &POSA{
   210  		chainConfig: chainConfig,
   211  		config:      &conf,
   212  		db:          db,
   213  		recents:     recents,
   214  		signatures:  signatures,
   215  		proposals:   make(map[common.Address]bool),
   216  		abi:         interactiveABI,
   217  	}
   218  }
   219  
   220  // SetStateFn sets the function to get state.
   221  func (c *POSA) SetStateFn(fn StateFn) {
   222  	c.stateFn = fn
   223  }
   224  
   225  // Author implements consensus.Engine, returning the Ethereum address recovered
   226  // from the signature in the header's extra-data section.
   227  func (c *POSA) Author(header *types.Header) (common.Address, error) {
   228  	return header.Coinbase, nil
   229  	// return ecrecover(header, c.signatures)
   230  }
   231  
   232  // VerifyHeader checks whether a header conforms to the consensus rules.
   233  func (c *POSA) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
   234  	return c.verifyHeader(chain, header, nil)
   235  }
   236  
   237  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   238  // method returns a quit channel to abort the operations and a results channel to
   239  // retrieve the async verifications (the order is that of the input slice).
   240  func (c *POSA) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   241  	abort := make(chan struct{})
   242  	results := make(chan error, len(headers))
   243  
   244  	go func() {
   245  		for i, header := range headers {
   246  			err := c.verifyHeader(chain, header, headers[:i])
   247  
   248  			select {
   249  			case <-abort:
   250  				return
   251  			case results <- err:
   252  			}
   253  		}
   254  	}()
   255  	return abort, results
   256  }
   257  
   258  // verifyHeader checks whether a header conforms to the consensus rules.The
   259  // caller may optionally pass in a batch of parents (ascending order) to avoid
   260  // looking those up from the database. This is useful for concurrently verifying
   261  // a batch of new headers.
   262  func (c *POSA) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   263  	if header.Number == nil {
   264  		return errUnknownBlock
   265  	}
   266  	number := header.Number.Uint64()
   267  
   268  	// Don't waste time checking blocks from the future
   269  	if header.Time > uint64(time.Now().Unix()) {
   270  		return consensus.ErrFutureBlock
   271  	}
   272  	// Check that the extra-data contains the vanity, validators and signature.
   273  	if len(header.Extra) < extraVanity {
   274  		return errMissingVanity
   275  	}
   276  	if len(header.Extra) < extraVanity+extraSeal {
   277  		return errMissingSignature
   278  	}
   279  	// check extra data
   280  	isEpoch := number%c.config.Epoch == 0
   281  
   282  	// Ensure that the extra-data contains a validator list on checkpoint, but none otherwise
   283  	validatorsBytes := len(header.Extra) - extraVanity - extraSeal
   284  	if !isEpoch && validatorsBytes != 0 {
   285  		return errExtraValidators
   286  	}
   287  	// Ensure that the validator bytes length is valid
   288  	if isEpoch && validatorsBytes%common.AddressLength != 0 {
   289  		return errExtraValidators
   290  	}
   291  
   292  	// Ensure that the mix digest is zero as we don't have fork protection currently
   293  	if header.MixDigest != (common.Hash{}) {
   294  		return errInvalidMixDigest
   295  	}
   296  	// Ensure that the block doesn't contain any uncles which are meaningless in PoA
   297  	if header.UncleHash != uncleHash {
   298  		return errInvalidUncleHash
   299  	}
   300  	// Ensure that the block's difficulty is meaningful (may not be correct at this point)
   301  	if number > 0 && header.Difficulty == nil {
   302  		return errInvalidDifficulty
   303  	}
   304  	// If all checks passed, validate any special fields for hard forks
   305  	if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
   306  		return err
   307  	}
   308  	// All basic checks passed, verify cascading fields
   309  	return c.verifyCascadingFields(chain, header, parents)
   310  }
   311  
   312  // verifyCascadingFields verifies all the header fields that are not standalone,
   313  // rather depend on a batch of previous headers. The caller may optionally pass
   314  // in a batch of parents (ascending order) to avoid looking those up from the
   315  // database. This is useful for concurrently verifying a batch of new headers.
   316  func (c *POSA) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   317  	// The genesis block is the always valid dead-end
   318  	number := header.Number.Uint64()
   319  	if number == 0 {
   320  		return nil
   321  	}
   322  
   323  	var parent *types.Header
   324  	if len(parents) > 0 {
   325  		parent = parents[len(parents)-1]
   326  	} else {
   327  		parent = chain.GetHeader(header.ParentHash, number-1)
   328  	}
   329  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   330  		return consensus.ErrUnknownAncestor
   331  	}
   332  
   333  	if parent.Time+c.config.Period > header.Time {
   334  		return ErrInvalidTimestamp
   335  	}
   336  
   337  	// All basic checks passed, verify the seal and return
   338  	return c.verifySeal(chain, header, parents)
   339  }
   340  
   341  // snapshot retrieves the authorization snapshot at a given point in time.
   342  func (c *POSA) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   343  	// Search for a snapshot in memory or on disk for checkpoints
   344  	var (
   345  		headers []*types.Header
   346  		snap    *Snapshot
   347  	)
   348  	for snap == nil {
   349  		// If an in-memory snapshot was found, use that
   350  		if s, ok := c.recents.Get(hash); ok {
   351  			snap = s.(*Snapshot)
   352  			break
   353  		}
   354  		// If an on-disk checkpoint snapshot can be found, use that
   355  		if number%checkpointInterval == 0 {
   356  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil {
   357  				log.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash)
   358  				snap = s
   359  				break
   360  			}
   361  		}
   362  		// If we're at the genesis, snapshot the initial state. Alternatively if we're
   363  		// at a checkpoint block without a parent (light client CHT), or we have piled
   364  		// up more headers than allowed to be reorged (chain reinit from a freezer),
   365  		// consider the checkpoint trusted and snapshot it.
   366  		if number == 0 || (number%c.config.Epoch == 0 && (len(headers) > params.FullImmutabilityThreshold || chain.GetHeaderByNumber(number-1) == nil)) {
   367  			checkpoint := chain.GetHeaderByNumber(number)
   368  			if checkpoint != nil {
   369  				hash := checkpoint.Hash()
   370  
   371  				validators := make([]common.Address, (len(checkpoint.Extra)-extraVanity-extraSeal)/common.AddressLength)
   372  				for i := 0; i < len(validators); i++ {
   373  					copy(validators[i][:], checkpoint.Extra[extraVanity+i*common.AddressLength:])
   374  				}
   375  				snap = newSnapshot(c.config, c.signatures, number, hash, validators)
   376  				if err := snap.store(c.db); err != nil {
   377  					return nil, err
   378  				}
   379  				log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash)
   380  				break
   381  			}
   382  		}
   383  		// No snapshot for this header, gather the header and move backward
   384  		var header *types.Header
   385  		if len(parents) > 0 {
   386  			// If we have explicit parents, pick from there (enforced)
   387  			header = parents[len(parents)-1]
   388  			if header.Hash() != hash || header.Number.Uint64() != number {
   389  				return nil, consensus.ErrUnknownAncestor
   390  			}
   391  			parents = parents[:len(parents)-1]
   392  		} else {
   393  			// No explicit parents (or no more left), reach out to the database
   394  			header = chain.GetHeader(hash, number)
   395  			if header == nil {
   396  				return nil, consensus.ErrUnknownAncestor
   397  			}
   398  		}
   399  		headers = append(headers, header)
   400  		number, hash = number-1, header.ParentHash
   401  	}
   402  	// Previous snapshot found, apply any pending headers on top of it
   403  	for i := 0; i < len(headers)/2; i++ {
   404  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   405  	}
   406  	snap, err := snap.apply(headers, chain, parents)
   407  	if err != nil {
   408  		return nil, err
   409  	}
   410  	c.recents.Add(snap.Hash, snap)
   411  
   412  	// If we've generated a new checkpoint snapshot, save to disk
   413  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   414  		if err = snap.store(c.db); err != nil {
   415  			return nil, err
   416  		}
   417  		log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   418  	}
   419  	return snap, err
   420  }
   421  
   422  // VerifyUncles implements consensus.Engine, always returning an error for any
   423  // uncles as this consensus mechanism doesn't permit uncles.
   424  func (c *POSA) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   425  	if len(block.Uncles()) > 0 {
   426  		return errors.New("uncles not allowed")
   427  	}
   428  	return nil
   429  }
   430  
   431  // VerifySeal implements consensus.Engine, checking whether the signature contained
   432  // in the header satisfies the consensus protocol requirements.
   433  func (c *POSA) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error {
   434  	return c.verifySeal(chain, header, nil)
   435  }
   436  
   437  // verifySeal checks whether the signature contained in the header satisfies the
   438  // consensus protocol requirements. The method accepts an optional list of parent
   439  // headers that aren't yet part of the local blockchain to generate the snapshots
   440  // from.
   441  func (c *POSA) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   442  	// Verifying the genesis block is not supported
   443  	number := header.Number.Uint64()
   444  	if number == 0 {
   445  		return errUnknownBlock
   446  	}
   447  	// Retrieve the snapshot needed to verify this header and cache it
   448  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   449  	if err != nil {
   450  		return err
   451  	}
   452  
   453  	// Resolve the authorization key and check against validators
   454  	signer, err := ecrecover(header, c.signatures)
   455  	if err != nil {
   456  		return err
   457  	}
   458  	if signer != header.Coinbase {
   459  		return errInvalidCoinbase
   460  	}
   461  
   462  	if _, ok := snap.Validators[signer]; !ok {
   463  		return errUnauthorizedValidator
   464  	}
   465  
   466  	for seen, recent := range snap.Recents {
   467  		if recent == signer {
   468  			// Validator is among recents, only fail if the current block doesn't shift it out
   469  			if limit := uint64(len(snap.Validators)/2 + 1); seen > number-limit {
   470  				return errRecentlySigned
   471  			}
   472  		}
   473  	}
   474  
   475  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   476  	if !c.fakeDiff {
   477  		inturn := snap.inturn(header.Number.Uint64(), signer)
   478  		if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
   479  			return errWrongDifficulty
   480  		}
   481  		if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
   482  			return errWrongDifficulty
   483  		}
   484  	}
   485  
   486  	return nil
   487  }
   488  
   489  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   490  // header for running the transactions on top.
   491  func (c *POSA) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   492  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   493  	header.Coinbase = c.validator
   494  	header.Nonce = types.BlockNonce{}
   495  
   496  	number := header.Number.Uint64()
   497  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   498  	if err != nil {
   499  		return err
   500  	}
   501  
   502  	// Set the correct difficulty
   503  	header.Difficulty = calcDifficulty(snap, c.validator)
   504  
   505  	// Ensure the extra data has all its components
   506  	if len(header.Extra) < extraVanity {
   507  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   508  	}
   509  	header.Extra = header.Extra[:extraVanity]
   510  
   511  	if number%c.config.Epoch == 0 {
   512  		newSortedValidators, err := c.getTopValidators(chain, header)
   513  		if err != nil {
   514  			return err
   515  		}
   516  
   517  		for _, validator := range newSortedValidators {
   518  			header.Extra = append(header.Extra, validator.Bytes()...)
   519  		}
   520  	}
   521  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   522  
   523  	// Mix digest is reserved for now, set to empty
   524  	header.MixDigest = common.Hash{}
   525  
   526  	// Ensure the timestamp has the correct delay
   527  	parent := chain.GetHeader(header.ParentHash, number-1)
   528  	if parent == nil {
   529  		return consensus.ErrUnknownAncestor
   530  	}
   531  	header.Time = parent.Time + c.config.Period
   532  	if header.Time < uint64(time.Now().Unix()) {
   533  		header.Time = uint64(time.Now().Unix())
   534  	}
   535  	return nil
   536  }
   537  
   538  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   539  // rewards given.
   540  func (c *POSA) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) error {
   541  	// Initialize all system contracts at block 1.
   542  	if header.Number.Cmp(common.Big1) == 0 {
   543  		if err := c.initializeSystemContracts(chain, header, state); err != nil {
   544  			log.Error("Initialize system contracts failed", "err", err)
   545  			return err
   546  		}
   547  	}
   548  
   549  	if header.Difficulty.Cmp(diffInTurn) != 0 {
   550  		if err := c.tryPunishValidator(chain, header, state); err != nil {
   551  			return err
   552  		}
   553  	}
   554  
   555  	// execute block reward tx.
   556  	if len(txs) > 0 {
   557  		if err := c.trySendBlockReward(chain, header, state); err != nil {
   558  			return err
   559  		}
   560  	}
   561  
   562  	// do epoch thing at the end, because it will update active validators
   563  	if header.Number.Uint64()%c.config.Epoch == 0 {
   564  		newValidators, err := c.doSomethingAtEpoch(chain, header, state)
   565  		if err != nil {
   566  			return err
   567  		}
   568  
   569  		validatorsBytes := make([]byte, len(newValidators)*common.AddressLength)
   570  		for i, validator := range newValidators {
   571  			copy(validatorsBytes[i*common.AddressLength:], validator.Bytes())
   572  		}
   573  
   574  		extraSuffix := len(header.Extra) - extraSeal
   575  		if !bytes.Equal(header.Extra[extraVanity:extraSuffix], validatorsBytes) {
   576  			return errInvalidExtraValidators
   577  		}
   578  	}
   579  
   580  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   581  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   582  	header.UncleHash = types.CalcUncleHash(nil)
   583  
   584  	return nil
   585  }
   586  
   587  // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
   588  // nor block rewards given, and returns the final block.
   589  func (c *POSA) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
   590  	// Initialize all system contracts at block 1.
   591  	if header.Number.Cmp(common.Big1) == 0 {
   592  		if err := c.initializeSystemContracts(chain, header, state); err != nil {
   593  			panic(err)
   594  		}
   595  	}
   596  
   597  	// punish validator if necessary
   598  	if header.Difficulty.Cmp(diffInTurn) != 0 {
   599  		if err := c.tryPunishValidator(chain, header, state); err != nil {
   600  			panic(err)
   601  		}
   602  	}
   603  
   604  	// deposit block reward if any tx exists.
   605  	if len(txs) > 0 {
   606  		if err := c.trySendBlockReward(chain, header, state); err != nil {
   607  			panic(err)
   608  		}
   609  	}
   610  
   611  	// do epoch thing at the end, because it will update active validators
   612  	if header.Number.Uint64()%c.config.Epoch == 0 {
   613  		if _, err := c.doSomethingAtEpoch(chain, header, state); err != nil {
   614  			panic(err)
   615  		}
   616  	}
   617  
   618  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   619  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   620  	header.UncleHash = types.CalcUncleHash(nil)
   621  
   622  	// Assemble and return the final block for sealing
   623  	return types.NewBlock(header, txs, nil, receipts, new(trie.Trie)), nil
   624  }
   625  
   626  func (c *POSA) trySendBlockReward(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error {
   627  	fee := state.GetBalance(consensus.FeeRecoder)
   628  	if fee.Cmp(common.Big0) <= 0 {
   629  		return nil
   630  	}
   631  
   632  	// Miner will send tx to deposit block fees to contract, add to his balance first.
   633  	state.AddBalance(header.Coinbase, fee)
   634  	// defer reset fee
   635  	defer state.SetBalance(consensus.FeeRecoder, common.Big0)
   636  
   637  	method := "distributeBlockReward"
   638  	data, err := c.abi[validatorsContractName].Pack(method)
   639  	if err != nil {
   640  		log.Error("Can't pack data for distributeBlockReward", "err", err)
   641  		return err
   642  	}
   643  
   644  	nonce := state.GetNonce(header.Coinbase)
   645  	msg := types.NewMessage(header.Coinbase, &validatorsContractAddr, nonce, fee, math.MaxUint64, new(big.Int), data, nil, true)
   646  
   647  	if _, err := executeMsg(msg, state, header, newChainContext(chain, c), c.chainConfig); err != nil {
   648  		return err
   649  	}
   650  
   651  	return nil
   652  }
   653  
   654  func (c *POSA) tryPunishValidator(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error {
   655  	number := header.Number.Uint64()
   656  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   657  	if err != nil {
   658  		return err
   659  	}
   660  	validators := snap.validators()
   661  	outTurnValidator := validators[number%uint64(len(validators))]
   662  	// check sigend recently or not
   663  	signedRecently := false
   664  	for _, recent := range snap.Recents {
   665  		if recent == outTurnValidator {
   666  			signedRecently = true
   667  			break
   668  		}
   669  	}
   670  	if !signedRecently {
   671  		if err := c.punishValidator(outTurnValidator, chain, header, state); err != nil {
   672  			return err
   673  		}
   674  	}
   675  
   676  	return nil
   677  }
   678  
   679  func (c *POSA) doSomethingAtEpoch(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) ([]common.Address, error) {
   680  	newSortedValidators, err := c.getTopValidators(chain, header)
   681  	if err != nil {
   682  		return []common.Address{}, err
   683  	}
   684  
   685  	// update contract new validators if new set exists
   686  	if err := c.updateValidators(chain, header, state); err != nil {
   687  		return []common.Address{}, err
   688  	}
   689  	//  decrease validator missed blocks counter at epoch
   690  	if err := c.decreaseMissedBlocksCounter(chain, header, state); err != nil {
   691  		return []common.Address{}, err
   692  	}
   693  
   694  	return newSortedValidators, nil
   695  }
   696  
   697  // initializeSystemContracts initializes all system contracts.
   698  func (c *POSA) initializeSystemContracts(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error {
   699  	snap, err := c.snapshot(chain, 0, header.ParentHash, nil)
   700  	if err != nil {
   701  		return err
   702  	}
   703  
   704  	genesisValidators := snap.validators()
   705  	if len(genesisValidators) == 0 || len(genesisValidators) > maxValidators {
   706  		return errInvalidValidatorsLength
   707  	}
   708  
   709  	method := "initialize"
   710  	contracts := []struct {
   711  		addr    common.Address
   712  		packFun func() ([]byte, error)
   713  	}{
   714  		{validatorsContractAddr, func() ([]byte, error) {
   715  			return c.abi[validatorsContractName].Pack(method, genesisValidators)
   716  		}},
   717  		{punishContractAddr, func() ([]byte, error) { return c.abi[punishContractName].Pack(method) }},
   718  		{proposalAddr, func() ([]byte, error) { return c.abi[proposalContractName].Pack(method, genesisValidators) }},
   719  	}
   720  
   721  	for _, contract := range contracts {
   722  		data, err := contract.packFun()
   723  		if err != nil {
   724  			return err
   725  		}
   726  
   727  		nonce := state.GetNonce(header.Coinbase)
   728  		msg := types.NewMessage(header.Coinbase, &contract.addr, nonce, new(big.Int), math.MaxUint64, new(big.Int), data, nil, true)
   729  
   730  		if _, err := executeMsg(msg, state, header, newChainContext(chain, c), c.chainConfig); err != nil {
   731  			return err
   732  		}
   733  	}
   734  
   735  	return nil
   736  }
   737  
   738  // call this at epoch block to get top validators based on the state of epoch block - 1
   739  func (c *POSA) getTopValidators(chain consensus.ChainHeaderReader, header *types.Header) ([]common.Address, error) {
   740  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   741  	if parent == nil {
   742  		return []common.Address{}, consensus.ErrUnknownAncestor
   743  	}
   744  	stateDB, err := c.stateFn(parent.Root)
   745  	if err != nil {
   746  		return []common.Address{}, err
   747  	}
   748  
   749  	method := "getTopValidators"
   750  	data, err := c.abi[validatorsContractName].Pack(method)
   751  	if err != nil {
   752  		log.Error("Can't pack data for getTopValidators", "error", err)
   753  		return []common.Address{}, err
   754  	}
   755  
   756  	msg := types.NewMessage(header.Coinbase, &validatorsContractAddr, 0, new(big.Int), math.MaxUint64, new(big.Int), data, nil, false)
   757  
   758  	// use parent
   759  	result, err := executeMsg(msg, stateDB, parent, newChainContext(chain, c), c.chainConfig)
   760  	if err != nil {
   761  		return []common.Address{}, err
   762  	}
   763  
   764  	// unpack data
   765  	ret, err := c.abi[validatorsContractName].Unpack(method, result)
   766  	if err != nil {
   767  		return []common.Address{}, err
   768  	}
   769  	if len(ret) != 1 {
   770  		return []common.Address{}, errors.New("Invalid params length")
   771  	}
   772  	validators, ok := ret[0].([]common.Address)
   773  	if !ok {
   774  		return []common.Address{}, errors.New("Invalid validators format")
   775  	}
   776  	sort.Sort(validatorsAscending(validators))
   777  	return validators, err
   778  }
   779  
   780  func (c *POSA) updateValidators(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error {
   781  	// method
   782  	method := "updateActiveValidatorSet"
   783  	data, err := c.abi[validatorsContractName].Pack(method, new(big.Int).SetUint64(c.config.Epoch))
   784  	if err != nil {
   785  		log.Error("Can't pack data for updateActiveValidatorSet", "error", err)
   786  		return err
   787  	}
   788  
   789  	// call contract
   790  	nonce := state.GetNonce(header.Coinbase)
   791  	msg := types.NewMessage(header.Coinbase, &validatorsContractAddr, nonce, new(big.Int), math.MaxUint64, new(big.Int), data, nil, true)
   792  	if _, err := executeMsg(msg, state, header, newChainContext(chain, c), c.chainConfig); err != nil {
   793  		log.Error("Can't update validators to contract", "err", err)
   794  		return err
   795  	}
   796  
   797  	return nil
   798  }
   799  
   800  func (c *POSA) punishValidator(val common.Address, chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error {
   801  	// method
   802  	method := "punish"
   803  	data, err := c.abi[punishContractName].Pack(method, val)
   804  	if err != nil {
   805  		log.Error("Can't pack data for punish", "error", err)
   806  		return err
   807  	}
   808  
   809  	// call contract
   810  	nonce := state.GetNonce(header.Coinbase)
   811  	msg := types.NewMessage(header.Coinbase, &punishContractAddr, nonce, new(big.Int), math.MaxUint64, new(big.Int), data, nil, true)
   812  	if _, err := executeMsg(msg, state, header, newChainContext(chain, c), c.chainConfig); err != nil {
   813  		log.Error("Can't punish validator", "err", err)
   814  		return err
   815  	}
   816  
   817  	return nil
   818  }
   819  
   820  func (c *POSA) decreaseMissedBlocksCounter(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB) error {
   821  	// method
   822  	method := "decreaseMissedBlocksCounter"
   823  	data, err := c.abi[punishContractName].Pack(method, new(big.Int).SetUint64(c.config.Epoch))
   824  	if err != nil {
   825  		log.Error("Can't pack data for decreaseMissedBlocksCounter", "error", err)
   826  		return err
   827  	}
   828  
   829  	// call contract
   830  	nonce := state.GetNonce(header.Coinbase)
   831  	msg := types.NewMessage(header.Coinbase, &punishContractAddr, nonce, new(big.Int), math.MaxUint64, new(big.Int), data, nil, true)
   832  	if _, err := executeMsg(msg, state, header, newChainContext(chain, c), c.chainConfig); err != nil {
   833  		log.Error("Can't decrease missed blocks counter for validator", "err", err)
   834  		return err
   835  	}
   836  
   837  	return nil
   838  }
   839  
   840  // Authorize injects a private key into the consensus engine to mint new blocks
   841  // with.
   842  func (c *POSA) Authorize(validator common.Address, signFn ValidatorFn) {
   843  	c.lock.Lock()
   844  	defer c.lock.Unlock()
   845  
   846  	c.validator = validator
   847  	c.signFn = signFn
   848  }
   849  
   850  // Seal implements consensus.Engine, attempting to create a sealed block using
   851  // the local signing credentials.
   852  func (c *POSA) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
   853  	header := block.Header()
   854  
   855  	// Sealing the genesis block is not supported
   856  	number := header.Number.Uint64()
   857  	if number == 0 {
   858  		return errUnknownBlock
   859  	}
   860  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   861  	if c.config.Period == 0 && len(block.Transactions()) == 0 {
   862  		log.Info("Sealing paused, waiting for transactions")
   863  		return nil
   864  	}
   865  	// Don't hold the val fields for the entire sealing procedure
   866  	c.lock.RLock()
   867  	val, signFn := c.validator, c.signFn
   868  	c.lock.RUnlock()
   869  
   870  	// Bail out if we're unauthorized to sign a block
   871  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   872  	if err != nil {
   873  		return err
   874  	}
   875  	if _, authorized := snap.Validators[val]; !authorized {
   876  		return errUnauthorizedValidator
   877  	}
   878  	// If we're amongst the recent validators, wait for the next block
   879  	for seen, recent := range snap.Recents {
   880  		if recent == val {
   881  			// Validator is among recents, only wait if the current block doesn't shift it out
   882  			if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
   883  				log.Info("Signed recently, must wait for others")
   884  				return nil
   885  			}
   886  		}
   887  	}
   888  
   889  	// Sweet, the protocol permits us to sign the block, wait for our time
   890  	delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple
   891  	if header.Difficulty.Cmp(diffNoTurn) == 0 {
   892  		// It's not our turn explicitly to sign, delay it a bit
   893  		wiggle := time.Duration(len(snap.Validators)/2+1) * wiggleTime
   894  		delay += time.Duration(rand.Int63n(int64(wiggle)))
   895  
   896  		log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
   897  	}
   898  	// Sign all the things!
   899  	sighash, err := signFn(accounts.Account{Address: val}, accounts.MimetypePOSA, POSARLP(header))
   900  	if err != nil {
   901  		return err
   902  	}
   903  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   904  	// Wait until sealing is terminated or delay timeout.
   905  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   906  	go func() {
   907  		select {
   908  		case <-stop:
   909  			return
   910  		case <-time.After(delay):
   911  		}
   912  
   913  		select {
   914  		case results <- block.WithSeal(header):
   915  		default:
   916  			log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header))
   917  		}
   918  	}()
   919  
   920  	return nil
   921  }
   922  
   923  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   924  // that a new block should have:
   925  // * DIFF_NOTURN(2) if BLOCK_NUMBER % validator_COUNT != validator_INDEX
   926  // * DIFF_INTURN(1) if BLOCK_NUMBER % validator_COUNT == validator_INDEX
   927  func (c *POSA) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   928  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   929  	if err != nil {
   930  		return nil
   931  	}
   932  	return calcDifficulty(snap, c.validator)
   933  }
   934  
   935  func calcDifficulty(snap *Snapshot, validator common.Address) *big.Int {
   936  	if snap.inturn(snap.Number+1, validator) {
   937  		return new(big.Int).Set(diffInTurn)
   938  	}
   939  	return new(big.Int).Set(diffNoTurn)
   940  }
   941  
   942  // SealHash returns the hash of a block prior to it being sealed.
   943  func (c *POSA) SealHash(header *types.Header) common.Hash {
   944  	return SealHash(header)
   945  }
   946  
   947  // Close implements consensus.Engine. It's a noop for POSA as there are no background threads.
   948  func (c *POSA) Close() error {
   949  	return nil
   950  }
   951  
   952  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   953  // controlling the validator voting.
   954  func (c *POSA) APIs(chain consensus.ChainHeaderReader) []rpc.API {
   955  	return []rpc.API{{
   956  		Namespace: "posa",
   957  		Version:   "1.0",
   958  		Service:   &API{chain: chain, posa: c},
   959  		Public:    false,
   960  	}}
   961  }
   962  
   963  // SealHash returns the hash of a block prior to it being sealed.
   964  func SealHash(header *types.Header) (hash common.Hash) {
   965  	hasher := sha3.NewLegacyKeccak256()
   966  	encodeSigHeader(hasher, header)
   967  	hasher.Sum(hash[:0])
   968  	return hash
   969  }
   970  
   971  // POSARLP returns the rlp bytes which needs to be signed for the proof-of-stake-authority
   972  // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
   973  // contained at the end of the extra data.
   974  //
   975  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   976  // panics. This is done to avoid accidentally using both forms (signature present
   977  // or not), which could be abused to produce different hashes for the same header.
   978  func POSARLP(header *types.Header) []byte {
   979  	b := new(bytes.Buffer)
   980  	encodeSigHeader(b, header)
   981  	return b.Bytes()
   982  }
   983  
   984  func encodeSigHeader(w io.Writer, header *types.Header) {
   985  	err := rlp.Encode(w, []interface{}{
   986  		header.ParentHash,
   987  		header.UncleHash,
   988  		header.Coinbase,
   989  		header.Root,
   990  		header.TxHash,
   991  		header.ReceiptHash,
   992  		header.Bloom,
   993  		header.Difficulty,
   994  		header.Number,
   995  		header.GasLimit,
   996  		header.GasUsed,
   997  		header.Time,
   998  		header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short
   999  		header.MixDigest,
  1000  		header.Nonce,
  1001  	})
  1002  	if err != nil {
  1003  		panic("can't encode: " + err.Error())
  1004  	}
  1005  }