github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/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/core"
    30  	"github.com/ethereum/go-ethereum/core/forkid"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/params"
    33  	"github.com/ethereum/go-ethereum/rlp"
    34  )
    35  
    36  type Chain struct {
    37  	genesis     core.Genesis
    38  	blocks      []*types.Block
    39  	chainConfig *params.ChainConfig
    40  }
    41  
    42  // Len returns the length of the chain.
    43  func (c *Chain) Len() int {
    44  	return len(c.blocks)
    45  }
    46  
    47  // TD calculates the total difficulty of the chain at the
    48  // chain head.
    49  func (c *Chain) TD() *big.Int {
    50  	sum := big.NewInt(0)
    51  	for _, block := range c.blocks[:c.Len()] {
    52  		sum.Add(sum, block.Difficulty())
    53  	}
    54  	return sum
    55  }
    56  
    57  // TotalDifficultyAt calculates the total difficulty of the chain
    58  // at the given block height.
    59  func (c *Chain) TotalDifficultyAt(height int) *big.Int {
    60  	sum := big.NewInt(0)
    61  	if height >= c.Len() {
    62  		return sum
    63  	}
    64  	for _, block := range c.blocks[:height+1] {
    65  		sum.Add(sum, block.Difficulty())
    66  	}
    67  	return sum
    68  }
    69  
    70  // ForkID gets the fork id of the chain.
    71  func (c *Chain) ForkID() forkid.ID {
    72  	return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len()))
    73  }
    74  
    75  // Shorten returns a copy chain of a desired height from the imported
    76  func (c *Chain) Shorten(height int) *Chain {
    77  	blocks := make([]*types.Block, height)
    78  	copy(blocks, c.blocks[:height])
    79  
    80  	config := *c.chainConfig
    81  	return &Chain{
    82  		blocks:      blocks,
    83  		chainConfig: &config,
    84  	}
    85  }
    86  
    87  // Head returns the chain head.
    88  func (c *Chain) Head() *types.Block {
    89  	return c.blocks[c.Len()-1]
    90  }
    91  
    92  func (c *Chain) GetHeaders(req GetBlockHeaders) (BlockHeaders, error) {
    93  	if req.Amount < 1 {
    94  		return nil, fmt.Errorf("no block headers requested")
    95  	}
    96  
    97  	headers := make(BlockHeaders, req.Amount)
    98  	var blockNumber uint64
    99  
   100  	// range over blocks to check if our chain has the requested header
   101  	for _, block := range c.blocks {
   102  		if block.Hash() == req.Origin.Hash || block.Number().Uint64() == req.Origin.Number {
   103  			headers[0] = block.Header()
   104  			blockNumber = block.Number().Uint64()
   105  		}
   106  	}
   107  	if headers[0] == nil {
   108  		return nil, fmt.Errorf("no headers found for given origin number %v, hash %v", req.Origin.Number, req.Origin.Hash)
   109  	}
   110  
   111  	if req.Reverse {
   112  		for i := 1; i < int(req.Amount); i++ {
   113  			blockNumber -= (1 - req.Skip)
   114  			headers[i] = c.blocks[blockNumber].Header()
   115  
   116  		}
   117  
   118  		return headers, nil
   119  	}
   120  
   121  	for i := 1; i < int(req.Amount); i++ {
   122  		blockNumber += (1 + req.Skip)
   123  		headers[i] = c.blocks[blockNumber].Header()
   124  	}
   125  
   126  	return headers, nil
   127  }
   128  
   129  // loadChain takes the given chain.rlp file, and decodes and returns
   130  // the blocks from the file.
   131  func loadChain(chainfile string, genesis string) (*Chain, error) {
   132  	gen, err := loadGenesis(genesis)
   133  	if err != nil {
   134  		return nil, err
   135  	}
   136  	gblock := gen.ToBlock(nil)
   137  
   138  	blocks, err := blocksFromFile(chainfile, gblock)
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  
   143  	c := &Chain{genesis: gen, blocks: blocks, chainConfig: gen.Config}
   144  	return c, nil
   145  }
   146  
   147  func loadGenesis(genesisFile string) (core.Genesis, error) {
   148  	chainConfig, err := ioutil.ReadFile(genesisFile)
   149  	if err != nil {
   150  		return core.Genesis{}, err
   151  	}
   152  	var gen core.Genesis
   153  	if err := json.Unmarshal(chainConfig, &gen); err != nil {
   154  		return core.Genesis{}, err
   155  	}
   156  	return gen, nil
   157  }
   158  
   159  func blocksFromFile(chainfile string, gblock *types.Block) ([]*types.Block, error) {
   160  	// Load chain.rlp.
   161  	fh, err := os.Open(chainfile)
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  	defer fh.Close()
   166  	var reader io.Reader = fh
   167  	if strings.HasSuffix(chainfile, ".gz") {
   168  		if reader, err = gzip.NewReader(reader); err != nil {
   169  			return nil, err
   170  		}
   171  	}
   172  	stream := rlp.NewStream(reader, 0)
   173  	var blocks = make([]*types.Block, 1)
   174  	blocks[0] = gblock
   175  	for i := 0; ; i++ {
   176  		var b types.Block
   177  		if err := stream.Decode(&b); err == io.EOF {
   178  			break
   179  		} else if err != nil {
   180  			return nil, fmt.Errorf("at block index %d: %v", i, err)
   181  		}
   182  		if b.NumberU64() != uint64(i+1) {
   183  			return nil, fmt.Errorf("block at index %d has wrong number %d", i, b.NumberU64())
   184  		}
   185  		blocks = append(blocks, &b)
   186  	}
   187  	return blocks, nil
   188  }