github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/eth/ethconfig/config.go (about)

     1  // Copyright 2017 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 ethconfig contains the configuration of the ETH and LES protocols.
    18  package ethconfig
    19  
    20  import (
    21  	"math/big"
    22  	"os"
    23  	"os/user"
    24  	"path/filepath"
    25  	"runtime"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/consensus"
    30  	"github.com/ethereum/go-ethereum/consensus/beacon"
    31  	"github.com/ethereum/go-ethereum/consensus/bor"
    32  	"github.com/ethereum/go-ethereum/consensus/bor/contract"
    33  	"github.com/ethereum/go-ethereum/consensus/bor/heimdall" //nolint:typecheck
    34  	"github.com/ethereum/go-ethereum/consensus/bor/heimdall/span"
    35  	"github.com/ethereum/go-ethereum/consensus/bor/heimdallapp"
    36  	"github.com/ethereum/go-ethereum/consensus/bor/heimdallgrpc"
    37  	"github.com/ethereum/go-ethereum/consensus/clique"
    38  	"github.com/ethereum/go-ethereum/consensus/ethash"
    39  	"github.com/ethereum/go-ethereum/core"
    40  	"github.com/ethereum/go-ethereum/eth/downloader"
    41  	"github.com/ethereum/go-ethereum/eth/gasprice"
    42  	"github.com/ethereum/go-ethereum/ethdb"
    43  	"github.com/ethereum/go-ethereum/internal/ethapi"
    44  	"github.com/ethereum/go-ethereum/log"
    45  	"github.com/ethereum/go-ethereum/miner"
    46  	"github.com/ethereum/go-ethereum/node"
    47  	"github.com/ethereum/go-ethereum/params"
    48  )
    49  
    50  // FullNodeGPO contains default gasprice oracle settings for full node.
    51  var FullNodeGPO = gasprice.Config{
    52  	Blocks:           20,
    53  	Percentile:       60,
    54  	MaxHeaderHistory: 1024,
    55  	MaxBlockHistory:  1024,
    56  	MaxPrice:         gasprice.DefaultMaxPrice,
    57  	IgnorePrice:      gasprice.DefaultIgnorePrice,
    58  }
    59  
    60  // LightClientGPO contains default gasprice oracle settings for light client.
    61  var LightClientGPO = gasprice.Config{
    62  	Blocks:           2,
    63  	Percentile:       60,
    64  	MaxHeaderHistory: 300,
    65  	MaxBlockHistory:  5,
    66  	MaxPrice:         gasprice.DefaultMaxPrice,
    67  	IgnorePrice:      gasprice.DefaultIgnorePrice,
    68  }
    69  
    70  // Defaults contains default settings for use on the Ethereum main net.
    71  var Defaults = Config{
    72  	SyncMode: downloader.SnapSync,
    73  	Ethash: ethash.Config{
    74  		CacheDir:         "ethash",
    75  		CachesInMem:      2,
    76  		CachesOnDisk:     3,
    77  		CachesLockMmap:   false,
    78  		DatasetsInMem:    1,
    79  		DatasetsOnDisk:   2,
    80  		DatasetsLockMmap: false,
    81  	},
    82  	NetworkId:               1,
    83  	TxLookupLimit:           2350000,
    84  	LightPeers:              100,
    85  	UltraLightFraction:      75,
    86  	DatabaseCache:           512,
    87  	TrieCleanCache:          154,
    88  	TrieCleanCacheJournal:   "triecache",
    89  	TrieCleanCacheRejournal: 60 * time.Minute,
    90  	TrieDirtyCache:          256,
    91  	TrieTimeout:             60 * time.Minute,
    92  	SnapshotCache:           102,
    93  	Miner: miner.Config{
    94  		GasCeil:  8000000,
    95  		GasPrice: big.NewInt(params.GWei),
    96  		Recommit: 125 * time.Second,
    97  	},
    98  	TxPool:             core.DefaultTxPoolConfig,
    99  	RPCGasCap:          50000000,
   100  	RPCReturnDataLimit: 100000,
   101  	RPCEVMTimeout:      5 * time.Second,
   102  	GPO:                FullNodeGPO,
   103  	RPCTxFeeCap:        5, // 5 matic
   104  }
   105  
   106  func init() {
   107  	home := os.Getenv("HOME")
   108  	if home == "" {
   109  		if user, err := user.Current(); err == nil {
   110  			home = user.HomeDir
   111  		}
   112  	}
   113  	if runtime.GOOS == "darwin" {
   114  		Defaults.Ethash.DatasetDir = filepath.Join(home, "Library", "Ethash")
   115  	} else if runtime.GOOS == "windows" {
   116  		localappdata := os.Getenv("LOCALAPPDATA")
   117  		if localappdata != "" {
   118  			Defaults.Ethash.DatasetDir = filepath.Join(localappdata, "Ethash")
   119  		} else {
   120  			Defaults.Ethash.DatasetDir = filepath.Join(home, "AppData", "Local", "Ethash")
   121  		}
   122  	} else {
   123  		Defaults.Ethash.DatasetDir = filepath.Join(home, ".ethash")
   124  	}
   125  }
   126  
   127  //go:generate gencodec -type Config -formats toml -out gen_config.go
   128  
   129  // Config contains configuration options for of the ETH and LES protocols.
   130  type Config struct {
   131  	// The genesis block, which is inserted if the database is empty.
   132  	// If nil, the Ethereum main net block is used.
   133  	Genesis *core.Genesis `toml:",omitempty"`
   134  
   135  	// Protocol options
   136  	NetworkId uint64 // Network ID to use for selecting peers to connect to
   137  	SyncMode  downloader.SyncMode
   138  
   139  	// This can be set to list of enrtree:// URLs which will be queried for
   140  	// for nodes to connect to.
   141  	EthDiscoveryURLs  []string
   142  	SnapDiscoveryURLs []string
   143  
   144  	NoPruning  bool // Whether to disable pruning and flush everything to disk
   145  	NoPrefetch bool // Whether to disable prefetching and only load state on demand
   146  
   147  	TxLookupLimit uint64 `toml:",omitempty"` // The maximum number of blocks from head whose tx indices are reserved.
   148  
   149  	// PeerRequiredBlocks is a set of block number -> hash mappings which must be in the
   150  	// canonical chain of all remote peers. Setting the option makes geth verify the
   151  	// presence of these blocks for every new peer connection.
   152  	PeerRequiredBlocks map[uint64]common.Hash `toml:"-"`
   153  
   154  	// Light client options
   155  	LightServ          int  `toml:",omitempty"` // Maximum percentage of time allowed for serving LES requests
   156  	LightIngress       int  `toml:",omitempty"` // Incoming bandwidth limit for light servers
   157  	LightEgress        int  `toml:",omitempty"` // Outgoing bandwidth limit for light servers
   158  	LightPeers         int  `toml:",omitempty"` // Maximum number of LES client peers
   159  	LightNoPrune       bool `toml:",omitempty"` // Whether to disable light chain pruning
   160  	LightNoSyncServe   bool `toml:",omitempty"` // Whether to serve light clients before syncing
   161  	SyncFromCheckpoint bool `toml:",omitempty"` // Whether to sync the header chain from the configured checkpoint
   162  
   163  	// Ultra Light client options
   164  	UltraLightServers      []string `toml:",omitempty"` // List of trusted ultra light servers
   165  	UltraLightFraction     int      `toml:",omitempty"` // Percentage of trusted servers to accept an announcement
   166  	UltraLightOnlyAnnounce bool     `toml:",omitempty"` // Whether to only announce headers, or also serve them
   167  
   168  	// Database options
   169  	SkipBcVersionCheck bool `toml:"-"`
   170  	DatabaseHandles    int  `toml:"-"`
   171  	DatabaseCache      int
   172  	DatabaseFreezer    string
   173  
   174  	TrieCleanCache          int
   175  	TrieCleanCacheJournal   string        `toml:",omitempty"` // Disk journal directory for trie cache to survive node restarts
   176  	TrieCleanCacheRejournal time.Duration `toml:",omitempty"` // Time interval to regenerate the journal for clean cache
   177  	TrieDirtyCache          int
   178  	TrieTimeout             time.Duration
   179  	SnapshotCache           int
   180  	Preimages               bool
   181  	TriesInMemory           uint64
   182  
   183  	// Mining options
   184  	Miner miner.Config
   185  
   186  	// Ethash options
   187  	Ethash ethash.Config
   188  
   189  	// Transaction pool options
   190  	TxPool core.TxPoolConfig
   191  
   192  	// Gas Price Oracle options
   193  	GPO gasprice.Config
   194  
   195  	// Enables tracking of SHA3 preimages in the VM
   196  	EnablePreimageRecording bool
   197  
   198  	// Miscellaneous options
   199  	DocRoot string `toml:"-"`
   200  
   201  	// RPCGasCap is the global gas cap for eth-call variants.
   202  	RPCGasCap uint64
   203  
   204  	// Maximum size (in bytes) a result of an rpc request could have
   205  	RPCReturnDataLimit uint64
   206  
   207  	// RPCEVMTimeout is the global timeout for eth-call.
   208  	RPCEVMTimeout time.Duration
   209  
   210  	// RPCTxFeeCap is the global transaction fee(price * gaslimit) cap for
   211  	// send-transction variants. The unit is ether.
   212  	RPCTxFeeCap float64
   213  
   214  	// Checkpoint is a hardcoded checkpoint which can be nil.
   215  	Checkpoint *params.TrustedCheckpoint `toml:",omitempty"`
   216  
   217  	// CheckpointOracle is the configuration for checkpoint oracle.
   218  	CheckpointOracle *params.CheckpointOracleConfig `toml:",omitempty"`
   219  
   220  	// URL to connect to Heimdall node
   221  	HeimdallURL string
   222  
   223  	// No heimdall service
   224  	WithoutHeimdall bool
   225  
   226  	// Address to connect to Heimdall gRPC server
   227  	HeimdallgRPCAddress string
   228  
   229  	// Run heimdall service as a child process
   230  	RunHeimdall bool
   231  
   232  	// Arguments to pass to heimdall service
   233  	RunHeimdallArgs string
   234  
   235  	// Use child heimdall process to fetch data, Only works when RunHeimdall is true
   236  	UseHeimdallApp bool
   237  
   238  	// Bor logs flag
   239  	BorLogs bool
   240  
   241  	// Parallel EVM (Block-STM) related config
   242  	ParallelEVM core.ParallelEVMConfig `toml:",omitempty"`
   243  
   244  	// Arrow Glacier block override (TODO: remove after the fork)
   245  	OverrideArrowGlacier *big.Int `toml:",omitempty"`
   246  
   247  	// OverrideTerminalTotalDifficulty (TODO: remove after the fork)
   248  	OverrideTerminalTotalDifficulty *big.Int `toml:",omitempty"`
   249  
   250  	// Develop Fake Author mode to produce blocks without authorisation
   251  	DevFakeAuthor bool `hcl:"devfakeauthor,optional" toml:"devfakeauthor,optional"`
   252  }
   253  
   254  // CreateConsensusEngine creates a consensus engine for the given chain configuration.
   255  func CreateConsensusEngine(stack *node.Node, chainConfig *params.ChainConfig, ethConfig *Config, notify []string, noverify bool, db ethdb.Database, blockchainAPI *ethapi.PublicBlockChainAPI) consensus.Engine {
   256  	config := &ethConfig.Ethash
   257  
   258  	// If proof-of-authority is requested, set it up
   259  	var engine consensus.Engine
   260  	if chainConfig.Clique != nil {
   261  		return clique.New(chainConfig.Clique, db)
   262  	}
   263  
   264  	// If Matic bor consensus is requested, set it up
   265  	// In order to pass the ethereum transaction tests, we need to set the burn contract which is in the bor config
   266  	// Then, bor != nil will also be enabled for ethash and clique. Only enable Bor for real if there is a validator contract present.
   267  	if chainConfig.Bor != nil && chainConfig.Bor.ValidatorContract != "" {
   268  		genesisContractsClient := contract.NewGenesisContractsClient(chainConfig, chainConfig.Bor.ValidatorContract, chainConfig.Bor.StateReceiverContract, blockchainAPI)
   269  		spanner := span.NewChainSpanner(blockchainAPI, contract.ValidatorSet(), chainConfig, common.HexToAddress(chainConfig.Bor.ValidatorContract))
   270  
   271  		if ethConfig.WithoutHeimdall {
   272  			return bor.New(chainConfig, db, blockchainAPI, spanner, nil, genesisContractsClient, ethConfig.DevFakeAuthor)
   273  		} else {
   274  			if ethConfig.DevFakeAuthor {
   275  				log.Warn("Sanitizing DevFakeAuthor", "Use DevFakeAuthor with", "--bor.withoutheimdall")
   276  			}
   277  			var heimdallClient bor.IHeimdallClient
   278  			if ethConfig.RunHeimdall && ethConfig.UseHeimdallApp {
   279  				heimdallClient = heimdallapp.NewHeimdallAppClient()
   280  			} else if ethConfig.HeimdallgRPCAddress != "" {
   281  				heimdallClient = heimdallgrpc.NewHeimdallGRPCClient(ethConfig.HeimdallgRPCAddress)
   282  			} else {
   283  				heimdallClient = heimdall.NewHeimdallClient(ethConfig.HeimdallURL)
   284  			}
   285  
   286  			return bor.New(chainConfig, db, blockchainAPI, spanner, heimdallClient, genesisContractsClient, false)
   287  		}
   288  	} else {
   289  		switch config.PowMode {
   290  		case ethash.ModeFake:
   291  			log.Warn("Ethash used in fake mode")
   292  		case ethash.ModeTest:
   293  			log.Warn("Ethash used in test mode")
   294  		case ethash.ModeShared:
   295  			log.Warn("Ethash used in shared mode")
   296  		}
   297  		engine = ethash.New(ethash.Config{
   298  			PowMode:          config.PowMode,
   299  			CacheDir:         stack.ResolvePath(config.CacheDir),
   300  			CachesInMem:      config.CachesInMem,
   301  			CachesOnDisk:     config.CachesOnDisk,
   302  			CachesLockMmap:   config.CachesLockMmap,
   303  			DatasetDir:       config.DatasetDir,
   304  			DatasetsInMem:    config.DatasetsInMem,
   305  			DatasetsOnDisk:   config.DatasetsOnDisk,
   306  			DatasetsLockMmap: config.DatasetsLockMmap,
   307  			NotifyFull:       config.NotifyFull,
   308  		}, notify, noverify)
   309  		engine.(*ethash.Ethash).SetThreads(-1) // Disable CPU mining
   310  	}
   311  	return beacon.New(engine)
   312  }