github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/consensus/bor/bor.go (about)

     1  package bor
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/hex"
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"io"
    11  	"math"
    12  	"math/big"
    13  	"sort"
    14  	"strconv"
    15  	"strings"
    16  	"sync"
    17  	"time"
    18  
    19  	lru "github.com/hashicorp/golang-lru"
    20  	"golang.org/x/crypto/sha3"
    21  
    22  	ethereum "github.com/ethereum/go-ethereum"
    23  	"github.com/ethereum/go-ethereum/accounts"
    24  	"github.com/ethereum/go-ethereum/accounts/abi"
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/common/hexutil"
    27  	"github.com/ethereum/go-ethereum/consensus"
    28  	"github.com/ethereum/go-ethereum/consensus/misc"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/state"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/core/vm"
    33  	"github.com/ethereum/go-ethereum/crypto"
    34  	"github.com/ethereum/go-ethereum/ethdb"
    35  	"github.com/ethereum/go-ethereum/event"
    36  	"github.com/ethereum/go-ethereum/internal/ethapi"
    37  	"github.com/ethereum/go-ethereum/log"
    38  	"github.com/ethereum/go-ethereum/params"
    39  	"github.com/ethereum/go-ethereum/rlp"
    40  	"github.com/ethereum/go-ethereum/rpc"
    41  	"github.com/ethereum/go-ethereum/trie"
    42  )
    43  
    44  const (
    45  	checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database
    46  	inmemorySnapshots  = 128  // Number of recent vote snapshots to keep in memory
    47  	inmemorySignatures = 4096 // Number of recent block signatures to keep in memory
    48  )
    49  
    50  // Bor protocol constants.
    51  var (
    52  	defaultSprintLength = uint64(64) // Default number of blocks after which to checkpoint and reset the pending votes
    53  
    54  	extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity
    55  	extraSeal   = 65 // Fixed number of extra-data suffix bytes reserved for signer seal
    56  
    57  	uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW.
    58  
    59  	diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures
    60  	diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures
    61  
    62  	validatorHeaderBytesLength = common.AddressLength + 20 // address + power
    63  	systemAddress              = common.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE")
    64  )
    65  
    66  // Various error messages to mark blocks invalid. These should be private to
    67  // prevent engine specific errors from being referenced in the remainder of the
    68  // codebase, inherently breaking if the engine is swapped out. Please put common
    69  // error types into the consensus package.
    70  var (
    71  	// errUnknownBlock is returned when the list of signers is requested for a block
    72  	// that is not part of the local blockchain.
    73  	errUnknownBlock = errors.New("unknown block")
    74  
    75  	// errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition
    76  	// block has a beneficiary set to non-zeroes.
    77  	errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero")
    78  
    79  	// errInvalidVote is returned if a nonce value is something else that the two
    80  	// allowed constants of 0x00..0 or 0xff..f.
    81  	errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f")
    82  
    83  	// errInvalidCheckpointVote is returned if a checkpoint/epoch transition block
    84  	// has a vote nonce set to non-zeroes.
    85  	errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero")
    86  
    87  	// errMissingVanity is returned if a block's extra-data section is shorter than
    88  	// 32 bytes, which is required to store the signer vanity.
    89  	errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
    90  
    91  	// errMissingSignature is returned if a block's extra-data section doesn't seem
    92  	// to contain a 65 byte secp256k1 signature.
    93  	errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
    94  
    95  	// errExtraValidators is returned if non-sprint-end block contain validator data in
    96  	// their extra-data fields.
    97  	errExtraValidators = errors.New("non-sprint-end block contains extra validator list")
    98  
    99  	// errInvalidSpanValidators is returned if a block contains an
   100  	// invalid list of validators (i.e. non divisible by 40 bytes).
   101  	errInvalidSpanValidators = errors.New("invalid validator list on sprint end block")
   102  
   103  	// errInvalidMixDigest is returned if a block's mix digest is non-zero.
   104  	errInvalidMixDigest = errors.New("non-zero mix digest")
   105  
   106  	// errInvalidUncleHash is returned if a block contains an non-empty uncle list.
   107  	errInvalidUncleHash = errors.New("non empty uncle hash")
   108  
   109  	// errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2.
   110  	errInvalidDifficulty = errors.New("invalid difficulty")
   111  
   112  	// ErrInvalidTimestamp is returned if the timestamp of a block is lower than
   113  	// the previous block's timestamp + the minimum block period.
   114  	ErrInvalidTimestamp = errors.New("invalid timestamp")
   115  
   116  	// errOutOfRangeChain is returned if an authorization list is attempted to
   117  	// be modified via out-of-range or non-contiguous headers.
   118  	errOutOfRangeChain = errors.New("out of range or non-contiguous chain")
   119  )
   120  
   121  // SignerFn is a signer callback function to request a header to be signed by a
   122  // backing account.
   123  type SignerFn func(accounts.Account, string, []byte) ([]byte, error)
   124  
   125  // ecrecover extracts the Ethereum account address from a signed header.
   126  func ecrecover(header *types.Header, sigcache *lru.ARCCache, c *params.BorConfig) (common.Address, error) {
   127  	// If the signature's already cached, return that
   128  	hash := header.Hash()
   129  	if address, known := sigcache.Get(hash); known {
   130  		return address.(common.Address), nil
   131  	}
   132  	// Retrieve the signature from the header extra-data
   133  	if len(header.Extra) < extraSeal {
   134  		return common.Address{}, errMissingSignature
   135  	}
   136  	signature := header.Extra[len(header.Extra)-extraSeal:]
   137  
   138  	// Recover the public key and the Ethereum address
   139  	pubkey, err := crypto.Ecrecover(SealHash(header, c).Bytes(), signature)
   140  	if err != nil {
   141  		return common.Address{}, err
   142  	}
   143  	var signer common.Address
   144  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
   145  
   146  	sigcache.Add(hash, signer)
   147  	return signer, nil
   148  }
   149  
   150  // SealHash returns the hash of a block prior to it being sealed.
   151  func SealHash(header *types.Header, c *params.BorConfig) (hash common.Hash) {
   152  	hasher := sha3.NewLegacyKeccak256()
   153  	encodeSigHeader(hasher, header, c)
   154  	hasher.Sum(hash[:0])
   155  	return hash
   156  }
   157  
   158  func encodeSigHeader(w io.Writer, header *types.Header, c *params.BorConfig) {
   159  	enc := []interface{}{
   160  		header.ParentHash,
   161  		header.UncleHash,
   162  		header.Coinbase,
   163  		header.Root,
   164  		header.TxHash,
   165  		header.ReceiptHash,
   166  		header.Bloom,
   167  		header.Difficulty,
   168  		header.Number,
   169  		header.GasLimit,
   170  		header.GasUsed,
   171  		header.Time,
   172  		header.Extra[:len(header.Extra)-65], // Yes, this will panic if extra is too short
   173  		header.MixDigest,
   174  		header.Nonce,
   175  	}
   176  	if c.IsJaipur(header.Number.Uint64()) {
   177  		if header.BaseFee != nil {
   178  			enc = append(enc, header.BaseFee)
   179  		}
   180  	}
   181  	if err := rlp.Encode(w, enc); err != nil {
   182  		panic("can't encode: " + err.Error())
   183  	}
   184  }
   185  
   186  // CalcProducerDelay is the block delay algorithm based on block time, period, producerDelay and turn-ness of a signer
   187  func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint64 {
   188  	// When the block is the first block of the sprint, it is expected to be delayed by `producerDelay`.
   189  	// That is to allow time for block propagation in the last sprint
   190  	delay := c.CalculatePeriod(number)
   191  	if number%c.Sprint == 0 {
   192  		delay = c.ProducerDelay
   193  	}
   194  	if succession > 0 {
   195  		delay += uint64(succession) * c.CalculateBackupMultiplier(number)
   196  	}
   197  	return delay
   198  }
   199  
   200  // BorRLP returns the rlp bytes which needs to be signed for the bor
   201  // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
   202  // contained at the end of the extra data.
   203  //
   204  // Note, the method requires the extra data to be at least 65 bytes, otherwise it
   205  // panics. This is done to avoid accidentally using both forms (signature present
   206  // or not), which could be abused to produce different hashes for the same header.
   207  func BorRLP(header *types.Header, c *params.BorConfig) []byte {
   208  	b := new(bytes.Buffer)
   209  	encodeSigHeader(b, header, c)
   210  	return b.Bytes()
   211  }
   212  
   213  // Bor is the matic-bor consensus engine
   214  type Bor struct {
   215  	chainConfig *params.ChainConfig // Chain config
   216  	config      *params.BorConfig   // Consensus engine configuration parameters for bor consensus
   217  	db          ethdb.Database      // Database to store and retrieve snapshot checkpoints
   218  
   219  	recents    *lru.ARCCache // Snapshots for recent block to speed up reorgs
   220  	signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
   221  
   222  	signer common.Address // Ethereum address of the signing key
   223  	signFn SignerFn       // Signer function to authorize hashes with
   224  	lock   sync.RWMutex   // Protects the signer fields
   225  
   226  	ethAPI                 *ethapi.PublicBlockChainAPI
   227  	GenesisContractsClient *GenesisContractsClient
   228  	validatorSetABI        abi.ABI
   229  	stateReceiverABI       abi.ABI
   230  	HeimdallClient         IHeimdallClient
   231  	WithoutHeimdall        bool
   232  
   233  	scope event.SubscriptionScope
   234  	// The fields below are for testing only
   235  	fakeDiff bool // Skip difficulty verifications
   236  }
   237  
   238  // New creates a Matic Bor consensus engine.
   239  func New(
   240  	chainConfig *params.ChainConfig,
   241  	db ethdb.Database,
   242  	ethAPI *ethapi.PublicBlockChainAPI,
   243  	heimdallURL string,
   244  	withoutHeimdall bool,
   245  ) *Bor {
   246  	// get bor config
   247  	borConfig := chainConfig.Bor
   248  
   249  	// Set any missing consensus parameters to their defaults
   250  	if borConfig != nil && borConfig.Sprint == 0 {
   251  		borConfig.Sprint = defaultSprintLength
   252  	}
   253  
   254  	// Allocate the snapshot caches and create the engine
   255  	recents, _ := lru.NewARC(inmemorySnapshots)
   256  	signatures, _ := lru.NewARC(inmemorySignatures)
   257  	vABI, _ := abi.JSON(strings.NewReader(validatorsetABI))
   258  	sABI, _ := abi.JSON(strings.NewReader(stateReceiverABI))
   259  	heimdallClient, _ := NewHeimdallClient(heimdallURL)
   260  	genesisContractsClient := NewGenesisContractsClient(chainConfig, borConfig.ValidatorContract, borConfig.StateReceiverContract, ethAPI)
   261  	c := &Bor{
   262  		chainConfig:            chainConfig,
   263  		config:                 borConfig,
   264  		db:                     db,
   265  		ethAPI:                 ethAPI,
   266  		recents:                recents,
   267  		signatures:             signatures,
   268  		validatorSetABI:        vABI,
   269  		stateReceiverABI:       sABI,
   270  		GenesisContractsClient: genesisContractsClient,
   271  		HeimdallClient:         heimdallClient,
   272  		WithoutHeimdall:        withoutHeimdall,
   273  	}
   274  
   275  	// make sure we can decode all the GenesisAlloc in the BorConfig.
   276  	for key, genesisAlloc := range c.config.BlockAlloc {
   277  		if _, err := decodeGenesisAlloc(genesisAlloc); err != nil {
   278  			panic(fmt.Sprintf("BUG: Block alloc '%s' in genesis is not correct: %v", key, err))
   279  		}
   280  	}
   281  
   282  	return c
   283  }
   284  
   285  // Author implements consensus.Engine, returning the Ethereum address recovered
   286  // from the signature in the header's extra-data section.
   287  func (c *Bor) Author(header *types.Header) (common.Address, error) {
   288  	return ecrecover(header, c.signatures, c.config)
   289  }
   290  
   291  // VerifyHeader checks whether a header conforms to the consensus rules.
   292  func (c *Bor) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
   293  	return c.verifyHeader(chain, header, nil)
   294  }
   295  
   296  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
   297  // method returns a quit channel to abort the operations and a results channel to
   298  // retrieve the async verifications (the order is that of the input slice).
   299  func (c *Bor) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   300  	abort := make(chan struct{})
   301  	results := make(chan error, len(headers))
   302  
   303  	go func() {
   304  		for i, header := range headers {
   305  			err := c.verifyHeader(chain, header, headers[:i])
   306  
   307  			select {
   308  			case <-abort:
   309  				return
   310  			case results <- err:
   311  			}
   312  		}
   313  	}()
   314  	return abort, results
   315  }
   316  
   317  // verifyHeader checks whether a header conforms to the consensus rules.The
   318  // caller may optionally pass in a batch of parents (ascending order) to avoid
   319  // looking those up from the database. This is useful for concurrently verifying
   320  // a batch of new headers.
   321  func (c *Bor) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   322  	if header.Number == nil {
   323  		return errUnknownBlock
   324  	}
   325  	number := header.Number.Uint64()
   326  
   327  	// Don't waste time checking blocks from the future
   328  	if header.Time > uint64(time.Now().Unix()) {
   329  		return consensus.ErrFutureBlock
   330  	}
   331  
   332  	if err := validateHeaderExtraField(header.Extra); err != nil {
   333  		return err
   334  	}
   335  
   336  	// check extr adata
   337  	isSprintEnd := (number+1)%c.config.Sprint == 0
   338  
   339  	// Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
   340  	signersBytes := len(header.Extra) - extraVanity - extraSeal
   341  	if !isSprintEnd && signersBytes != 0 {
   342  		return errExtraValidators
   343  	}
   344  	if isSprintEnd && signersBytes%validatorHeaderBytesLength != 0 {
   345  		return errInvalidSpanValidators
   346  	}
   347  	// Ensure that the mix digest is zero as we don't have fork protection currently
   348  	if header.MixDigest != (common.Hash{}) {
   349  		return errInvalidMixDigest
   350  	}
   351  	// Ensure that the block doesn't contain any uncles which are meaningless in PoA
   352  	if header.UncleHash != uncleHash {
   353  		return errInvalidUncleHash
   354  	}
   355  	// Ensure that the block's difficulty is meaningful (may not be correct at this point)
   356  	if number > 0 {
   357  		if header.Difficulty == nil {
   358  			return errInvalidDifficulty
   359  		}
   360  	}
   361  	// Verify that the gas limit is <= 2^63-1
   362  	cap := uint64(0x7fffffffffffffff)
   363  	if header.GasLimit > cap {
   364  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   365  	}
   366  	// If all checks passed, validate any special fields for hard forks
   367  	if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
   368  		return err
   369  	}
   370  	// All basic checks passed, verify cascading fields
   371  	return c.verifyCascadingFields(chain, header, parents)
   372  }
   373  
   374  // validateHeaderExtraField validates that the extra-data contains both the vanity and signature.
   375  // header.Extra = header.Vanity + header.ProducerBytes (optional) + header.Seal
   376  func validateHeaderExtraField(extraBytes []byte) error {
   377  	if len(extraBytes) < extraVanity {
   378  		return errMissingVanity
   379  	}
   380  	if len(extraBytes) < extraVanity+extraSeal {
   381  		return errMissingSignature
   382  	}
   383  	return nil
   384  }
   385  
   386  // verifyCascadingFields verifies all the header fields that are not standalone,
   387  // rather depend on a batch of previous headers. The caller may optionally pass
   388  // in a batch of parents (ascending order) to avoid looking those up from the
   389  // database. This is useful for concurrently verifying a batch of new headers.
   390  func (c *Bor) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   391  	// The genesis block is the always valid dead-end
   392  	number := header.Number.Uint64()
   393  	if number == 0 {
   394  		return nil
   395  	}
   396  
   397  	// Ensure that the block's timestamp isn't too close to it's parent
   398  	var parent *types.Header
   399  	if len(parents) > 0 {
   400  		parent = parents[len(parents)-1]
   401  	} else {
   402  		parent = chain.GetHeader(header.ParentHash, number-1)
   403  	}
   404  
   405  	if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
   406  		return consensus.ErrUnknownAncestor
   407  	}
   408  
   409  	// Verify that the gasUsed is <= gasLimit
   410  	if header.GasUsed > header.GasLimit {
   411  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   412  	}
   413  	if !chain.Config().IsLondon(header.Number) {
   414  		// Verify BaseFee not present before EIP-1559 fork.
   415  		if header.BaseFee != nil {
   416  			return fmt.Errorf("invalid baseFee before fork: have %d, want <nil>", header.BaseFee)
   417  		}
   418  		if err := misc.VerifyGaslimit(parent.GasLimit, header.GasLimit); err != nil {
   419  			return err
   420  		}
   421  	} else if err := misc.VerifyEip1559Header(chain.Config(), parent, header); err != nil {
   422  		// Verify the header's EIP-1559 attributes.
   423  		return err
   424  	}
   425  
   426  	if parent.Time+c.config.CalculatePeriod(number) > header.Time {
   427  		return ErrInvalidTimestamp
   428  	}
   429  
   430  	// Retrieve the snapshot needed to verify this header and cache it
   431  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   432  	if err != nil {
   433  		return err
   434  	}
   435  
   436  	// verify the validator list in the last sprint block
   437  	if isSprintStart(number, c.config.Sprint) {
   438  		parentValidatorBytes := parent.Extra[extraVanity : len(parent.Extra)-extraSeal]
   439  		validatorsBytes := make([]byte, len(snap.ValidatorSet.Validators)*validatorHeaderBytesLength)
   440  
   441  		currentValidators := snap.ValidatorSet.Copy().Validators
   442  		// sort validator by address
   443  		sort.Sort(ValidatorsByAddress(currentValidators))
   444  		for i, validator := range currentValidators {
   445  			copy(validatorsBytes[i*validatorHeaderBytesLength:], validator.HeaderBytes())
   446  		}
   447  		// len(header.Extra) >= extraVanity+extraSeal has already been validated in validateHeaderExtraField, so this won't result in a panic
   448  		if !bytes.Equal(parentValidatorBytes, validatorsBytes) {
   449  			return &MismatchingValidatorsError{number - 1, validatorsBytes, parentValidatorBytes}
   450  		}
   451  	}
   452  
   453  	// All basic checks passed, verify the seal and return
   454  	return c.verifySeal(chain, header, parents)
   455  }
   456  
   457  // snapshot retrieves the authorization snapshot at a given point in time.
   458  func (c *Bor) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) {
   459  	// Search for a snapshot in memory or on disk for checkpoints
   460  	var (
   461  		headers []*types.Header
   462  		snap    *Snapshot
   463  	)
   464  
   465  	for snap == nil {
   466  		// If an in-memory snapshot was found, use that
   467  		if s, ok := c.recents.Get(hash); ok {
   468  			snap = s.(*Snapshot)
   469  			break
   470  		}
   471  
   472  		// If an on-disk checkpoint snapshot can be found, use that
   473  		if number%checkpointInterval == 0 {
   474  			if s, err := loadSnapshot(c.config, c.signatures, c.db, hash, c.ethAPI); err == nil {
   475  				log.Trace("Loaded snapshot from disk", "number", number, "hash", hash)
   476  				snap = s
   477  				break
   478  			}
   479  		}
   480  
   481  		// If we're at the genesis, snapshot the initial state. Alternatively if we're
   482  		// at a checkpoint block without a parent (light client CHT), or we have piled
   483  		// up more headers than allowed to be reorged (chain reinit from a freezer),
   484  		// consider the checkpoint trusted and snapshot it.
   485  		// TODO fix this
   486  		if number == 0 {
   487  			checkpoint := chain.GetHeaderByNumber(number)
   488  			if checkpoint != nil {
   489  				// get checkpoint data
   490  				hash := checkpoint.Hash()
   491  
   492  				// get validators and current span
   493  				validators, err := c.GetCurrentValidators(hash, number+1)
   494  				if err != nil {
   495  					return nil, err
   496  				}
   497  
   498  				// new snap shot
   499  				snap = newSnapshot(c.config, c.signatures, number, hash, validators, c.ethAPI)
   500  				if err := snap.store(c.db); err != nil {
   501  					return nil, err
   502  				}
   503  				log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash)
   504  				break
   505  			}
   506  		}
   507  
   508  		// No snapshot for this header, gather the header and move backward
   509  		var header *types.Header
   510  		if len(parents) > 0 {
   511  			// If we have explicit parents, pick from there (enforced)
   512  			header = parents[len(parents)-1]
   513  			if header.Hash() != hash || header.Number.Uint64() != number {
   514  				return nil, consensus.ErrUnknownAncestor
   515  			}
   516  			parents = parents[:len(parents)-1]
   517  		} else {
   518  			// No explicit parents (or no more left), reach out to the database
   519  			header = chain.GetHeader(hash, number)
   520  			if header == nil {
   521  				return nil, consensus.ErrUnknownAncestor
   522  			}
   523  		}
   524  		headers = append(headers, header)
   525  		number, hash = number-1, header.ParentHash
   526  	}
   527  
   528  	// check if snapshot is nil
   529  	if snap == nil {
   530  		return nil, fmt.Errorf("Unknown error while retrieving snapshot at block number %v", number)
   531  	}
   532  
   533  	// Previous snapshot found, apply any pending headers on top of it
   534  	for i := 0; i < len(headers)/2; i++ {
   535  		headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i]
   536  	}
   537  
   538  	snap, err := snap.apply(headers)
   539  	if err != nil {
   540  		return nil, err
   541  	}
   542  	c.recents.Add(snap.Hash, snap)
   543  
   544  	// If we've generated a new checkpoint snapshot, save to disk
   545  	if snap.Number%checkpointInterval == 0 && len(headers) > 0 {
   546  		if err = snap.store(c.db); err != nil {
   547  			return nil, err
   548  		}
   549  		log.Trace("Stored snapshot to disk", "number", snap.Number, "hash", snap.Hash)
   550  	}
   551  	return snap, err
   552  }
   553  
   554  // VerifyUncles implements consensus.Engine, always returning an error for any
   555  // uncles as this consensus mechanism doesn't permit uncles.
   556  func (c *Bor) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   557  	if len(block.Uncles()) > 0 {
   558  		return errors.New("uncles not allowed")
   559  	}
   560  	return nil
   561  }
   562  
   563  // VerifySeal implements consensus.Engine, checking whether the signature contained
   564  // in the header satisfies the consensus protocol requirements.
   565  func (c *Bor) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error {
   566  	return c.verifySeal(chain, header, nil)
   567  }
   568  
   569  // verifySeal checks whether the signature contained in the header satisfies the
   570  // consensus protocol requirements. The method accepts an optional list of parent
   571  // headers that aren't yet part of the local blockchain to generate the snapshots
   572  // from.
   573  func (c *Bor) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
   574  	// Verifying the genesis block is not supported
   575  	number := header.Number.Uint64()
   576  	if number == 0 {
   577  		return errUnknownBlock
   578  	}
   579  	// Retrieve the snapshot needed to verify this header and cache it
   580  	snap, err := c.snapshot(chain, number-1, header.ParentHash, parents)
   581  	if err != nil {
   582  		return err
   583  	}
   584  
   585  	// Resolve the authorization key and check against signers
   586  	signer, err := ecrecover(header, c.signatures, c.config)
   587  	if err != nil {
   588  		return err
   589  	}
   590  	if !snap.ValidatorSet.HasAddress(signer.Bytes()) {
   591  		// Check the UnauthorizedSignerError.Error() msg to see why we pass number-1
   592  		return &UnauthorizedSignerError{number - 1, signer.Bytes()}
   593  	}
   594  
   595  	succession, err := snap.GetSignerSuccessionNumber(signer)
   596  	if err != nil {
   597  		return err
   598  	}
   599  
   600  	var parent *types.Header
   601  	if len(parents) > 0 { // if parents is nil, len(parents) is zero
   602  		parent = parents[len(parents)-1]
   603  	} else if number > 0 {
   604  		parent = chain.GetHeader(header.ParentHash, number-1)
   605  	}
   606  
   607  	if parent != nil && header.Time < parent.Time+CalcProducerDelay(number, succession, c.config) {
   608  		return &BlockTooSoonError{number, succession}
   609  	}
   610  
   611  	// Ensure that the difficulty corresponds to the turn-ness of the signer
   612  	if !c.fakeDiff {
   613  		difficulty := snap.Difficulty(signer)
   614  		if header.Difficulty.Uint64() != difficulty {
   615  			return &WrongDifficultyError{number, difficulty, header.Difficulty.Uint64(), signer.Bytes()}
   616  		}
   617  	}
   618  
   619  	return nil
   620  }
   621  
   622  // Prepare implements consensus.Engine, preparing all the consensus fields of the
   623  // header for running the transactions on top.
   624  func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   625  	// If the block isn't a checkpoint, cast a random vote (good enough for now)
   626  	header.Coinbase = common.Address{}
   627  	header.Nonce = types.BlockNonce{}
   628  
   629  	number := header.Number.Uint64()
   630  	// Assemble the validator snapshot to check which votes make sense
   631  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   632  	if err != nil {
   633  		return err
   634  	}
   635  
   636  	// Set the correct difficulty
   637  	header.Difficulty = new(big.Int).SetUint64(snap.Difficulty(c.signer))
   638  
   639  	// Ensure the extra data has all it's components
   640  	if len(header.Extra) < extraVanity {
   641  		header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...)
   642  	}
   643  	header.Extra = header.Extra[:extraVanity]
   644  
   645  	// get validator set if number
   646  	if (number+1)%c.config.Sprint == 0 {
   647  		newValidators, err := c.GetCurrentValidators(header.ParentHash, number+1)
   648  		if err != nil {
   649  			return errors.New("unknown validators")
   650  		}
   651  
   652  		// sort validator by address
   653  		sort.Sort(ValidatorsByAddress(newValidators))
   654  		for _, validator := range newValidators {
   655  			header.Extra = append(header.Extra, validator.HeaderBytes()...)
   656  		}
   657  	}
   658  
   659  	// add extra seal space
   660  	header.Extra = append(header.Extra, make([]byte, extraSeal)...)
   661  
   662  	// Mix digest is reserved for now, set to empty
   663  	header.MixDigest = common.Hash{}
   664  
   665  	// Ensure the timestamp has the correct delay
   666  	parent := chain.GetHeader(header.ParentHash, number-1)
   667  	if parent == nil {
   668  		return consensus.ErrUnknownAncestor
   669  	}
   670  
   671  	var succession int
   672  	// if signer is not empty
   673  	if bytes.Compare(c.signer.Bytes(), common.Address{}.Bytes()) != 0 {
   674  		succession, err = snap.GetSignerSuccessionNumber(c.signer)
   675  		if err != nil {
   676  			return err
   677  		}
   678  	}
   679  
   680  	header.Time = parent.Time + CalcProducerDelay(number, succession, c.config)
   681  	if header.Time < uint64(time.Now().Unix()) {
   682  		header.Time = uint64(time.Now().Unix())
   683  	}
   684  	return nil
   685  }
   686  
   687  // Finalize implements consensus.Engine, ensuring no uncles are set, nor block
   688  // rewards given.
   689  func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
   690  	stateSyncData := []*types.StateSyncData{}
   691  
   692  	var err error
   693  	headerNumber := header.Number.Uint64()
   694  	if headerNumber%c.config.Sprint == 0 {
   695  		cx := chainContext{Chain: chain, Bor: c}
   696  		// check and commit span
   697  		if err := c.checkAndCommitSpan(state, header, cx); err != nil {
   698  			log.Error("Error while committing span", "error", err)
   699  			return
   700  		}
   701  
   702  		if !c.WithoutHeimdall {
   703  			// commit statees
   704  			stateSyncData, err = c.CommitStates(state, header, cx)
   705  			if err != nil {
   706  				log.Error("Error while committing states", "error", err)
   707  				return
   708  			}
   709  		}
   710  	}
   711  
   712  	if err = c.changeContractCodeIfNeeded(headerNumber, state); err != nil {
   713  		log.Error("Error changing contract code", "error", err)
   714  		return
   715  	}
   716  
   717  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   718  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   719  	header.UncleHash = types.CalcUncleHash(nil)
   720  
   721  	// Set state sync data to blockchain
   722  	bc := chain.(*core.BlockChain)
   723  	bc.SetStateSync(stateSyncData)
   724  }
   725  
   726  func decodeGenesisAlloc(i interface{}) (core.GenesisAlloc, error) {
   727  	var alloc core.GenesisAlloc
   728  	b, err := json.Marshal(i)
   729  	if err != nil {
   730  		return nil, err
   731  	}
   732  	if err := json.Unmarshal(b, &alloc); err != nil {
   733  		return nil, err
   734  	}
   735  	return alloc, nil
   736  }
   737  
   738  func (c *Bor) changeContractCodeIfNeeded(headerNumber uint64, state *state.StateDB) error {
   739  	for blockNumber, genesisAlloc := range c.config.BlockAlloc {
   740  		if blockNumber == strconv.FormatUint(headerNumber, 10) {
   741  			allocs, err := decodeGenesisAlloc(genesisAlloc)
   742  			if err != nil {
   743  				return fmt.Errorf("failed to decode genesis alloc: %v", err)
   744  			}
   745  			for addr, account := range allocs {
   746  				log.Info("change contract code", "address", addr)
   747  				state.SetCode(addr, account.Code)
   748  			}
   749  		}
   750  	}
   751  	return nil
   752  }
   753  
   754  // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
   755  // nor block rewards given, and returns the final block.
   756  func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
   757  	stateSyncData := []*types.StateSyncData{}
   758  
   759  	headerNumber := header.Number.Uint64()
   760  
   761  	if headerNumber%c.config.Sprint == 0 {
   762  		cx := chainContext{Chain: chain, Bor: c}
   763  
   764  		// check and commit span
   765  		err := c.checkAndCommitSpan(state, header, cx)
   766  		if err != nil {
   767  			log.Error("Error while committing span", "error", err)
   768  			return nil, err
   769  		}
   770  
   771  		if !c.WithoutHeimdall {
   772  			// commit states
   773  			stateSyncData, err = c.CommitStates(state, header, cx)
   774  			if err != nil {
   775  				log.Error("Error while committing states", "error", err)
   776  				return nil, err
   777  			}
   778  		}
   779  	}
   780  
   781  	if err := c.changeContractCodeIfNeeded(headerNumber, state); err != nil {
   782  		log.Error("Error changing contract code", "error", err)
   783  		return nil, err
   784  	}
   785  
   786  	// No block rewards in PoA, so the state remains as is and uncles are dropped
   787  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   788  	header.UncleHash = types.CalcUncleHash(nil)
   789  
   790  	// Assemble block
   791  	block := types.NewBlock(header, txs, nil, receipts, new(trie.Trie))
   792  
   793  	// set state sync
   794  	bc := chain.(*core.BlockChain)
   795  	bc.SetStateSync(stateSyncData)
   796  
   797  	// return the final block for sealing
   798  	return block, nil
   799  }
   800  
   801  // Authorize injects a private key into the consensus engine to mint new blocks
   802  // with.
   803  func (c *Bor) Authorize(signer common.Address, signFn SignerFn) {
   804  	c.lock.Lock()
   805  	defer c.lock.Unlock()
   806  
   807  	c.signer = signer
   808  	c.signFn = signFn
   809  }
   810  
   811  // Seal implements consensus.Engine, attempting to create a sealed block using
   812  // the local signing credentials.
   813  func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
   814  	header := block.Header()
   815  	// Sealing the genesis block is not supported
   816  	number := header.Number.Uint64()
   817  	if number == 0 {
   818  		return errUnknownBlock
   819  	}
   820  	// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
   821  	if c.config.CalculatePeriod(number) == 0 && len(block.Transactions()) == 0 {
   822  		log.Info("Sealing paused, waiting for transactions")
   823  		return nil
   824  	}
   825  	// Don't hold the signer fields for the entire sealing procedure
   826  	c.lock.RLock()
   827  	signer, signFn := c.signer, c.signFn
   828  	c.lock.RUnlock()
   829  
   830  	snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
   831  	if err != nil {
   832  		return err
   833  	}
   834  
   835  	// Bail out if we're unauthorized to sign a block
   836  	if !snap.ValidatorSet.HasAddress(signer.Bytes()) {
   837  		// Check the UnauthorizedSignerError.Error() msg to see why we pass number-1
   838  		return &UnauthorizedSignerError{number - 1, signer.Bytes()}
   839  	}
   840  
   841  	successionNumber, err := snap.GetSignerSuccessionNumber(signer)
   842  	if err != nil {
   843  		return err
   844  	}
   845  
   846  	// Sweet, the protocol permits us to sign the block, wait for our time
   847  	delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple
   848  	// wiggle was already accounted for in header.Time, this is just for logging
   849  	wiggle := time.Duration(successionNumber) * time.Duration(c.config.CalculateBackupMultiplier(number)) * time.Second
   850  
   851  	// Sign all the things!
   852  	sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeBor, BorRLP(header, c.config))
   853  	if err != nil {
   854  		return err
   855  	}
   856  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
   857  
   858  	// Wait until sealing is terminated or delay timeout.
   859  	log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
   860  	go func() {
   861  		select {
   862  		case <-stop:
   863  			log.Debug("Discarding sealing operation for block", "number", number)
   864  			return
   865  		case <-time.After(delay):
   866  			if wiggle > 0 {
   867  				log.Info(
   868  					"Sealing out-of-turn",
   869  					"number", number,
   870  					"wiggle", common.PrettyDuration(wiggle),
   871  					"in-turn-signer", snap.ValidatorSet.GetProposer().Address.Hex(),
   872  				)
   873  			}
   874  			log.Info(
   875  				"Sealing successful",
   876  				"number", number,
   877  				"delay", delay,
   878  				"headerDifficulty", header.Difficulty,
   879  			)
   880  		}
   881  		select {
   882  		case results <- block.WithSeal(header):
   883  		default:
   884  			log.Warn("Sealing result was not read by miner", "number", number, "sealhash", SealHash(header, c.config))
   885  		}
   886  	}()
   887  	return nil
   888  }
   889  
   890  // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
   891  // that a new block should have based on the previous blocks in the chain and the
   892  // current signer.
   893  func (c *Bor) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   894  	snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
   895  	if err != nil {
   896  		return nil
   897  	}
   898  	return new(big.Int).SetUint64(snap.Difficulty(c.signer))
   899  }
   900  
   901  // SealHash returns the hash of a block prior to it being sealed.
   902  func (c *Bor) SealHash(header *types.Header) common.Hash {
   903  	return SealHash(header, c.config)
   904  }
   905  
   906  // APIs implements consensus.Engine, returning the user facing RPC API to allow
   907  // controlling the signer voting.
   908  func (c *Bor) APIs(chain consensus.ChainHeaderReader) []rpc.API {
   909  	return []rpc.API{{
   910  		Namespace: "bor",
   911  		Version:   "1.0",
   912  		Service:   &API{chain: chain, bor: c},
   913  		Public:    false,
   914  	}}
   915  }
   916  
   917  // Close implements consensus.Engine. It's a noop for bor as there are no background threads.
   918  func (c *Bor) Close() error {
   919  	return nil
   920  }
   921  
   922  // GetCurrentSpan get current span from contract
   923  func (c *Bor) GetCurrentSpan(headerHash common.Hash) (*Span, error) {
   924  	// block
   925  	blockNr := rpc.BlockNumberOrHashWithHash(headerHash, false)
   926  
   927  	// method
   928  	method := "getCurrentSpan"
   929  
   930  	ctx, cancel := context.WithCancel(context.Background())
   931  	defer cancel()
   932  
   933  	data, err := c.validatorSetABI.Pack(method)
   934  	if err != nil {
   935  		log.Error("Unable to pack tx for getCurrentSpan", "error", err)
   936  		return nil, err
   937  	}
   938  
   939  	msgData := (hexutil.Bytes)(data)
   940  	toAddress := common.HexToAddress(c.config.ValidatorContract)
   941  	gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2))
   942  	result, err := c.ethAPI.Call(ctx, ethapi.TransactionArgs{
   943  		Gas:  &gas,
   944  		To:   &toAddress,
   945  		Data: &msgData,
   946  	}, blockNr, nil)
   947  	if err != nil {
   948  		return nil, err
   949  	}
   950  
   951  	// span result
   952  	ret := new(struct {
   953  		Number     *big.Int
   954  		StartBlock *big.Int
   955  		EndBlock   *big.Int
   956  	})
   957  	if err := c.validatorSetABI.UnpackIntoInterface(ret, method, result); err != nil {
   958  		return nil, err
   959  	}
   960  
   961  	// create new span
   962  	span := Span{
   963  		ID:         ret.Number.Uint64(),
   964  		StartBlock: ret.StartBlock.Uint64(),
   965  		EndBlock:   ret.EndBlock.Uint64(),
   966  	}
   967  
   968  	return &span, nil
   969  }
   970  
   971  // GetCurrentValidators get current validators
   972  func (c *Bor) GetCurrentValidators(headerHash common.Hash, blockNumber uint64) ([]*Validator, error) {
   973  	// block
   974  	blockNr := rpc.BlockNumberOrHashWithHash(headerHash, false)
   975  
   976  	// method
   977  	method := "getBorValidators"
   978  
   979  	ctx, cancel := context.WithCancel(context.Background())
   980  	defer cancel()
   981  
   982  	data, err := c.validatorSetABI.Pack(method, big.NewInt(0).SetUint64(blockNumber))
   983  	if err != nil {
   984  		log.Error("Unable to pack tx for getValidator", "error", err)
   985  		return nil, err
   986  	}
   987  
   988  	// call
   989  	msgData := (hexutil.Bytes)(data)
   990  	toAddress := common.HexToAddress(c.config.ValidatorContract)
   991  	gas := (hexutil.Uint64)(uint64(math.MaxUint64 / 2))
   992  	result, err := c.ethAPI.Call(ctx, ethapi.TransactionArgs{
   993  		Gas:  &gas,
   994  		To:   &toAddress,
   995  		Data: &msgData,
   996  	}, blockNr, nil)
   997  	if err != nil {
   998  		panic(err)
   999  		// return nil, err
  1000  	}
  1001  
  1002  	var (
  1003  		ret0 = new([]common.Address)
  1004  		ret1 = new([]*big.Int)
  1005  	)
  1006  	out := &[]interface{}{
  1007  		ret0,
  1008  		ret1,
  1009  	}
  1010  
  1011  	if err := c.validatorSetABI.UnpackIntoInterface(out, method, result); err != nil {
  1012  		return nil, err
  1013  	}
  1014  
  1015  	valz := make([]*Validator, len(*ret0))
  1016  	for i, a := range *ret0 {
  1017  		valz[i] = &Validator{
  1018  			Address:     a,
  1019  			VotingPower: (*ret1)[i].Int64(),
  1020  		}
  1021  	}
  1022  
  1023  	return valz, nil
  1024  }
  1025  
  1026  func (c *Bor) checkAndCommitSpan(
  1027  	state *state.StateDB,
  1028  	header *types.Header,
  1029  	chain core.ChainContext,
  1030  ) error {
  1031  	headerNumber := header.Number.Uint64()
  1032  	span, err := c.GetCurrentSpan(header.ParentHash)
  1033  	if err != nil {
  1034  		return err
  1035  	}
  1036  	if c.needToCommitSpan(span, headerNumber) {
  1037  		err := c.fetchAndCommitSpan(span.ID+1, state, header, chain)
  1038  		return err
  1039  	}
  1040  	return nil
  1041  }
  1042  
  1043  func (c *Bor) needToCommitSpan(span *Span, headerNumber uint64) bool {
  1044  	// if span is nil
  1045  	if span == nil {
  1046  		return false
  1047  	}
  1048  
  1049  	// check span is not set initially
  1050  	if span.EndBlock == 0 {
  1051  		return true
  1052  	}
  1053  
  1054  	// if current block is first block of last sprint in current span
  1055  	if span.EndBlock > c.config.Sprint && span.EndBlock-c.config.Sprint+1 == headerNumber {
  1056  		return true
  1057  	}
  1058  
  1059  	return false
  1060  }
  1061  
  1062  func (c *Bor) fetchAndCommitSpan(
  1063  	newSpanID uint64,
  1064  	state *state.StateDB,
  1065  	header *types.Header,
  1066  	chain core.ChainContext,
  1067  ) error {
  1068  	var heimdallSpan HeimdallSpan
  1069  
  1070  	if c.WithoutHeimdall {
  1071  		s, err := c.getNextHeimdallSpanForTest(newSpanID, state, header, chain)
  1072  		if err != nil {
  1073  			return err
  1074  		}
  1075  		heimdallSpan = *s
  1076  	} else {
  1077  		response, err := c.HeimdallClient.FetchWithRetry(fmt.Sprintf("bor/span/%d", newSpanID), "")
  1078  		if err != nil {
  1079  			return err
  1080  		}
  1081  
  1082  		if err := json.Unmarshal(response.Result, &heimdallSpan); err != nil {
  1083  			return err
  1084  		}
  1085  	}
  1086  
  1087  	// check if chain id matches with heimdall span
  1088  	if heimdallSpan.ChainID != c.chainConfig.ChainID.String() {
  1089  		return fmt.Errorf(
  1090  			"Chain id proposed span, %s, and bor chain id, %s, doesn't match",
  1091  			heimdallSpan.ChainID,
  1092  			c.chainConfig.ChainID,
  1093  		)
  1094  	}
  1095  
  1096  	// get validators bytes
  1097  	var validators []MinimalVal
  1098  	for _, val := range heimdallSpan.ValidatorSet.Validators {
  1099  		validators = append(validators, val.MinimalVal())
  1100  	}
  1101  	validatorBytes, err := rlp.EncodeToBytes(validators)
  1102  	if err != nil {
  1103  		return err
  1104  	}
  1105  
  1106  	// get producers bytes
  1107  	var producers []MinimalVal
  1108  	for _, val := range heimdallSpan.SelectedProducers {
  1109  		producers = append(producers, val.MinimalVal())
  1110  	}
  1111  	producerBytes, err := rlp.EncodeToBytes(producers)
  1112  	if err != nil {
  1113  		return err
  1114  	}
  1115  
  1116  	// method
  1117  	method := "commitSpan"
  1118  	log.Info("✅ Committing new span",
  1119  		"id", heimdallSpan.ID,
  1120  		"startBlock", heimdallSpan.StartBlock,
  1121  		"endBlock", heimdallSpan.EndBlock,
  1122  		"validatorBytes", hex.EncodeToString(validatorBytes),
  1123  		"producerBytes", hex.EncodeToString(producerBytes),
  1124  	)
  1125  
  1126  	// get packed data
  1127  	data, err := c.validatorSetABI.Pack(method,
  1128  		big.NewInt(0).SetUint64(heimdallSpan.ID),
  1129  		big.NewInt(0).SetUint64(heimdallSpan.StartBlock),
  1130  		big.NewInt(0).SetUint64(heimdallSpan.EndBlock),
  1131  		validatorBytes,
  1132  		producerBytes,
  1133  	)
  1134  	if err != nil {
  1135  		log.Error("Unable to pack tx for commitSpan", "error", err)
  1136  		return err
  1137  	}
  1138  
  1139  	// get system message
  1140  	msg := getSystemMessage(common.HexToAddress(c.config.ValidatorContract), data)
  1141  
  1142  	// apply message
  1143  	return applyMessage(msg, state, header, c.chainConfig, chain)
  1144  }
  1145  
  1146  // CommitStates commit states
  1147  func (c *Bor) CommitStates(
  1148  	state *state.StateDB,
  1149  	header *types.Header,
  1150  	chain chainContext,
  1151  ) ([]*types.StateSyncData, error) {
  1152  	stateSyncs := make([]*types.StateSyncData, 0)
  1153  	number := header.Number.Uint64()
  1154  	_lastStateID, err := c.GenesisContractsClient.LastStateId(number - 1)
  1155  	if err != nil {
  1156  		return nil, err
  1157  	}
  1158  
  1159  	to := time.Unix(int64(chain.Chain.GetHeaderByNumber(number-c.config.Sprint).Time), 0)
  1160  	lastStateID := _lastStateID.Uint64()
  1161  	log.Info(
  1162  		"Fetching state updates from Heimdall",
  1163  		"fromID", lastStateID+1,
  1164  		"to", to.Format(time.RFC3339))
  1165  	eventRecords, err := c.HeimdallClient.FetchStateSyncEvents(lastStateID+1, to.Unix())
  1166  	if c.config.OverrideStateSyncRecords != nil {
  1167  		if val, ok := c.config.OverrideStateSyncRecords[strconv.FormatUint(number, 10)]; ok {
  1168  			eventRecords = eventRecords[0:val]
  1169  		}
  1170  	}
  1171  
  1172  	chainID := c.chainConfig.ChainID.String()
  1173  	for _, eventRecord := range eventRecords {
  1174  		if eventRecord.ID <= lastStateID {
  1175  			continue
  1176  		}
  1177  		if err := validateEventRecord(eventRecord, number, to, lastStateID, chainID); err != nil {
  1178  			log.Error(err.Error())
  1179  			break
  1180  		}
  1181  
  1182  		stateData := types.StateSyncData{
  1183  			ID:       eventRecord.ID,
  1184  			Contract: eventRecord.Contract,
  1185  			Data:     hex.EncodeToString(eventRecord.Data),
  1186  			TxHash:   eventRecord.TxHash,
  1187  		}
  1188  		stateSyncs = append(stateSyncs, &stateData)
  1189  
  1190  		if err := c.GenesisContractsClient.CommitState(eventRecord, state, header, chain); err != nil {
  1191  			return nil, err
  1192  		}
  1193  		lastStateID++
  1194  	}
  1195  	return stateSyncs, nil
  1196  }
  1197  
  1198  func validateEventRecord(eventRecord *EventRecordWithTime, number uint64, to time.Time, lastStateID uint64, chainID string) error {
  1199  	// event id should be sequential and event.Time should lie in the range [from, to)
  1200  	if lastStateID+1 != eventRecord.ID || eventRecord.ChainID != chainID || !eventRecord.Time.Before(to) {
  1201  		return &InvalidStateReceivedError{number, lastStateID, &to, eventRecord}
  1202  	}
  1203  	return nil
  1204  }
  1205  
  1206  func (c *Bor) SetHeimdallClient(h IHeimdallClient) {
  1207  	c.HeimdallClient = h
  1208  }
  1209  
  1210  //
  1211  // Private methods
  1212  //
  1213  
  1214  func (c *Bor) getNextHeimdallSpanForTest(
  1215  	newSpanID uint64,
  1216  	state *state.StateDB,
  1217  	header *types.Header,
  1218  	chain core.ChainContext,
  1219  ) (*HeimdallSpan, error) {
  1220  	headerNumber := header.Number.Uint64()
  1221  	span, err := c.GetCurrentSpan(header.ParentHash)
  1222  	if err != nil {
  1223  		return nil, err
  1224  	}
  1225  
  1226  	// get local chain context object
  1227  	localContext := chain.(chainContext)
  1228  	// Retrieve the snapshot needed to verify this header and cache it
  1229  	snap, err := c.snapshot(localContext.Chain, headerNumber-1, header.ParentHash, nil)
  1230  	if err != nil {
  1231  		return nil, err
  1232  	}
  1233  
  1234  	// new span
  1235  	span.ID = newSpanID
  1236  	if span.EndBlock == 0 {
  1237  		span.StartBlock = 256
  1238  	} else {
  1239  		span.StartBlock = span.EndBlock + 1
  1240  	}
  1241  	span.EndBlock = span.StartBlock + (100 * c.config.Sprint) - 1
  1242  
  1243  	selectedProducers := make([]Validator, len(snap.ValidatorSet.Validators))
  1244  	for i, v := range snap.ValidatorSet.Validators {
  1245  		selectedProducers[i] = *v
  1246  	}
  1247  	heimdallSpan := &HeimdallSpan{
  1248  		Span:              *span,
  1249  		ValidatorSet:      *snap.ValidatorSet,
  1250  		SelectedProducers: selectedProducers,
  1251  		ChainID:           c.chainConfig.ChainID.String(),
  1252  	}
  1253  
  1254  	return heimdallSpan, nil
  1255  }
  1256  
  1257  //
  1258  // Chain context
  1259  //
  1260  
  1261  // chain context
  1262  type chainContext struct {
  1263  	Chain consensus.ChainHeaderReader
  1264  	Bor   consensus.Engine
  1265  }
  1266  
  1267  func (c chainContext) Engine() consensus.Engine {
  1268  	return c.Bor
  1269  }
  1270  
  1271  func (c chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  1272  	return c.Chain.GetHeader(hash, number)
  1273  }
  1274  
  1275  // callmsg implements core.Message to allow passing it as a transaction simulator.
  1276  type callmsg struct {
  1277  	ethereum.CallMsg
  1278  }
  1279  
  1280  func (m callmsg) From() common.Address { return m.CallMsg.From }
  1281  func (m callmsg) Nonce() uint64        { return 0 }
  1282  func (m callmsg) CheckNonce() bool     { return false }
  1283  func (m callmsg) To() *common.Address  { return m.CallMsg.To }
  1284  func (m callmsg) GasPrice() *big.Int   { return m.CallMsg.GasPrice }
  1285  func (m callmsg) Gas() uint64          { return m.CallMsg.Gas }
  1286  func (m callmsg) Value() *big.Int      { return m.CallMsg.Value }
  1287  func (m callmsg) Data() []byte         { return m.CallMsg.Data }
  1288  
  1289  // get system message
  1290  func getSystemMessage(toAddress common.Address, data []byte) callmsg {
  1291  	return callmsg{
  1292  		ethereum.CallMsg{
  1293  			From:     systemAddress,
  1294  			Gas:      math.MaxUint64 / 2,
  1295  			GasPrice: big.NewInt(0),
  1296  			Value:    big.NewInt(0),
  1297  			To:       &toAddress,
  1298  			Data:     data,
  1299  		},
  1300  	}
  1301  }
  1302  
  1303  // apply message
  1304  func applyMessage(
  1305  	msg callmsg,
  1306  	state *state.StateDB,
  1307  	header *types.Header,
  1308  	chainConfig *params.ChainConfig,
  1309  	chainContext core.ChainContext,
  1310  ) error {
  1311  	// Create a new context to be used in the EVM environment
  1312  	blockContext := core.NewEVMBlockContext(header, chainContext, &header.Coinbase)
  1313  	// Create a new environment which holds all relevant information
  1314  	// about the transaction and calling mechanisms.
  1315  	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, state, chainConfig, vm.Config{})
  1316  	// Apply the transaction to the current state (included in the env)
  1317  	_, _, err := vmenv.Call(
  1318  		vm.AccountRef(msg.From()),
  1319  		*msg.To(),
  1320  		msg.Data(),
  1321  		msg.Gas(),
  1322  		msg.Value(),
  1323  	)
  1324  	// Update the state with pending changes
  1325  	if err != nil {
  1326  		state.Finalise(true)
  1327  	}
  1328  
  1329  	return nil
  1330  }
  1331  
  1332  func validatorContains(a []*Validator, x *Validator) (*Validator, bool) {
  1333  	for _, n := range a {
  1334  		if bytes.Compare(n.Address.Bytes(), x.Address.Bytes()) == 0 {
  1335  			return n, true
  1336  		}
  1337  	}
  1338  	return nil, false
  1339  }
  1340  
  1341  func getUpdatedValidatorSet(oldValidatorSet *ValidatorSet, newVals []*Validator) *ValidatorSet {
  1342  	v := oldValidatorSet
  1343  	oldVals := v.Validators
  1344  
  1345  	var changes []*Validator
  1346  	for _, ov := range oldVals {
  1347  		if f, ok := validatorContains(newVals, ov); ok {
  1348  			ov.VotingPower = f.VotingPower
  1349  		} else {
  1350  			ov.VotingPower = 0
  1351  		}
  1352  
  1353  		changes = append(changes, ov)
  1354  	}
  1355  
  1356  	for _, nv := range newVals {
  1357  		if _, ok := validatorContains(changes, nv); !ok {
  1358  			changes = append(changes, nv)
  1359  		}
  1360  	}
  1361  
  1362  	v.UpdateWithChangeSet(changes)
  1363  	return v
  1364  }
  1365  
  1366  func isSprintStart(number, sprint uint64) bool {
  1367  	return number%sprint == 0
  1368  }