github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/cmd/devp2p/internal/ethtest/chain.go (about)

     1  // Copyright 2020 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package ethtest
    18  
    19  import (
    20  	"compress/gzip"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"io/ioutil"
    25  	"math/big"
    26  	"os"
    27  	"strings"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/core/forkid"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/params"
    34  	"github.com/ethereum/go-ethereum/rlp"
    35  )
    36  
    37  type Chain struct {
    38  	genesis     core.Genesis
    39  	blocks      []*types.Block
    40  	chainConfig *params.ChainConfig
    41  }
    42  
    43  // Len returns the length of the chain.
    44  func (c *Chain) Len() int {
    45  	return len(c.blocks)
    46  }
    47  
    48  // TD calculates the total difficulty of the chain at the
    49  // chain head.
    50  func (c *Chain) TD() *big.Int {
    51  	sum := big.NewInt(0)
    52  	for _, block := range c.blocks[:c.Len()] {
    53  		sum.Add(sum, block.Difficulty())
    54  	}
    55  	return sum
    56  }
    57  
    58  // TotalDifficultyAt calculates the total difficulty of the chain
    59  // at the given block height.
    60  func (c *Chain) TotalDifficultyAt(height int) *big.Int {
    61  	sum := big.NewInt(0)
    62  	if height >= c.Len() {
    63  		return sum
    64  	}
    65  	for _, block := range c.blocks[:height+1] {
    66  		sum.Add(sum, block.Difficulty())
    67  	}
    68  	return sum
    69  }
    70  
    71  func (c *Chain) RootAt(height int) common.Hash {
    72  	if height < c.Len() {
    73  		return c.blocks[height].Root()
    74  	}
    75  	return common.Hash{}
    76  }
    77  
    78  // ForkID gets the fork id of the chain.
    79  func (c *Chain) ForkID() forkid.ID {
    80  	return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len()))
    81  }
    82  
    83  // Shorten returns a copy chain of a desired height from the imported
    84  func (c *Chain) Shorten(height int) *Chain {
    85  	blocks := make([]*types.Block, height)
    86  	copy(blocks, c.blocks[:height])
    87  
    88  	config := *c.chainConfig
    89  	return &Chain{
    90  		blocks:      blocks,
    91  		chainConfig: &config,
    92  	}
    93  }
    94  
    95  // Head returns the chain head.
    96  func (c *Chain) Head() *types.Block {
    97  	return c.blocks[c.Len()-1]
    98  }
    99  
   100  func (c *Chain) GetHeaders(req GetBlockHeaders) (BlockHeaders, error) {
   101  	if req.Amount < 1 {
   102  		return nil, fmt.Errorf("no block headers requested")
   103  	}
   104  
   105  	headers := make(BlockHeaders, req.Amount)
   106  	var blockNumber uint64
   107  
   108  	// range over blocks to check if our chain has the requested header
   109  	for _, block := range c.blocks {
   110  		if block.Hash() == req.Origin.Hash || block.Number().Uint64() == req.Origin.Number {
   111  			headers[0] = block.Header()
   112  			blockNumber = block.Number().Uint64()
   113  		}
   114  	}
   115  	if headers[0] == nil {
   116  		return nil, fmt.Errorf("no headers found for given origin number %v, hash %v", req.Origin.Number, req.Origin.Hash)
   117  	}
   118  
   119  	if req.Reverse {
   120  		for i := 1; i < int(req.Amount); i++ {
   121  			blockNumber -= (1 - req.Skip)
   122  			headers[i] = c.blocks[blockNumber].Header()
   123  
   124  		}
   125  
   126  		return headers, nil
   127  	}
   128  
   129  	for i := 1; i < int(req.Amount); i++ {
   130  		blockNumber += (1 + req.Skip)
   131  		headers[i] = c.blocks[blockNumber].Header()
   132  	}
   133  
   134  	return headers, nil
   135  }
   136  
   137  // loadChain takes the given chain.rlp file, and decodes and returns
   138  // the blocks from the file.
   139  func loadChain(chainfile string, genesis string) (*Chain, error) {
   140  	gen, err := loadGenesis(genesis)
   141  	if err != nil {
   142  		return nil, err
   143  	}
   144  	gblock := gen.ToBlock(nil)
   145  
   146  	blocks, err := blocksFromFile(chainfile, gblock)
   147  	if err != nil {
   148  		return nil, err
   149  	}
   150  
   151  	c := &Chain{genesis: gen, blocks: blocks, chainConfig: gen.Config}
   152  	return c, nil
   153  }
   154  
   155  func loadGenesis(genesisFile string) (core.Genesis, error) {
   156  	chainConfig, err := ioutil.ReadFile(genesisFile)
   157  	if err != nil {
   158  		return core.Genesis{}, err
   159  	}
   160  	var gen core.Genesis
   161  	if err := json.Unmarshal(chainConfig, &gen); err != nil {
   162  		return core.Genesis{}, err
   163  	}
   164  	return gen, nil
   165  }
   166  
   167  func blocksFromFile(chainfile string, gblock *types.Block) ([]*types.Block, error) {
   168  	// Load chain.rlp.
   169  	fh, err := os.Open(chainfile)
   170  	if err != nil {
   171  		return nil, err
   172  	}
   173  	defer fh.Close()
   174  	var reader io.Reader = fh
   175  	if strings.HasSuffix(chainfile, ".gz") {
   176  		if reader, err = gzip.NewReader(reader); err != nil {
   177  			return nil, err
   178  		}
   179  	}
   180  	stream := rlp.NewStream(reader, 0)
   181  	var blocks = make([]*types.Block, 1)
   182  	blocks[0] = gblock
   183  	for i := 0; ; i++ {
   184  		var b types.Block
   185  		if err := stream.Decode(&b); err == io.EOF {
   186  			break
   187  		} else if err != nil {
   188  			return nil, fmt.Errorf("at block index %d: %v", i, err)
   189  		}
   190  		if b.NumberU64() != uint64(i+1) {
   191  			return nil, fmt.Errorf("block at index %d has wrong number %d", i, b.NumberU64())
   192  		}
   193  		blocks = append(blocks, &b)
   194  	}
   195  	return blocks, nil
   196  }