github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/cmd/devp2p/internal/ethtest/chain.go (about)

     1  // Copyright 2020 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. 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  	"math/big"
    25  	"os"
    26  	"strings"
    27  
    28  	"github.com/tirogen/go-ethereum/common"
    29  	"github.com/tirogen/go-ethereum/core"
    30  	"github.com/tirogen/go-ethereum/core/forkid"
    31  	"github.com/tirogen/go-ethereum/core/types"
    32  	"github.com/tirogen/go-ethereum/params"
    33  	"github.com/tirogen/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 := new(big.Int)
    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 := new(big.Int)
    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  func (c *Chain) RootAt(height int) common.Hash {
    71  	if height < c.Len() {
    72  		return c.blocks[height].Root()
    73  	}
    74  	return common.Hash{}
    75  }
    76  
    77  // ForkID gets the fork id of the chain.
    78  func (c *Chain) ForkID() forkid.ID {
    79  	return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len()))
    80  }
    81  
    82  // Shorten returns a copy chain of a desired height from the imported
    83  func (c *Chain) Shorten(height int) *Chain {
    84  	blocks := make([]*types.Block, height)
    85  	copy(blocks, c.blocks[:height])
    86  
    87  	config := *c.chainConfig
    88  	return &Chain{
    89  		blocks:      blocks,
    90  		chainConfig: &config,
    91  	}
    92  }
    93  
    94  // Head returns the chain head.
    95  func (c *Chain) Head() *types.Block {
    96  	return c.blocks[c.Len()-1]
    97  }
    98  
    99  func (c *Chain) GetHeaders(req *GetBlockHeaders) ([]*types.Header, error) {
   100  	if req.Amount < 1 {
   101  		return nil, fmt.Errorf("no block headers requested")
   102  	}
   103  
   104  	headers := make([]*types.Header, req.Amount)
   105  	var blockNumber uint64
   106  
   107  	// range over blocks to check if our chain has the requested header
   108  	for _, block := range c.blocks {
   109  		if block.Hash() == req.Origin.Hash || block.Number().Uint64() == req.Origin.Number {
   110  			headers[0] = block.Header()
   111  			blockNumber = block.Number().Uint64()
   112  		}
   113  	}
   114  	if headers[0] == nil {
   115  		return nil, fmt.Errorf("no headers found for given origin number %v, hash %v", req.Origin.Number, req.Origin.Hash)
   116  	}
   117  
   118  	if req.Reverse {
   119  		for i := 1; i < int(req.Amount); i++ {
   120  			blockNumber -= (1 - req.Skip)
   121  			headers[i] = c.blocks[blockNumber].Header()
   122  		}
   123  
   124  		return headers, nil
   125  	}
   126  
   127  	for i := 1; i < int(req.Amount); i++ {
   128  		blockNumber += (1 + req.Skip)
   129  		headers[i] = c.blocks[blockNumber].Header()
   130  	}
   131  
   132  	return headers, nil
   133  }
   134  
   135  // loadChain takes the given chain.rlp file, and decodes and returns
   136  // the blocks from the file.
   137  func loadChain(chainfile string, genesis string) (*Chain, error) {
   138  	gen, err := loadGenesis(genesis)
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  	gblock := gen.ToBlock()
   143  
   144  	blocks, err := blocksFromFile(chainfile, gblock)
   145  	if err != nil {
   146  		return nil, err
   147  	}
   148  
   149  	c := &Chain{genesis: gen, blocks: blocks, chainConfig: gen.Config}
   150  	return c, nil
   151  }
   152  
   153  func loadGenesis(genesisFile string) (core.Genesis, error) {
   154  	chainConfig, err := os.ReadFile(genesisFile)
   155  	if err != nil {
   156  		return core.Genesis{}, err
   157  	}
   158  	var gen core.Genesis
   159  	if err := json.Unmarshal(chainConfig, &gen); err != nil {
   160  		return core.Genesis{}, err
   161  	}
   162  	return gen, nil
   163  }
   164  
   165  func blocksFromFile(chainfile string, gblock *types.Block) ([]*types.Block, error) {
   166  	// Load chain.rlp.
   167  	fh, err := os.Open(chainfile)
   168  	if err != nil {
   169  		return nil, err
   170  	}
   171  	defer fh.Close()
   172  	var reader io.Reader = fh
   173  	if strings.HasSuffix(chainfile, ".gz") {
   174  		if reader, err = gzip.NewReader(reader); err != nil {
   175  			return nil, err
   176  		}
   177  	}
   178  	stream := rlp.NewStream(reader, 0)
   179  	var blocks = make([]*types.Block, 1)
   180  	blocks[0] = gblock
   181  	for i := 0; ; i++ {
   182  		var b types.Block
   183  		if err := stream.Decode(&b); err == io.EOF {
   184  			break
   185  		} else if err != nil {
   186  			return nil, fmt.Errorf("at block index %d: %v", i, err)
   187  		}
   188  		if b.NumberU64() != uint64(i+1) {
   189  			return nil, fmt.Errorf("block at index %d has wrong number %d", i, b.NumberU64())
   190  		}
   191  		blocks = append(blocks, &b)
   192  	}
   193  	return blocks, nil
   194  }