github.com/MetalBlockchain/subnet-evm@v0.4.9/plugin/evm/config.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package evm
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"time"
    10  
    11  	"github.com/MetalBlockchain/subnet-evm/core"
    12  	"github.com/MetalBlockchain/subnet-evm/eth"
    13  	"github.com/ethereum/go-ethereum/common"
    14  	"github.com/spf13/cast"
    15  )
    16  
    17  const (
    18  	defaultAcceptorQueueLimit                         = 64 // Provides 2 minutes of buffer (2s block target) for a commit delay
    19  	defaultPruningEnabled                             = true
    20  	defaultCommitInterval                             = 4096
    21  	defaultTrieCleanCache                             = 512
    22  	defaultTrieDirtyCache                             = 256
    23  	defaultTrieDirtyCommitTarget                      = 20
    24  	defaultSnapshotCache                              = 256
    25  	defaultSyncableCommitInterval                     = defaultCommitInterval * 4
    26  	defaultSnapshotAsync                              = true
    27  	defaultRpcGasCap                                  = 50_000_000 // Default to 50M Gas Limit
    28  	defaultRpcTxFeeCap                                = 100        // 100 AVAX
    29  	defaultMetricsExpensiveEnabled                    = true
    30  	defaultApiMaxDuration                             = 0 // Default to no maximum API call duration
    31  	defaultWsCpuRefillRate                            = 0 // Default to no maximum WS CPU usage
    32  	defaultWsCpuMaxStored                             = 0 // Default to no maximum WS CPU usage
    33  	defaultMaxBlocksPerRequest                        = 0 // Default to no maximum on the number of blocks per getLogs request
    34  	defaultContinuousProfilerFrequency                = 15 * time.Minute
    35  	defaultContinuousProfilerMaxFiles                 = 5
    36  	defaultRegossipFrequency                          = 1 * time.Minute
    37  	defaultRegossipMaxTxs                             = 16
    38  	defaultRegossipTxsPerAddress                      = 1
    39  	defaultPriorityRegossipFrequency                  = 1 * time.Second
    40  	defaultPriorityRegossipMaxTxs                     = 32
    41  	defaultPriorityRegossipTxsPerAddress              = 16
    42  	defaultOfflinePruningBloomFilterSize       uint64 = 512 // Default size (MB) for the offline pruner to use
    43  	defaultLogLevel                                   = "info"
    44  	defaultLogJSONFormat                              = false
    45  	defaultMaxOutboundActiveRequests                  = 16
    46  	defaultMaxOutboundActiveCrossChainRequests        = 64
    47  	defaultPopulateMissingTriesParallelism            = 1024
    48  	defaultStateSyncServerTrieCache                   = 64 // MB
    49  	defaultAcceptedCacheSize                          = 32 // blocks
    50  
    51  	// defaultStateSyncMinBlocks is the minimum number of blocks the blockchain
    52  	// should be ahead of local last accepted to perform state sync.
    53  	// This constant is chosen so normal bootstrapping is preferred when it would
    54  	// be faster than state sync.
    55  	// time assumptions:
    56  	// - normal bootstrap processing time: ~14 blocks / second
    57  	// - state sync time: ~6 hrs.
    58  	defaultStateSyncMinBlocks = 300_000
    59  )
    60  
    61  var (
    62  	defaultEnabledAPIs = []string{
    63  		"eth",
    64  		"eth-filter",
    65  		"net",
    66  		"web3",
    67  		"internal-eth",
    68  		"internal-blockchain",
    69  		"internal-transaction",
    70  	}
    71  	defaultAllowUnprotectedTxHashes = []common.Hash{
    72  		common.HexToHash("0xfefb2da535e927b85fe68eb81cb2e4a5827c905f78381a01ef2322aa9b0aee8e"), // EIP-1820: https://eips.ethereum.org/EIPS/eip-1820
    73  	}
    74  )
    75  
    76  type Duration struct {
    77  	time.Duration
    78  }
    79  
    80  // Config ...
    81  type Config struct {
    82  	// Airdrop
    83  	AirdropFile string `json:"airdrop"`
    84  
    85  	// Subnet EVM APIs
    86  	SnowmanAPIEnabled bool   `json:"snowman-api-enabled"`
    87  	WarpAPIEnabled    bool   `json:"warp-api-enabled"`
    88  	AdminAPIEnabled   bool   `json:"admin-api-enabled"`
    89  	AdminAPIDir       string `json:"admin-api-dir"`
    90  
    91  	// EnabledEthAPIs is a list of Ethereum services that should be enabled
    92  	// If none is specified, then we use the default list [defaultEnabledAPIs]
    93  	EnabledEthAPIs []string `json:"eth-apis"`
    94  
    95  	// Continuous Profiler
    96  	ContinuousProfilerDir       string   `json:"continuous-profiler-dir"`       // If set to non-empty string creates a continuous profiler
    97  	ContinuousProfilerFrequency Duration `json:"continuous-profiler-frequency"` // Frequency to run continuous profiler if enabled
    98  	ContinuousProfilerMaxFiles  int      `json:"continuous-profiler-max-files"` // Maximum number of files to maintain
    99  
   100  	// Gas/Price Caps
   101  	RPCGasCap   uint64  `json:"rpc-gas-cap"`
   102  	RPCTxFeeCap float64 `json:"rpc-tx-fee-cap"`
   103  
   104  	// Cache settings
   105  	TrieCleanCache        int      `json:"trie-clean-cache"`         // Size of the trie clean cache (MB)
   106  	TrieCleanJournal      string   `json:"trie-clean-journal"`       // Directory to use to save the trie clean cache (must be populated to enable journaling the trie clean cache)
   107  	TrieCleanRejournal    Duration `json:"trie-clean-rejournal"`     // Frequency to re-journal the trie clean cache to disk (minimum 1 minute, must be populated to enable journaling the trie clean cache)
   108  	TrieDirtyCache        int      `json:"trie-dirty-cache"`         // Size of the trie dirty cache (MB)
   109  	TrieDirtyCommitTarget int      `json:"trie-dirty-commit-target"` // Memory limit to target in the dirty cache before performing a commit (MB)
   110  	SnapshotCache         int      `json:"snapshot-cache"`           // Size of the snapshot disk layer clean cache (MB)
   111  
   112  	// Eth Settings
   113  	Preimages      bool `json:"preimages-enabled"`
   114  	SnapshotAsync  bool `json:"snapshot-async"`
   115  	SnapshotVerify bool `json:"snapshot-verification-enabled"`
   116  
   117  	// Pruning Settings
   118  	Pruning                         bool    `json:"pruning-enabled"`                    // If enabled, trie roots are only persisted every 4096 blocks
   119  	AcceptorQueueLimit              int     `json:"accepted-queue-limit"`               // Maximum blocks to queue before blocking during acceptance
   120  	CommitInterval                  uint64  `json:"commit-interval"`                    // Specifies the commit interval at which to persist EVM and atomic tries.
   121  	AllowMissingTries               bool    `json:"allow-missing-tries"`                // If enabled, warnings preventing an incomplete trie index are suppressed
   122  	PopulateMissingTries            *uint64 `json:"populate-missing-tries,omitempty"`   // Sets the starting point for re-populating missing tries. Disables re-generation if nil.
   123  	PopulateMissingTriesParallelism int     `json:"populate-missing-tries-parallelism"` // Number of concurrent readers to use when re-populating missing tries on startup.
   124  
   125  	// Metric Settings
   126  	MetricsExpensiveEnabled bool `json:"metrics-expensive-enabled"` // Debug-level metrics that might impact runtime performance
   127  
   128  	// API Settings
   129  	LocalTxsEnabled bool `json:"local-txs-enabled"`
   130  
   131  	TxPoolJournal      string   `json:"tx-pool-journal"`
   132  	TxPoolRejournal    Duration `json:"tx-pool-rejournal"`
   133  	TxPoolPriceLimit   uint64   `json:"tx-pool-price-limit"`
   134  	TxPoolPriceBump    uint64   `json:"tx-pool-price-bump"`
   135  	TxPoolAccountSlots uint64   `json:"tx-pool-account-slots"`
   136  	TxPoolGlobalSlots  uint64   `json:"tx-pool-global-slots"`
   137  	TxPoolAccountQueue uint64   `json:"tx-pool-account-queue"`
   138  	TxPoolGlobalQueue  uint64   `json:"tx-pool-global-queue"`
   139  
   140  	APIMaxDuration           Duration      `json:"api-max-duration"`
   141  	WSCPURefillRate          Duration      `json:"ws-cpu-refill-rate"`
   142  	WSCPUMaxStored           Duration      `json:"ws-cpu-max-stored"`
   143  	MaxBlocksPerRequest      int64         `json:"api-max-blocks-per-request"`
   144  	AllowUnfinalizedQueries  bool          `json:"allow-unfinalized-queries"`
   145  	AllowUnprotectedTxs      bool          `json:"allow-unprotected-txs"`
   146  	AllowUnprotectedTxHashes []common.Hash `json:"allow-unprotected-tx-hashes"`
   147  
   148  	// Keystore Settings
   149  	KeystoreDirectory             string `json:"keystore-directory"` // both absolute and relative supported
   150  	KeystoreExternalSigner        string `json:"keystore-external-signer"`
   151  	KeystoreInsecureUnlockAllowed bool   `json:"keystore-insecure-unlock-allowed"`
   152  
   153  	// Gossip Settings
   154  	RemoteGossipOnlyEnabled       bool             `json:"remote-gossip-only-enabled"`
   155  	RegossipFrequency             Duration         `json:"regossip-frequency"`
   156  	RegossipMaxTxs                int              `json:"regossip-max-txs"`
   157  	RegossipTxsPerAddress         int              `json:"regossip-txs-per-address"`
   158  	PriorityRegossipFrequency     Duration         `json:"priority-regossip-frequency"`
   159  	PriorityRegossipMaxTxs        int              `json:"priority-regossip-max-txs"`
   160  	PriorityRegossipTxsPerAddress int              `json:"priority-regossip-txs-per-address"`
   161  	PriorityRegossipAddresses     []common.Address `json:"priority-regossip-addresses"`
   162  
   163  	// Log
   164  	LogLevel      string `json:"log-level"`
   165  	LogJSONFormat bool   `json:"log-json-format"`
   166  
   167  	// Address for Tx Fees (must be empty if not supported by blockchain)
   168  	FeeRecipient string `json:"feeRecipient"`
   169  
   170  	// Offline Pruning Settings
   171  	OfflinePruning                bool   `json:"offline-pruning-enabled"`
   172  	OfflinePruningBloomFilterSize uint64 `json:"offline-pruning-bloom-filter-size"`
   173  	OfflinePruningDataDirectory   string `json:"offline-pruning-data-directory"`
   174  
   175  	// VM2VM network
   176  	MaxOutboundActiveRequests           int64 `json:"max-outbound-active-requests"`
   177  	MaxOutboundActiveCrossChainRequests int64 `json:"max-outbound-active-cross-chain-requests"`
   178  
   179  	// Database Settings
   180  	InspectDatabase bool `json:"inspect-database"` // Inspects the database on startup if enabled.
   181  
   182  	// Sync settings
   183  	StateSyncEnabled         bool   `json:"state-sync-enabled"`
   184  	StateSyncSkipResume      bool   `json:"state-sync-skip-resume"` // Forces state sync to use the highest available summary block
   185  	StateSyncServerTrieCache int    `json:"state-sync-server-trie-cache"`
   186  	StateSyncIDs             string `json:"state-sync-ids"`
   187  	StateSyncCommitInterval  uint64 `json:"state-sync-commit-interval"`
   188  	StateSyncMinBlocks       uint64 `json:"state-sync-min-blocks"`
   189  
   190  	// SkipUpgradeCheck disables checking that upgrades must take place before the last
   191  	// accepted block. Skipping this check is useful when a node operator does not update
   192  	// their node before the network upgrade and their node accepts blocks that have
   193  	// identical state with the pre-upgrade ruleset.
   194  	SkipUpgradeCheck bool `json:"skip-upgrade-check"`
   195  
   196  	// SkipSubnetEVMUpgradeCheck disables checking that SubnetEVM Upgrade is enabled at genesis
   197  	SkipSubnetEVMUpgradeCheck bool `json:"skip-subnet-evm-upgrade-check"`
   198  
   199  	// AcceptedCacheSize is the depth to keep in the accepted headers cache and the
   200  	// accepted logs cache at the accepted tip.
   201  	//
   202  	// This is particularly useful for improving the performance of eth_getLogs
   203  	// on RPC nodes.
   204  	AcceptedCacheSize int `json:"accepted-cache-size"`
   205  
   206  	// TxLookupLimit is the maximum number of blocks from head whose tx indices
   207  	// are reserved:
   208  	//  * 0:   means no limit
   209  	//  * N:   means N block limit [HEAD-N+1, HEAD] and delete extra indexes
   210  	TxLookupLimit uint64 `json:"tx-lookup-limit"`
   211  }
   212  
   213  // EthAPIs returns an array of strings representing the Eth APIs that should be enabled
   214  func (c Config) EthAPIs() []string {
   215  	return c.EnabledEthAPIs
   216  }
   217  
   218  func (c Config) EthBackendSettings() eth.Settings {
   219  	return eth.Settings{MaxBlocksPerRequest: c.MaxBlocksPerRequest}
   220  }
   221  
   222  func (c *Config) SetDefaults() {
   223  	c.EnabledEthAPIs = defaultEnabledAPIs
   224  	c.RPCGasCap = defaultRpcGasCap
   225  	c.RPCTxFeeCap = defaultRpcTxFeeCap
   226  	c.MetricsExpensiveEnabled = defaultMetricsExpensiveEnabled
   227  
   228  	c.TxPoolJournal = core.DefaultTxPoolConfig.Journal
   229  	c.TxPoolRejournal = Duration{core.DefaultTxPoolConfig.Rejournal}
   230  	c.TxPoolPriceLimit = core.DefaultTxPoolConfig.PriceLimit
   231  	c.TxPoolPriceBump = core.DefaultTxPoolConfig.PriceBump
   232  	c.TxPoolAccountSlots = core.DefaultTxPoolConfig.AccountSlots
   233  	c.TxPoolGlobalSlots = core.DefaultTxPoolConfig.GlobalSlots
   234  	c.TxPoolAccountQueue = core.DefaultTxPoolConfig.AccountQueue
   235  	c.TxPoolGlobalQueue = core.DefaultTxPoolConfig.GlobalQueue
   236  
   237  	c.APIMaxDuration.Duration = defaultApiMaxDuration
   238  	c.WSCPURefillRate.Duration = defaultWsCpuRefillRate
   239  	c.WSCPUMaxStored.Duration = defaultWsCpuMaxStored
   240  	c.MaxBlocksPerRequest = defaultMaxBlocksPerRequest
   241  	c.ContinuousProfilerFrequency.Duration = defaultContinuousProfilerFrequency
   242  	c.ContinuousProfilerMaxFiles = defaultContinuousProfilerMaxFiles
   243  	c.Pruning = defaultPruningEnabled
   244  	c.TrieCleanCache = defaultTrieCleanCache
   245  	c.TrieDirtyCache = defaultTrieDirtyCache
   246  	c.TrieDirtyCommitTarget = defaultTrieDirtyCommitTarget
   247  	c.SnapshotCache = defaultSnapshotCache
   248  	c.AcceptorQueueLimit = defaultAcceptorQueueLimit
   249  	c.CommitInterval = defaultCommitInterval
   250  	c.SnapshotAsync = defaultSnapshotAsync
   251  	c.RegossipFrequency.Duration = defaultRegossipFrequency
   252  	c.RegossipMaxTxs = defaultRegossipMaxTxs
   253  	c.RegossipTxsPerAddress = defaultRegossipTxsPerAddress
   254  	c.PriorityRegossipFrequency.Duration = defaultPriorityRegossipFrequency
   255  	c.PriorityRegossipMaxTxs = defaultPriorityRegossipMaxTxs
   256  	c.PriorityRegossipTxsPerAddress = defaultPriorityRegossipTxsPerAddress
   257  	c.OfflinePruningBloomFilterSize = defaultOfflinePruningBloomFilterSize
   258  	c.LogLevel = defaultLogLevel
   259  	c.LogJSONFormat = defaultLogJSONFormat
   260  	c.MaxOutboundActiveRequests = defaultMaxOutboundActiveRequests
   261  	c.MaxOutboundActiveCrossChainRequests = defaultMaxOutboundActiveCrossChainRequests
   262  	c.PopulateMissingTriesParallelism = defaultPopulateMissingTriesParallelism
   263  	c.StateSyncServerTrieCache = defaultStateSyncServerTrieCache
   264  	c.StateSyncCommitInterval = defaultSyncableCommitInterval
   265  	c.StateSyncMinBlocks = defaultStateSyncMinBlocks
   266  	c.AllowUnprotectedTxHashes = defaultAllowUnprotectedTxHashes
   267  	c.AcceptedCacheSize = defaultAcceptedCacheSize
   268  }
   269  
   270  func (d *Duration) UnmarshalJSON(data []byte) (err error) {
   271  	var v interface{}
   272  	if err := json.Unmarshal(data, &v); err != nil {
   273  		return err
   274  	}
   275  	d.Duration, err = cast.ToDurationE(v)
   276  	return err
   277  }
   278  
   279  // String implements the stringer interface.
   280  func (d Duration) String() string {
   281  	return d.Duration.String()
   282  }
   283  
   284  // String implements the stringer interface.
   285  func (d Duration) MarshalJSON() ([]byte, error) {
   286  	return json.Marshal(d.Duration.String())
   287  }
   288  
   289  // Validate returns an error if this is an invalid config.
   290  func (c *Config) Validate() error {
   291  	if c.PopulateMissingTries != nil && (c.OfflinePruning || c.Pruning) {
   292  		return fmt.Errorf("cannot enable populate missing tries while offline pruning (enabled: %t)/pruning (enabled: %t) are enabled", c.OfflinePruning, c.Pruning)
   293  	}
   294  	if c.PopulateMissingTries != nil && c.PopulateMissingTriesParallelism < 1 {
   295  		return fmt.Errorf("cannot enable populate missing tries without at least one reader (parallelism: %d)", c.PopulateMissingTriesParallelism)
   296  	}
   297  
   298  	if !c.Pruning && c.OfflinePruning {
   299  		return fmt.Errorf("cannot run offline pruning while pruning is disabled")
   300  	}
   301  
   302  	// If pruning is enabled, the commit interval must be non-zero so the node commits state tries every CommitInterval blocks.
   303  	if c.Pruning && c.CommitInterval == 0 {
   304  		return fmt.Errorf("cannot use commit interval of 0 with pruning enabled")
   305  	}
   306  	return nil
   307  }