github.com/phillinzzz/newBsc@v1.1.6/consensus/parlia/parlia.go (about)

     1  package parlia
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/hex"
     7  	"errors"
     8  	"fmt"
     9  	"io"
    10  	"math"
    11  	"math/big"
    12  	"math/rand"
    13  	"sort"
    14  	"strings"
    15  	"sync"
    16  	"time"
    17  
    18  	lru "github.com/hashicorp/golang-lru"
    19  	"golang.org/x/crypto/sha3"
    20  
    21  	"github.com/phillinzzz/newBsc"
    22  	"github.com/phillinzzz/newBsc/accounts"
    23  	"github.com/phillinzzz/newBsc/accounts/abi"
    24  	"github.com/phillinzzz/newBsc/common"
    25  	"github.com/phillinzzz/newBsc/common/gopool"
    26  	"github.com/phillinzzz/newBsc/common/hexutil"
    27  	"github.com/phillinzzz/newBsc/consensus"
    28  	"github.com/phillinzzz/newBsc/consensus/misc"
    29  	"github.com/phillinzzz/newBsc/core"
    30  	"github.com/phillinzzz/newBsc/core/forkid"
    31  	"github.com/phillinzzz/newBsc/core/state"
    32  	"github.com/phillinzzz/newBsc/core/systemcontracts"
    33  	"github.com/phillinzzz/newBsc/core/types"
    34  	"github.com/phillinzzz/newBsc/core/vm"
    35  	"github.com/phillinzzz/newBsc/crypto"
    36  	"github.com/phillinzzz/newBsc/ethdb"
    37  	"github.com/phillinzzz/newBsc/internal/ethapi"
    38  	"github.com/phillinzzz/newBsc/log"
    39  	"github.com/phillinzzz/newBsc/params"
    40  	"github.com/phillinzzz/newBsc/rlp"
    41  	"github.com/phillinzzz/newBsc/rpc"
    42  	"github.com/phillinzzz/newBsc/trie"
    43  )
    44  
    45  const (
    46  	inMemorySnapshots  = 128  // Number of recent snapshots to keep in memory
    47  	inMemorySignatures = 4096 // Number of recent block signatures to keep in memory
    48  
    49  	checkpointInterval = 1024        // Number of blocks after which to save the snapshot to the database
    50  	defaultEpochLength = uint64(100) // Default number of blocks of checkpoint to update validatorSet from contract
    51  
    52  	extraVanity      = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity
    53  	extraSeal        = 65 // Fixed number of extra-data suffix bytes reserved for signer seal
    54  	nextForkHashSize = 4  // Fixed number of extra-data suffix bytes reserved for nextForkHash.
    55  
    56  	validatorBytesLength = common.AddressLength
    57  	wiggleTime           = uint64(1) // second, Random delay (per signer) to allow concurrent signers
    58  	initialBackOffTime   = uint64(1) // second
    59  	processBackOffTime   = uint64(1) // second
    60  
    61  	systemRewardPercent = 4 // it means 1/2^4 = 1/16 percentage of gas fee incoming will be distributed to system
    62  
    63  )
    64  
    65  var (
    66  	uncleHash  = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW.
    67  	diffInTurn = big.NewInt(2)            // Block difficulty for in-turn signatures
    68  	diffNoTurn = big.NewInt(1)            // Block difficulty for out-of-turn signatures
    69  	// 100 native token
    70  	maxSystemBalance = new(big.Int).Mul(big.NewInt(100), big.NewInt(params.Ether))
    71  
    72  	systemContracts = map[common.Address]bool{
    73  		common.HexToAddress(systemcontracts.ValidatorContract):          true,
    74  		common.HexToAddress(systemcontracts.SlashContract):              true,
    75  		common.HexToAddress(systemcontracts.SystemRewardContract):       true,
    76  		common.HexToAddress(systemcontracts.LightClientContract):        true,
    77  		common.HexToAddress(systemcontracts.RelayerHubContract):         true,
    78  		common.HexToAddress(systemcontracts.GovHubContract):             true,
    79  		common.HexToAddress(systemcontracts.TokenHubContract):           true,
    80  		common.HexToAddress(systemcontracts.RelayerIncentivizeContract): true,
    81  		common.HexToAddress(systemcontracts.CrossChainContract):         true,
    82  	}
    83  )
    84  
    85  // Various error messages to mark blocks invalid. These should be private to
    86  // prevent engine specific errors from being referenced in the remainder of the
    87  // codebase, inherently breaking if the engine is swapped out. Please put common
    88  // error types into the consensus package.
    89  var (
    90  	// errUnknownBlock is returned when the list of validators is requested for a block
    91  	// that is not part of the local blockchain.
    92  	errUnknownBlock = errors.New("unknown block")
    93  
    94  	// errMissingVanity is returned if a block's extra-data section is shorter than
    95  	// 32 bytes, which is required to store the signer vanity.
    96  	errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
    97  
    98  	// errMissingSignature is returned if a block's extra-data section doesn't seem
    99  	// to contain a 65 byte secp256k1 signature.
   100  	errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
   101  
   102  	// errExtraValidators is returned if non-sprint-end block contain validator data in
   103  	// their extra-data fields.
   104  	errExtraValidators = errors.New("non-sprint-end block contains extra validator list")
   105  
   106  	// errInvalidSpanValidators is returned if a block contains an
   107  	// invalid list of validators (i.e. non divisible by 20 bytes).
   108  	errInvalidSpanValidators = errors.New("invalid validator list on sprint end 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  	// errMismatchingEpochValidators is returned if a sprint block contains a
   117  	// list of validators different than the one the local node calculated.
   118  	errMismatchingEpochValidators = errors.New("mismatching validator list on epoch block")
   119  
   120  	// errInvalidDifficulty is returned if the difficulty of a block is missing.
   121  	errInvalidDifficulty = errors.New("invalid difficulty")
   122  
   123  	// errWrongDifficulty is returned if the difficulty of a block doesn't match the
   124  	// turn of the signer.
   125  	errWrongDifficulty = errors.New("wrong difficulty")
   126  
   127  	// errOutOfRangeChain is returned if an authorization list is attempted to
   128  	// be modified via out-of-range or non-contiguous headers.
   129  	errOutOfRangeChain = errors.New("out of range or non-contiguous chain")
   130  
   131  	// errBlockHashInconsistent is returned if an authorization list is attempted to
   132  	// insert an inconsistent block.
   133  	errBlockHashInconsistent = errors.New("the block hash is inconsistent")
   134  
   135  	// errUnauthorizedValidator is returned if a header is signed by a non-authorized entity.
   136  	errUnauthorizedValidator = errors.New("unauthorized validator")
   137  
   138  	// errCoinBaseMisMatch is returned if a header's coinbase do not match with signature
   139  	errCoinBaseMisMatch = errors.New("coinbase do not match with signature")
   140  
   141  	// errRecentlySigned is returned if a header is signed by an authorized entity
   142  	// that already signed a header recently, thus is temporarily not allowed to.
   143  	errRecentlySigned = errors.New("recently signed")
   144  )
   145  
   146  // SignerFn is a signer callback function to request a header to be signed by a
   147  // backing account.
   148  type SignerFn func(accounts.Account, string, []byte) ([]byte, error)
   149  type SignerTxFn func(accounts.Account, *types.Transaction, *big.Int) (*types.Transaction, error)
   150  
   151  func isToSystemContract(to common.Address) bool {
   152  	return systemContracts[to]
   153  }
   154  
   155  // ecrecover extracts the Ethereum account address from a signed header.
   156  func ecrecover(header *types.Header, sigCache *lru.ARCCache, chainId *big.Int) (common.Address, error) {
   157  	// If the signature's already cached, return that
   158  	hash := header.Hash()
   159  	if address, known := sigCache.Get(hash); known {
   160  		return address.(common.Address), nil
   161  	}
   162  	// Retrieve the signature from the header extra-data
   163  	if len(header.Extra) < extraSeal {
   164  		return common.Address{}, errMissingSignature
   165  	}
   166  	signature := header.Extra[len(header.Extra)-extraSeal:]
   167  
   168  	// Recover the public key and the Ethereum address
   169  	pubkey, err := crypto.Ecrecover(SealHash(header, chainId).Bytes(), signature)
   170  	if err != nil {
   171  		return common.Address{}, err
   172  	}
   173  	var signer common.Address
   174  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
   175  
   176  	sigCache.Add(hash, signer)
   177  	return signer, nil
   178  }
   179  
   180  // ParliaRLP returns the rlp bytes which needs to be signed for the parlia
   181  // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
   182  // contained at the end of the extra data.
   183  //
   184  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   185  // panics. This is done to avoid accidentally using both forms (signature present
   186  // or not), which could be abused to produce different hashes for the same header.
   187  func ParliaRLP(header *types.Header, chainId *big.Int) []byte {
   188  	b := new(bytes.Buffer)
   189  	encodeSigHeader(b, header, chainId)
   190  	return b.Bytes()
   191  }
   192  
   193  // Parlia is the consensus engine of BSC
   194  type Parlia struct {
   195  	chainConfig *params.ChainConfig  // Chain config
   196  	config      *params.ParliaConfig // Consensus engine configuration parameters for parlia consensus
   197  	genesisHash common.Hash
   198  	db          ethdb.Database // Database to store and retrieve snapshot checkpoints
   199  
   200  	recentSnaps *lru.ARCCache // Snapshots for recent block to speed up
   201  	signatures  *lru.ARCCache // Signatures of recent blocks to speed up mining
   202  
   203  	signer types.Signer
   204  
   205  	val      common.Address // Ethereum address of the signing key
   206  	signFn   SignerFn       // Signer function to authorize hashes with
   207  	signTxFn SignerTxFn
   208  
   209  	lock sync.RWMutex // Protects the signer fields
   210  
   211  	ethAPI          *ethapi.PublicBlockChainAPI
   212  	validatorSetABI abi.ABI
   213  	slashABI        abi.ABI
   214  
   215  	// The fields below are for testing only
   216  	fakeDiff bool // Skip difficulty verifications
   217  }
   218  
   219  // New creates a Parlia consensus engine.
   220  func New(
   221  	chainConfig *params.ChainConfig,
   222  	db ethdb.Database,
   223  	ethAPI *ethapi.PublicBlockChainAPI,
   224  	genesisHash common.Hash,
   225  ) *Parlia {
   226  	// get parlia config
   227  	parliaConfig := chainConfig.Parlia
   228  
   229  	// Set any missing consensus parameters to their defaults
   230  	if parliaConfig != nil && parliaConfig.Epoch == 0 {
   231  		parliaConfig.Epoch = defaultEpochLength
   232  	}
   233  
   234  	// Allocate the snapshot caches and create the engine
   235  	recentSnaps, err := lru.NewARC(inMemorySnapshots)
   236  	if err != nil {
   237  		panic(err)
   238  	}
   239  	signatures, err := lru.NewARC(inMemorySignatures)
   240  	if err != nil {
   241  		panic(err)
   242  	}
   243  	vABI, err := abi.JSON(strings.NewReader(validatorSetABI))
   244  	if err != nil {
   245  		panic(err)
   246  	}
   247  	sABI, err := abi.JSON(strings.NewReader(slashABI))
   248  	if err != nil {
   249  		panic(err)
   250  	}
   251  	c := &Parlia{
   252  		chainConfig:     chainConfig,
   253  		config:          parliaConfig,
   254  		genesisHash:     genesisHash,
   255  		db:              db,
   256  		ethAPI:          ethAPI,
   257  		recentSnaps:     recentSnaps,
   258  		signatures:      signatures,
   259  		validatorSetABI: vABI,
   260  		slashABI:        sABI,
   261  		signer:          types.NewEIP155Signer(chainConfig.ChainID),
   262  	}
   263  
   264  	return c
   265  }
   266  
   267  func (p *Parlia) IsSystemTransaction(tx *types.Transaction, header *types.Header) (bool, error) {
   268  	// deploy a contract
   269  	if tx.To() == nil {
   270  		return false, nil
   271  	}
   272  	sender, err := types.Sender(p.signer, tx)
   273  	if err != nil {
   274  		return false, errors.New("UnAuthorized transaction")
   275  	}
   276  	if sender == header.Coinbase && isToSystemContract(*tx.To()) && tx.GasPrice().Cmp(big.NewInt(0)) == 0 {
   277  		return true, nil
   278  	}
   279  	return false, nil
   280  }
   281  
   282  func (p *Parlia) IsSystemContract(to *common.Address) bool {
   283  	if to == nil {
   284  		return false
   285  	}
   286  	return isToSystemContract(*to)
   287  }
   288  
   289  // Author implements consensus.Engine, returning the SystemAddress
   290  func (p *Parlia) Author(header *types.Header) (common.Address, error) {
   291  	return header.Coinbase, nil
   292  }
   293  
   294  // VerifyHeader checks whether a header conforms to the consensus rules.
   295  func (p *Parlia) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
   296  	return p.verifyHeader(chain, header, nil)
   297  }
   298  
   299  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   300  // method returns a quit channel to abort the operations and a results channel to
   301  // retrieve the async verifications (the order is that of the input slice).
   302  func (p *Parlia) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   303  	abort := make(chan struct{})
   304  	results := make(chan error, len(headers))
   305  
   306  	gopool.Submit(func() {
   307  		for i, header := range headers {
   308  			err := p.verifyHeader(chain, header, headers[:i])
   309  
   310  			select {
   311  			case <-abort:
   312  				return
   313  			case results <- err:
   314  			}
   315  		}
   316  	})
   317  	return abort, results
   318  }
   319  
   320  // verifyHeader checks whether a header conforms to the consensus rules.The
   321  // caller may optionally pass in a batch of parents (ascending order) to avoid
   322  // looking those up from the database. This is useful for concurrently verifying
   323  // a batch of new headers.
   324  func (p *Parlia) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   325  	if header.Number == nil {
   326  		return errUnknownBlock
   327  	}
   328  	number := header.Number.Uint64()
   329  
   330  	// Don't waste time checking blocks from the future
   331  	if header.Time > uint64(time.Now().Unix()) {
   332  		return consensus.ErrFutureBlock
   333  	}
   334  	// Check that the extra-data contains the vanity, validators and signature.
   335  	if len(header.Extra) < extraVanity {
   336  		return errMissingVanity
   337  	}
   338  	if len(header.Extra) < extraVanity+extraSeal {
   339  		return errMissingSignature
   340  	}
   341  	// check extra data
   342  	isEpoch := number%p.config.Epoch == 0
   343  
   344  	// Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
   345  	signersBytes := len(header.Extra) - extraVanity - extraSeal
   346  	if !isEpoch && signersBytes != 0 {
   347  		return errExtraValidators
   348  	}
   349  
   350  	if isEpoch && signersBytes%validatorBytesLength != 0 {
   351  		return errInvalidSpanValidators
   352  	}
   353  
   354  	// Ensure that the mix digest is zero as we don't have fork protection currently
   355  	if header.MixDigest != (common.Hash{}) {
   356  		return errInvalidMixDigest
   357  	}
   358  	// Ensure that the block doesn't contain any uncles which are meaningless in PoA
   359  	if header.UncleHash != uncleHash {
   360  		return errInvalidUncleHash
   361  	}
   362  	// Ensure that the block's difficulty is meaningful (may not be correct at this point)
   363  	if number > 0 {
   364  		if header.Difficulty == nil {
   365  			return errInvalidDifficulty
   366  		}
   367  	}
   368  	// If all checks passed, validate any special fields for hard forks
   369  	if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
   370  		return err
   371  	}
   372  	// All basic checks passed, verify cascading fields
   373  	return p.verifyCascadingFields(chain, header, parents)
   374  }
   375  
   376  // verifyCascadingFields verifies all the header fields that are not standalone,
   377  // rather depend on a batch of previous headers. The caller may optionally pass
   378  // in a batch of parents (ascending order) to avoid looking those up from the
   379  // database. This is useful for concurrently verifying a batch of new headers.
   380  func (p *Parlia) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   381  	// The genesis block is the always valid dead-end
   382  	number := header.Number.Uint64()
   383  	if number == 0 {
   384  		return nil
   385  	}
   386  
   387  	var parent *types.Header
   388  	if len(parents) > 0 {
   389  		parent = parents[len(parents)-1]
   390  	} else {
   391  		parent = chain.GetHeader(header.ParentHash, number-1)
   392  	}
   393  
   394  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   395  		return consensus.ErrUnknownAncestor
   396  	}
   397  
   398  	snap, err := p.snapshot(chain, number-1, header.ParentHash, parents)
   399  	if err != nil {
   400  		return err
   401  	}
   402  
   403  	err = p.blockTimeVerifyForRamanujanFork(snap, header, parent)
   404  	if err != nil {
   405  		return err
   406  	}
   407  
   408  	// Verify that the gas limit is <= 2^63-1
   409  	capacity := uint64(0x7fffffffffffffff)
   410  	if header.GasLimit > capacity {
   411  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, capacity)
   412  	}
   413  	// Verify that the gasUsed is <= gasLimit
   414  	if header.GasUsed > header.GasLimit {
   415  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   416  	}
   417  
   418  	// Verify that the gas limit remains within allowed bounds
   419  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   420  	if diff < 0 {
   421  		diff *= -1
   422  	}
   423  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   424  
   425  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   426  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   427  	}
   428  
   429  	// All basic checks passed, verify the seal and return
   430  	return p.verifySeal(chain, header, parents)
   431  }
   432  
   433  // snapshot retrieves the authorization snapshot at a given point in time.
   434  func (p *Parlia) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   435  	// Search for a snapshot in memory or on disk for checkpoints
   436  	var (
   437  		headers []*types.Header
   438  		snap    *Snapshot
   439  	)
   440  
   441  	for snap == nil {
   442  		// If an in-memory snapshot was found, use that
   443  		if s, ok := p.recentSnaps.Get(hash); ok {
   444  			snap = s.(*Snapshot)
   445  			break
   446  		}
   447  
   448  		// If an on-disk checkpoint snapshot can be found, use that
   449  		if number%checkpointInterval == 0 {
   450  			if s, err := loadSnapshot(p.config, p.signatures, p.db, hash, p.ethAPI); err == nil {
   451  				log.Trace("Loaded snapshot from disk", "number", number, "hash", hash)
   452  				snap = s
   453  				break
   454  			}
   455  		}
   456  
   457  		// If we're at the genesis, snapshot the initial state.
   458  		if number == 0 {
   459  			checkpoint := chain.GetHeaderByNumber(number)
   460  			if checkpoint != nil {
   461  				// get checkpoint data
   462  				hash := checkpoint.Hash()
   463  
   464  				validatorBytes := checkpoint.Extra[extraVanity : len(checkpoint.Extra)-extraSeal]
   465  				// get validators from headers
   466  				validators, err := ParseValidators(validatorBytes)
   467  				if err != nil {
   468  					return nil, err
   469  				}
   470  
   471  				// new snap shot
   472  				snap = newSnapshot(p.config, p.signatures, number, hash, validators, p.ethAPI)
   473  				if err := snap.store(p.db); err != nil {
   474  					return nil, err
   475  				}
   476  				log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash)
   477  				break
   478  			}
   479  		}
   480  
   481  		// No snapshot for this header, gather the header and move backward
   482  		var header *types.Header
   483  		if len(parents) > 0 {
   484  			// If we have explicit parents, pick from there (enforced)
   485  			header = parents[len(parents)-1]
   486  			if header.Hash() != hash || header.Number.Uint64() != number {
   487  				return nil, consensus.ErrUnknownAncestor
   488  			}
   489  			parents = parents[:len(parents)-1]
   490  		} else {
   491  			// No explicit parents (or no more left), reach out to the database
   492  			header = chain.GetHeader(hash, number)
   493  			if header == nil {
   494  				return nil, consensus.ErrUnknownAncestor
   495  			}
   496  		}
   497  		headers = append(headers, header)
   498  		number, hash = number-1, header.ParentHash
   499  	}
   500  
   501  	// check if snapshot is nil
   502  	if snap == nil {
   503  		return nil, fmt.Errorf("unknown error while retrieving snapshot at block number %v", number)
   504  	}
   505  
   506  	// Previous snapshot found, apply any pending headers on top of it
   507  	for i := 0; i < len(headers)/2; i++ {
   508  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   509  	}
   510  
   511  	snap, err := snap.apply(headers, chain, parents, p.chainConfig.ChainID)
   512  	if err != nil {
   513  		return nil, err
   514  	}
   515  	p.recentSnaps.Add(snap.Hash, snap)
   516  
   517  	// If we've generated a new checkpoint snapshot, save to disk
   518  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   519  		if err = snap.store(p.db); err != nil {
   520  			return nil, err
   521  		}
   522  		log.Trace("Stored snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   523  	}
   524  	return snap, err
   525  }
   526  
   527  // VerifyUncles implements consensus.Engine, always returning an error for any
   528  // uncles as this consensus mechanism doesn't permit uncles.
   529  func (p *Parlia) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   530  	if len(block.Uncles()) > 0 {
   531  		return errors.New("uncles not allowed")
   532  	}
   533  	return nil
   534  }
   535  
   536  // VerifySeal implements consensus.Engine, checking whether the signature contained
   537  // in the header satisfies the consensus protocol requirements.
   538  func (p *Parlia) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   539  	return p.verifySeal(chain, header, nil)
   540  }
   541  
   542  // verifySeal checks whether the signature contained in the header satisfies the
   543  // consensus protocol requirements. The method accepts an optional list of parent
   544  // headers that aren't yet part of the local blockchain to generate the snapshots
   545  // from.
   546  func (p *Parlia) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   547  	// Verifying the genesis block is not supported
   548  	number := header.Number.Uint64()
   549  	if number == 0 {
   550  		return errUnknownBlock
   551  	}
   552  	// Retrieve the snapshot needed to verify this header and cache it
   553  	snap, err := p.snapshot(chain, number-1, header.ParentHash, parents)
   554  	if err != nil {
   555  		return err
   556  	}
   557  
   558  	// Resolve the authorization key and check against validators
   559  	signer, err := ecrecover(header, p.signatures, p.chainConfig.ChainID)
   560  	if err != nil {
   561  		return err
   562  	}
   563  
   564  	if signer != header.Coinbase {
   565  		return errCoinBaseMisMatch
   566  	}
   567  
   568  	if _, ok := snap.Validators[signer]; !ok {
   569  		return errUnauthorizedValidator
   570  	}
   571  
   572  	for seen, recent := range snap.Recents {
   573  		if recent == signer {
   574  			// Signer is among recents, only fail if the current block doesn't shift it out
   575  			if limit := uint64(len(snap.Validators)/2 + 1); seen > number-limit {
   576  				return errRecentlySigned
   577  			}
   578  		}
   579  	}
   580  
   581  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   582  	if !p.fakeDiff {
   583  		inturn := snap.inturn(signer)
   584  		if inturn && header.Difficulty.Cmp(diffInTurn) != 0 {
   585  			return errWrongDifficulty
   586  		}
   587  		if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 {
   588  			return errWrongDifficulty
   589  		}
   590  	}
   591  
   592  	return nil
   593  }
   594  
   595  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   596  // header for running the transactions on top.
   597  func (p *Parlia) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   598  	header.Coinbase = p.val
   599  	header.Nonce = types.BlockNonce{}
   600  
   601  	number := header.Number.Uint64()
   602  	snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
   603  	if err != nil {
   604  		return err
   605  	}
   606  
   607  	// Set the correct difficulty
   608  	header.Difficulty = CalcDifficulty(snap, p.val)
   609  
   610  	// Ensure the extra data has all it's components
   611  	if len(header.Extra) < extraVanity-nextForkHashSize {
   612  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-nextForkHashSize-len(header.Extra))...)
   613  	}
   614  	header.Extra = header.Extra[:extraVanity-nextForkHashSize]
   615  	nextForkHash := forkid.NextForkHash(p.chainConfig, p.genesisHash, number)
   616  	header.Extra = append(header.Extra, nextForkHash[:]...)
   617  
   618  	if number%p.config.Epoch == 0 {
   619  		newValidators, err := p.getCurrentValidators(header.ParentHash)
   620  		if err != nil {
   621  			return err
   622  		}
   623  		// sort validator by address
   624  		sort.Sort(validatorsAscending(newValidators))
   625  		for _, validator := range newValidators {
   626  			header.Extra = append(header.Extra, validator.Bytes()...)
   627  		}
   628  	}
   629  
   630  	// add extra seal space
   631  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   632  
   633  	// Mix digest is reserved for now, set to empty
   634  	header.MixDigest = common.Hash{}
   635  
   636  	// Ensure the timestamp has the correct delay
   637  	parent := chain.GetHeader(header.ParentHash, number-1)
   638  	if parent == nil {
   639  		return consensus.ErrUnknownAncestor
   640  	}
   641  	header.Time = p.blockTimeForRamanujanFork(snap, header, parent)
   642  	if header.Time < uint64(time.Now().Unix()) {
   643  		header.Time = uint64(time.Now().Unix())
   644  	}
   645  	return nil
   646  }
   647  
   648  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   649  // rewards given.
   650  func (p *Parlia) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs *[]*types.Transaction,
   651  	uncles []*types.Header, receipts *[]*types.Receipt, systemTxs *[]*types.Transaction, usedGas *uint64) error {
   652  	// warn if not in majority fork
   653  	number := header.Number.Uint64()
   654  	snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
   655  	if err != nil {
   656  		return err
   657  	}
   658  	nextForkHash := forkid.NextForkHash(p.chainConfig, p.genesisHash, number)
   659  	if !snap.isMajorityFork(hex.EncodeToString(nextForkHash[:])) {
   660  		log.Debug("there is a possible fork, and your client is not the majority. Please check...", "nextForkHash", hex.EncodeToString(nextForkHash[:]))
   661  	}
   662  	// If the block is a epoch end block, verify the validator list
   663  	// The verification can only be done when the state is ready, it can't be done in VerifyHeader.
   664  	if header.Number.Uint64()%p.config.Epoch == 0 {
   665  		newValidators, err := p.getCurrentValidators(header.ParentHash)
   666  		if err != nil {
   667  			return err
   668  		}
   669  		// sort validator by address
   670  		sort.Sort(validatorsAscending(newValidators))
   671  		validatorsBytes := make([]byte, len(newValidators)*validatorBytesLength)
   672  		for i, validator := range newValidators {
   673  			copy(validatorsBytes[i*validatorBytesLength:], validator.Bytes())
   674  		}
   675  
   676  		extraSuffix := len(header.Extra) - extraSeal
   677  		if !bytes.Equal(header.Extra[extraVanity:extraSuffix], validatorsBytes) {
   678  			return errMismatchingEpochValidators
   679  		}
   680  	}
   681  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   682  	cx := chainContext{Chain: chain, parlia: p}
   683  	if header.Number.Cmp(common.Big1) == 0 {
   684  		err := p.initContract(state, header, cx, txs, receipts, systemTxs, usedGas, false)
   685  		if err != nil {
   686  			log.Error("init contract failed")
   687  		}
   688  	}
   689  	if header.Difficulty.Cmp(diffInTurn) != 0 {
   690  		spoiledVal := snap.supposeValidator()
   691  		signedRecently := false
   692  		for _, recent := range snap.Recents {
   693  			if recent == spoiledVal {
   694  				signedRecently = true
   695  				break
   696  			}
   697  		}
   698  		if !signedRecently {
   699  			log.Trace("slash validator", "block hash", header.Hash(), "address", spoiledVal)
   700  			err = p.slash(spoiledVal, state, header, cx, txs, receipts, systemTxs, usedGas, false)
   701  			if err != nil {
   702  				// it is possible that slash validator failed because of the slash channel is disabled.
   703  				log.Error("slash validator failed", "block hash", header.Hash(), "address", spoiledVal)
   704  			}
   705  		}
   706  	}
   707  	val := header.Coinbase
   708  	err = p.distributeIncoming(val, state, header, cx, txs, receipts, systemTxs, usedGas, false)
   709  	if err != nil {
   710  		return err
   711  	}
   712  	if len(*systemTxs) > 0 {
   713  		return errors.New("the length of systemTxs do not match")
   714  	}
   715  	return nil
   716  }
   717  
   718  // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
   719  // nor block rewards given, and returns the final block.
   720  func (p *Parlia) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB,
   721  	txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, []*types.Receipt, error) {
   722  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   723  	cx := chainContext{Chain: chain, parlia: p}
   724  	if txs == nil {
   725  		txs = make([]*types.Transaction, 0)
   726  	}
   727  	if receipts == nil {
   728  		receipts = make([]*types.Receipt, 0)
   729  	}
   730  	if header.Number.Cmp(common.Big1) == 0 {
   731  		err := p.initContract(state, header, cx, &txs, &receipts, nil, &header.GasUsed, true)
   732  		if err != nil {
   733  			log.Error("init contract failed")
   734  		}
   735  	}
   736  	if header.Difficulty.Cmp(diffInTurn) != 0 {
   737  		number := header.Number.Uint64()
   738  		snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
   739  		if err != nil {
   740  			return nil, nil, err
   741  		}
   742  		spoiledVal := snap.supposeValidator()
   743  		signedRecently := false
   744  		for _, recent := range snap.Recents {
   745  			if recent == spoiledVal {
   746  				signedRecently = true
   747  				break
   748  			}
   749  		}
   750  		if !signedRecently {
   751  			err = p.slash(spoiledVal, state, header, cx, &txs, &receipts, nil, &header.GasUsed, true)
   752  			if err != nil {
   753  				// it is possible that slash validator failed because of the slash channel is disabled.
   754  				log.Error("slash validator failed", "block hash", header.Hash(), "address", spoiledVal)
   755  			}
   756  		}
   757  	}
   758  	err := p.distributeIncoming(p.val, state, header, cx, &txs, &receipts, nil, &header.GasUsed, true)
   759  	if err != nil {
   760  		return nil, nil, err
   761  	}
   762  	// should not happen. Once happen, stop the node is better than broadcast the block
   763  	if header.GasLimit < header.GasUsed {
   764  		return nil, nil, errors.New("gas consumption of system txs exceed the gas limit")
   765  	}
   766  	header.UncleHash = types.CalcUncleHash(nil)
   767  	var blk *types.Block
   768  	var rootHash common.Hash
   769  	wg := sync.WaitGroup{}
   770  	wg.Add(2)
   771  	go func() {
   772  		rootHash = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   773  		wg.Done()
   774  	}()
   775  	go func() {
   776  		blk = types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil))
   777  		wg.Done()
   778  	}()
   779  	wg.Wait()
   780  	blk.SetRoot(rootHash)
   781  	// Assemble and return the final block for sealing
   782  	return blk, receipts, nil
   783  }
   784  
   785  // Authorize injects a private key into the consensus engine to mint new blocks
   786  // with.
   787  func (p *Parlia) Authorize(val common.Address, signFn SignerFn, signTxFn SignerTxFn) {
   788  	p.lock.Lock()
   789  	defer p.lock.Unlock()
   790  
   791  	p.val = val
   792  	p.signFn = signFn
   793  	p.signTxFn = signTxFn
   794  }
   795  
   796  func (p *Parlia) Delay(chain consensus.ChainReader, header *types.Header) *time.Duration {
   797  	number := header.Number.Uint64()
   798  	snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
   799  	if err != nil {
   800  		return nil
   801  	}
   802  	delay := p.delayForRamanujanFork(snap, header)
   803  	// The blocking time should be no more than half of period
   804  	half := time.Duration(p.config.Period) * time.Second / 2
   805  	if delay > half {
   806  		delay = half
   807  	}
   808  	return &delay
   809  }
   810  
   811  // Seal implements consensus.Engine, attempting to create a sealed block using
   812  // the local signing credentials.
   813  func (p *Parlia) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
   814  	header := block.Header()
   815  
   816  	// Sealing the genesis block is not supported
   817  	number := header.Number.Uint64()
   818  	if number == 0 {
   819  		return errUnknownBlock
   820  	}
   821  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   822  	if p.config.Period == 0 && len(block.Transactions()) == 0 {
   823  		log.Info("Sealing paused, waiting for transactions")
   824  		return nil
   825  	}
   826  	// Don't hold the val fields for the entire sealing procedure
   827  	p.lock.RLock()
   828  	val, signFn := p.val, p.signFn
   829  	p.lock.RUnlock()
   830  
   831  	snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
   832  	if err != nil {
   833  		return err
   834  	}
   835  
   836  	// Bail out if we're unauthorized to sign a block
   837  	if _, authorized := snap.Validators[val]; !authorized {
   838  		return errUnauthorizedValidator
   839  	}
   840  
   841  	// If we're amongst the recent signers, wait for the next block
   842  	for seen, recent := range snap.Recents {
   843  		if recent == val {
   844  			// Signer is among recents, only wait if the current block doesn't shift it out
   845  			if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
   846  				log.Info("Signed recently, must wait for others")
   847  				return nil
   848  			}
   849  		}
   850  	}
   851  
   852  	// Sweet, the protocol permits us to sign the block, wait for our time
   853  	delay := p.delayForRamanujanFork(snap, header)
   854  
   855  	log.Info("Sealing block with", "number", number, "delay", delay, "headerDifficulty", header.Difficulty, "val", val.Hex())
   856  
   857  	// Sign all the things!
   858  	sig, err := signFn(accounts.Account{Address: val}, accounts.MimetypeParlia, ParliaRLP(header, p.chainConfig.ChainID))
   859  	if err != nil {
   860  		return err
   861  	}
   862  	copy(header.Extra[len(header.Extra)-extraSeal:], sig)
   863  
   864  	// Wait until sealing is terminated or delay timeout.
   865  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   866  	go func() {
   867  		select {
   868  		case <-stop:
   869  			return
   870  		case <-time.After(delay):
   871  		}
   872  		if p.shouldWaitForCurrentBlockProcess(chain, header, snap) {
   873  			log.Info("Waiting for received in turn block to process")
   874  			select {
   875  			case <-stop:
   876  				log.Info("Received block process finished, abort block seal")
   877  				return
   878  			case <-time.After(time.Duration(processBackOffTime) * time.Second):
   879  				log.Info("Process backoff time exhausted, start to seal block")
   880  			}
   881  		}
   882  
   883  		select {
   884  		case results <- block.WithSeal(header):
   885  		default:
   886  			log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header, p.chainConfig.ChainID))
   887  		}
   888  	}()
   889  
   890  	return nil
   891  }
   892  
   893  func (p *Parlia) shouldWaitForCurrentBlockProcess(chain consensus.ChainHeaderReader, header *types.Header, snap *Snapshot) bool {
   894  	if header.Difficulty.Cmp(diffInTurn) == 0 {
   895  		return false
   896  	}
   897  
   898  	highestVerifiedHeader := chain.GetHighestVerifiedHeader()
   899  	if highestVerifiedHeader == nil {
   900  		return false
   901  	}
   902  
   903  	if header.ParentHash == highestVerifiedHeader.ParentHash {
   904  		return true
   905  	}
   906  	return false
   907  }
   908  
   909  func (p *Parlia) EnoughDistance(chain consensus.ChainReader, header *types.Header) bool {
   910  	snap, err := p.snapshot(chain, header.Number.Uint64()-1, header.ParentHash, nil)
   911  	if err != nil {
   912  		return true
   913  	}
   914  	return snap.enoughDistance(p.val, header)
   915  }
   916  
   917  func (p *Parlia) AllowLightProcess(chain consensus.ChainReader, currentHeader *types.Header) bool {
   918  	snap, err := p.snapshot(chain, currentHeader.Number.Uint64()-1, currentHeader.ParentHash, nil)
   919  	if err != nil {
   920  		return true
   921  	}
   922  
   923  	idx := snap.indexOfVal(p.val)
   924  	// validator is not allowed to diff sync
   925  	return idx < 0
   926  }
   927  
   928  func (p *Parlia) IsLocalBlock(header *types.Header) bool {
   929  	return p.val == header.Coinbase
   930  }
   931  
   932  func (p *Parlia) SignRecently(chain consensus.ChainReader, parent *types.Header) (bool, error) {
   933  	snap, err := p.snapshot(chain, parent.Number.Uint64(), parent.ParentHash, nil)
   934  	if err != nil {
   935  		return true, err
   936  	}
   937  
   938  	// Bail out if we're unauthorized to sign a block
   939  	if _, authorized := snap.Validators[p.val]; !authorized {
   940  		return true, errUnauthorizedValidator
   941  	}
   942  
   943  	// If we're amongst the recent signers, wait for the next block
   944  	number := parent.Number.Uint64() + 1
   945  	for seen, recent := range snap.Recents {
   946  		if recent == p.val {
   947  			// Signer is among recents, only wait if the current block doesn't shift it out
   948  			if limit := uint64(len(snap.Validators)/2 + 1); number < limit || seen > number-limit {
   949  				return true, nil
   950  			}
   951  		}
   952  	}
   953  	return false, nil
   954  }
   955  
   956  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   957  // that a new block should have based on the previous blocks in the chain and the
   958  // current signer.
   959  func (p *Parlia) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   960  	snap, err := p.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   961  	if err != nil {
   962  		return nil
   963  	}
   964  	return CalcDifficulty(snap, p.val)
   965  }
   966  
   967  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   968  // that a new block should have based on the previous blocks in the chain and the
   969  // current signer.
   970  func CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
   971  	if snap.inturn(signer) {
   972  		return new(big.Int).Set(diffInTurn)
   973  	}
   974  	return new(big.Int).Set(diffNoTurn)
   975  }
   976  
   977  // SealHash returns the hash of a block prior to it being sealed.
   978  func (p *Parlia) SealHash(header *types.Header) common.Hash {
   979  	return SealHash(header, p.chainConfig.ChainID)
   980  }
   981  
   982  // APIs implements consensus.Engine, returning the user facing RPC API to query snapshot.
   983  func (p *Parlia) APIs(chain consensus.ChainHeaderReader) []rpc.API {
   984  	return []rpc.API{{
   985  		Namespace: "parlia",
   986  		Version:   "1.0",
   987  		Service:   &API{chain: chain, parlia: p},
   988  		Public:    false,
   989  	}}
   990  }
   991  
   992  // Close implements consensus.Engine. It's a noop for parlia as there are no background threads.
   993  func (p *Parlia) Close() error {
   994  	return nil
   995  }
   996  
   997  // ==========================  interaction with contract/account =========
   998  
   999  // getCurrentValidators get current validators
  1000  func (p *Parlia) getCurrentValidators(blockHash common.Hash) ([]common.Address, error) {
  1001  	// block
  1002  	blockNr := rpc.BlockNumberOrHashWithHash(blockHash, false)
  1003  
  1004  	// method
  1005  	method := "getValidators"
  1006  
  1007  	ctx, cancel := context.WithCancel(context.Background())
  1008  	defer cancel() // cancel when we are finished consuming integers
  1009  
  1010  	data, err := p.validatorSetABI.Pack(method)
  1011  	if err != nil {
  1012  		log.Error("Unable to pack tx for getValidators", "error", err)
  1013  		return nil, err
  1014  	}
  1015  	// call
  1016  	msgData := (hexutil.Bytes)(data)
  1017  	toAddress := common.HexToAddress(systemcontracts.ValidatorContract)
  1018  	gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2))
  1019  	result, err := p.ethAPI.Call(ctx, ethapi.CallArgs{
  1020  		Gas:  &gas,
  1021  		To:   &toAddress,
  1022  		Data: &msgData,
  1023  	}, blockNr, nil)
  1024  	if err != nil {
  1025  		return nil, err
  1026  	}
  1027  
  1028  	var (
  1029  		ret0 = new([]common.Address)
  1030  	)
  1031  	out := ret0
  1032  
  1033  	if err := p.validatorSetABI.UnpackIntoInterface(out, method, result); err != nil {
  1034  		return nil, err
  1035  	}
  1036  
  1037  	valz := make([]common.Address, len(*ret0))
  1038  	for i, a := range *ret0 {
  1039  		valz[i] = a
  1040  	}
  1041  	return valz, nil
  1042  }
  1043  
  1044  // slash spoiled validators
  1045  func (p *Parlia) distributeIncoming(val common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
  1046  	txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  1047  	coinbase := header.Coinbase
  1048  	balance := state.GetBalance(consensus.SystemAddress)
  1049  	if balance.Cmp(common.Big0) <= 0 {
  1050  		return nil
  1051  	}
  1052  	state.SetBalance(consensus.SystemAddress, big.NewInt(0))
  1053  	state.AddBalance(coinbase, balance)
  1054  
  1055  	doDistributeSysReward := state.GetBalance(common.HexToAddress(systemcontracts.SystemRewardContract)).Cmp(maxSystemBalance) < 0
  1056  	if doDistributeSysReward {
  1057  		var rewards = new(big.Int)
  1058  		rewards = rewards.Rsh(balance, systemRewardPercent)
  1059  		if rewards.Cmp(common.Big0) > 0 {
  1060  			err := p.distributeToSystem(rewards, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  1061  			if err != nil {
  1062  				return err
  1063  			}
  1064  			log.Trace("distribute to system reward pool", "block hash", header.Hash(), "amount", rewards)
  1065  			balance = balance.Sub(balance, rewards)
  1066  		}
  1067  	}
  1068  	log.Trace("distribute to validator contract", "block hash", header.Hash(), "amount", balance)
  1069  	return p.distributeToValidator(balance, val, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  1070  }
  1071  
  1072  // slash spoiled validators
  1073  func (p *Parlia) slash(spoiledVal common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
  1074  	txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  1075  	// method
  1076  	method := "slash"
  1077  
  1078  	// get packed data
  1079  	data, err := p.slashABI.Pack(method,
  1080  		spoiledVal,
  1081  	)
  1082  	if err != nil {
  1083  		log.Error("Unable to pack tx for slash", "error", err)
  1084  		return err
  1085  	}
  1086  	// get system message
  1087  	msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.SlashContract), data, common.Big0)
  1088  	// apply message
  1089  	return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  1090  }
  1091  
  1092  // init contract
  1093  func (p *Parlia) initContract(state *state.StateDB, header *types.Header, chain core.ChainContext,
  1094  	txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  1095  	// method
  1096  	method := "init"
  1097  	// contracts
  1098  	contracts := []string{
  1099  		systemcontracts.ValidatorContract,
  1100  		systemcontracts.SlashContract,
  1101  		systemcontracts.LightClientContract,
  1102  		systemcontracts.RelayerHubContract,
  1103  		systemcontracts.TokenHubContract,
  1104  		systemcontracts.RelayerIncentivizeContract,
  1105  		systemcontracts.CrossChainContract,
  1106  	}
  1107  	// get packed data
  1108  	data, err := p.validatorSetABI.Pack(method)
  1109  	if err != nil {
  1110  		log.Error("Unable to pack tx for init validator set", "error", err)
  1111  		return err
  1112  	}
  1113  	for _, c := range contracts {
  1114  		msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(c), data, common.Big0)
  1115  		// apply message
  1116  		log.Trace("init contract", "block hash", header.Hash(), "contract", c)
  1117  		err = p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  1118  		if err != nil {
  1119  			return err
  1120  		}
  1121  	}
  1122  	return nil
  1123  }
  1124  
  1125  func (p *Parlia) distributeToSystem(amount *big.Int, state *state.StateDB, header *types.Header, chain core.ChainContext,
  1126  	txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  1127  	// get system message
  1128  	msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.SystemRewardContract), nil, amount)
  1129  	// apply message
  1130  	return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  1131  }
  1132  
  1133  // slash spoiled validators
  1134  func (p *Parlia) distributeToValidator(amount *big.Int, validator common.Address,
  1135  	state *state.StateDB, header *types.Header, chain core.ChainContext,
  1136  	txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
  1137  	// method
  1138  	method := "deposit"
  1139  
  1140  	// get packed data
  1141  	data, err := p.validatorSetABI.Pack(method,
  1142  		validator,
  1143  	)
  1144  	if err != nil {
  1145  		log.Error("Unable to pack tx for deposit", "error", err)
  1146  		return err
  1147  	}
  1148  	// get system message
  1149  	msg := p.getSystemMessage(header.Coinbase, common.HexToAddress(systemcontracts.ValidatorContract), data, amount)
  1150  	// apply message
  1151  	return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
  1152  }
  1153  
  1154  // get system message
  1155  func (p *Parlia) getSystemMessage(from, toAddress common.Address, data []byte, value *big.Int) callmsg {
  1156  	return callmsg{
  1157  		ethereum.CallMsg{
  1158  			From:     from,
  1159  			Gas:      math.MaxUint64 / 2,
  1160  			GasPrice: big.NewInt(0),
  1161  			Value:    value,
  1162  			To:       &toAddress,
  1163  			Data:     data,
  1164  		},
  1165  	}
  1166  }
  1167  
  1168  func (p *Parlia) applyTransaction(
  1169  	msg callmsg,
  1170  	state *state.StateDB,
  1171  	header *types.Header,
  1172  	chainContext core.ChainContext,
  1173  	txs *[]*types.Transaction, receipts *[]*types.Receipt,
  1174  	receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool,
  1175  ) (err error) {
  1176  	nonce := state.GetNonce(msg.From())
  1177  	expectedTx := types.NewTransaction(nonce, *msg.To(), msg.Value(), msg.Gas(), msg.GasPrice(), msg.Data())
  1178  	expectedHash := p.signer.Hash(expectedTx)
  1179  
  1180  	if msg.From() == p.val && mining {
  1181  		expectedTx, err = p.signTxFn(accounts.Account{Address: msg.From()}, expectedTx, p.chainConfig.ChainID)
  1182  		if err != nil {
  1183  			return err
  1184  		}
  1185  	} else {
  1186  		if receivedTxs == nil || len(*receivedTxs) == 0 || (*receivedTxs)[0] == nil {
  1187  			return errors.New("supposed to get a actual transaction, but get none")
  1188  		}
  1189  		actualTx := (*receivedTxs)[0]
  1190  		if !bytes.Equal(p.signer.Hash(actualTx).Bytes(), expectedHash.Bytes()) {
  1191  			return fmt.Errorf("expected tx hash %v, get %v, nonce %d, to %s, value %s, gas %d, gasPrice %s, data %s", expectedHash.String(), actualTx.Hash().String(),
  1192  				expectedTx.Nonce(),
  1193  				expectedTx.To().String(),
  1194  				expectedTx.Value().String(),
  1195  				expectedTx.Gas(),
  1196  				expectedTx.GasPrice().String(),
  1197  				hex.EncodeToString(expectedTx.Data()),
  1198  			)
  1199  		}
  1200  		expectedTx = actualTx
  1201  		// move to next
  1202  		*receivedTxs = (*receivedTxs)[1:]
  1203  	}
  1204  	state.Prepare(expectedTx.Hash(), common.Hash{}, len(*txs))
  1205  	gasUsed, err := applyMessage(msg, state, header, p.chainConfig, chainContext)
  1206  	if err != nil {
  1207  		return err
  1208  	}
  1209  	*txs = append(*txs, expectedTx)
  1210  	var root []byte
  1211  	if p.chainConfig.IsByzantium(header.Number) {
  1212  		state.Finalise(true)
  1213  	} else {
  1214  		root = state.IntermediateRoot(p.chainConfig.IsEIP158(header.Number)).Bytes()
  1215  	}
  1216  	*usedGas += gasUsed
  1217  	receipt := types.NewReceipt(root, false, *usedGas)
  1218  	receipt.TxHash = expectedTx.Hash()
  1219  	receipt.GasUsed = gasUsed
  1220  
  1221  	// Set the receipt logs and create a bloom for filtering
  1222  	receipt.Logs = state.GetLogs(expectedTx.Hash())
  1223  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  1224  	receipt.BlockHash = state.BlockHash()
  1225  	receipt.BlockNumber = header.Number
  1226  	receipt.TransactionIndex = uint(state.TxIndex())
  1227  	*receipts = append(*receipts, receipt)
  1228  	state.SetNonce(msg.From(), nonce+1)
  1229  	return nil
  1230  }
  1231  
  1232  // ===========================     utility function        ==========================
  1233  // SealHash returns the hash of a block prior to it being sealed.
  1234  func SealHash(header *types.Header, chainId *big.Int) (hash common.Hash) {
  1235  	hasher := sha3.NewLegacyKeccak256()
  1236  	encodeSigHeader(hasher, header, chainId)
  1237  	hasher.Sum(hash[:0])
  1238  	return hash
  1239  }
  1240  
  1241  func encodeSigHeader(w io.Writer, header *types.Header, chainId *big.Int) {
  1242  	err := rlp.Encode(w, []interface{}{
  1243  		chainId,
  1244  		header.ParentHash,
  1245  		header.UncleHash,
  1246  		header.Coinbase,
  1247  		header.Root,
  1248  		header.TxHash,
  1249  		header.ReceiptHash,
  1250  		header.Bloom,
  1251  		header.Difficulty,
  1252  		header.Number,
  1253  		header.GasLimit,
  1254  		header.GasUsed,
  1255  		header.Time,
  1256  		header.Extra[:len(header.Extra)-65], // this will panic if extra is too short, should check before calling encodeSigHeader
  1257  		header.MixDigest,
  1258  		header.Nonce,
  1259  	})
  1260  	if err != nil {
  1261  		panic("can't encode: " + err.Error())
  1262  	}
  1263  }
  1264  
  1265  func backOffTime(snap *Snapshot, val common.Address) uint64 {
  1266  	if snap.inturn(val) {
  1267  		return 0
  1268  	} else {
  1269  		idx := snap.indexOfVal(val)
  1270  		if idx < 0 {
  1271  			// The backOffTime does not matter when a validator is not authorized.
  1272  			return 0
  1273  		}
  1274  		s := rand.NewSource(int64(snap.Number))
  1275  		r := rand.New(s)
  1276  		n := len(snap.Validators)
  1277  		backOffSteps := make([]uint64, 0, n)
  1278  		for idx := uint64(0); idx < uint64(n); idx++ {
  1279  			backOffSteps = append(backOffSteps, idx)
  1280  		}
  1281  		r.Shuffle(n, func(i, j int) {
  1282  			backOffSteps[i], backOffSteps[j] = backOffSteps[j], backOffSteps[i]
  1283  		})
  1284  		delay := initialBackOffTime + backOffSteps[idx]*wiggleTime
  1285  		return delay
  1286  	}
  1287  }
  1288  
  1289  // chain context
  1290  type chainContext struct {
  1291  	Chain  consensus.ChainHeaderReader
  1292  	parlia consensus.Engine
  1293  }
  1294  
  1295  func (c chainContext) Engine() consensus.Engine {
  1296  	return c.parlia
  1297  }
  1298  
  1299  func (c chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  1300  	return c.Chain.GetHeader(hash, number)
  1301  }
  1302  
  1303  // callmsg implements core.Message to allow passing it as a transaction simulator.
  1304  type callmsg struct {
  1305  	ethereum.CallMsg
  1306  }
  1307  
  1308  func (m callmsg) From() common.Address { return m.CallMsg.From }
  1309  func (m callmsg) Nonce() uint64        { return 0 }
  1310  func (m callmsg) CheckNonce() bool     { return false }
  1311  func (m callmsg) To() *common.Address  { return m.CallMsg.To }
  1312  func (m callmsg) GasPrice() *big.Int   { return m.CallMsg.GasPrice }
  1313  func (m callmsg) Gas() uint64          { return m.CallMsg.Gas }
  1314  func (m callmsg) Value() *big.Int      { return m.CallMsg.Value }
  1315  func (m callmsg) Data() []byte         { return m.CallMsg.Data }
  1316  
  1317  // apply message
  1318  func applyMessage(
  1319  	msg callmsg,
  1320  	state *state.StateDB,
  1321  	header *types.Header,
  1322  	chainConfig *params.ChainConfig,
  1323  	chainContext core.ChainContext,
  1324  ) (uint64, error) {
  1325  	// Create a new context to be used in the EVM environment
  1326  	context := core.NewEVMBlockContext(header, chainContext, nil)
  1327  	// Create a new environment which holds all relevant information
  1328  	// about the transaction and calling mechanisms.
  1329  	vmenv := vm.NewEVM(context, vm.TxContext{Origin: msg.From(), GasPrice: big.NewInt(0)}, state, chainConfig, vm.Config{})
  1330  	// Apply the transaction to the current state (included in the env)
  1331  	ret, returnGas, err := vmenv.Call(
  1332  		vm.AccountRef(msg.From()),
  1333  		*msg.To(),
  1334  		msg.Data(),
  1335  		msg.Gas(),
  1336  		msg.Value(),
  1337  	)
  1338  	if err != nil {
  1339  		log.Error("apply message failed", "msg", string(ret), "err", err)
  1340  	}
  1341  	return msg.Gas() - returnGas, err
  1342  }