Skip to content

Commit 4aa72e6

Browse files
sync: coreth PR #958: refactor config package (#1696)
Signed-off-by: Ceyhun Onur <ceyhun.onur@avalabs.org> Co-authored-by: Ceyhun Onur <ceyhun.onur@avalabs.org>
1 parent 89eef79 commit 4aa72e6

File tree

7 files changed

+198
-219
lines changed

7 files changed

+198
-219
lines changed

RELEASES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
- `StorageRangeAt`
66
- `GetModifiedAccountsByNumber`
77
- `GetModifiedAccountsByHash`
8+
- Removed deprecated flag `tx-lookup-limit`. Use `transaction-history` instead.
89
- Add pending releases here
910

1011

plugin/evm/config.go

Lines changed: 0 additions & 21 deletions
This file was deleted.

plugin/evm/config/config.go

Lines changed: 31 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -9,86 +9,18 @@ import (
99
"fmt"
1010
"time"
1111

12-
"github.com/ava-labs/avalanchego/database/pebbledb"
1312
"github.com/ava-labs/libevm/common"
1413
"github.com/ava-labs/libevm/common/hexutil"
1514
"github.com/spf13/cast"
1615
)
1716

18-
const (
19-
defaultAcceptorQueueLimit = 64 // Provides 2 minutes of buffer (2s block target) for a commit delay
20-
defaultPruningEnabled = true
21-
defaultCommitInterval = 4096
22-
defaultTrieCleanCache = 512
23-
defaultTrieDirtyCache = 512
24-
defaultTrieDirtyCommitTarget = 20
25-
defaultTriePrefetcherParallelism = 16
26-
defaultSnapshotCache = 256
27-
defaultSyncableCommitInterval = defaultCommitInterval * 4
28-
defaultSnapshotWait = false
29-
defaultRpcGasCap = 50_000_000 // Default to 50M Gas Limit
30-
defaultRpcTxFeeCap = 100 // 100 AVAX
31-
defaultMetricsExpensiveEnabled = true
32-
defaultApiMaxDuration = 0 // Default to no maximum API call duration
33-
defaultWsCpuRefillRate = 0 // Default to no maximum WS CPU usage
34-
defaultWsCpuMaxStored = 0 // Default to no maximum WS CPU usage
35-
defaultMaxBlocksPerRequest = 0 // Default to no maximum on the number of blocks per getLogs request
36-
defaultContinuousProfilerFrequency = 15 * time.Minute
37-
defaultContinuousProfilerMaxFiles = 5
38-
defaultPushGossipPercentStake = .9
39-
defaultPushGossipNumValidators = 100
40-
defaultPushGossipNumPeers = 0
41-
defaultPushRegossipNumValidators = 10
42-
defaultPushRegossipNumPeers = 0
43-
defaultPushGossipFrequency = 100 * time.Millisecond
44-
defaultPullGossipFrequency = 1 * time.Second
45-
defaultRegossipFrequency = 30 * time.Second
46-
defaultOfflinePruningBloomFilterSize uint64 = 512 // Default size (MB) for the offline pruner to use
47-
defaultLogLevel = "info"
48-
defaultLogJSONFormat = false
49-
defaultMaxOutboundActiveRequests = 16
50-
defaultPopulateMissingTriesParallelism = 1024
51-
defaultStateSyncServerTrieCache = 64 // MB
52-
defaultAcceptedCacheSize = 32 // blocks
53-
54-
// defaultStateSyncMinBlocks is the minimum number of blocks the blockchain
55-
// should be ahead of local last accepted to perform state sync.
56-
// This constant is chosen so normal bootstrapping is preferred when it would
57-
// be faster than state sync.
58-
// time assumptions:
59-
// - normal bootstrap processing time: ~14 blocks / second
60-
// - state sync time: ~6 hrs.
61-
defaultStateSyncMinBlocks = 300_000
62-
defaultStateSyncRequestSize = 1024 // the number of key/values to ask peers for per request
63-
defaultDBType = pebbledb.Name
64-
defaultValidatorAPIEnabled = true
65-
66-
estimatedBlockAcceptPeriod = 2 * time.Second
67-
defaultHistoricalProofQueryWindow = uint64(24 * time.Hour / estimatedBlockAcceptPeriod)
68-
defaultStateHistory = uint64(32)
69-
)
70-
71-
type PBool bool
72-
73-
var (
74-
defaultEnabledAPIs = []string{
75-
"eth",
76-
"eth-filter",
77-
"net",
78-
"web3",
79-
"internal-eth",
80-
"internal-blockchain",
81-
"internal-transaction",
82-
}
83-
defaultAllowUnprotectedTxHashes = []common.Hash{
84-
common.HexToHash("0xfefb2da535e927b85fe68eb81cb2e4a5827c905f78381a01ef2322aa9b0aee8e"), // EIP-1820: https://eips.ethereum.org/EIPS/eip-1820
17+
type (
18+
PBool bool
19+
Duration struct {
20+
time.Duration
8521
}
8622
)
8723

88-
type Duration struct {
89-
time.Duration
90-
}
91-
9224
// Config ...
9325
type Config struct {
9426
// Airdrop
@@ -223,12 +155,10 @@ type Config struct {
223155
TransactionHistory uint64 `json:"transaction-history"`
224156
// The maximum number of blocks from head whose state histories are reserved for pruning blockchains.
225157
StateHistory uint64 `json:"state-history"`
226-
// Deprecated, use 'TransactionHistory' instead.
227-
TxLookupLimit uint64 `json:"tx-lookup-limit"`
228158

229159
// SkipTxIndexing skips indexing transactions.
230160
// This is useful for validators that don't need to index transactions.
231-
// TxLookupLimit can be still used to control unindexing old transactions.
161+
// TransactionHistory can be still used to control unindexing old transactions.
232162
SkipTxIndexing bool `json:"skip-tx-indexing"`
233163

234164
// WarpOffChainMessages encodes off-chain messages (unrelated to any on-chain event ie. block or AddressedCall)
@@ -252,78 +182,33 @@ type Config struct {
252182
StateScheme string `json:"state-scheme"`
253183
}
254184

255-
// TxPoolConfig contains the transaction pool config to be passed
256-
// to [Config.SetDefaults].
257-
type TxPoolConfig struct {
258-
PriceLimit uint64
259-
PriceBump uint64
260-
AccountSlots uint64
261-
GlobalSlots uint64
262-
AccountQueue uint64
263-
GlobalQueue uint64
264-
Lifetime time.Duration
185+
// GetConfig returns a new config object with the default values set and the
186+
// deprecation message.
187+
// If configBytes is not empty, it will be unmarshalled into the config object.
188+
// If the unmarshalling fails, an error is returned.
189+
// If the config is invalid, an error is returned.
190+
func GetConfig(configBytes []byte, networkID uint32) (Config, string, error) {
191+
config := NewDefaultConfig()
192+
if len(configBytes) > 0 {
193+
if err := json.Unmarshal(configBytes, &config); err != nil {
194+
return Config{}, "", fmt.Errorf("failed to unmarshal config %s: %w", string(configBytes), err)
195+
}
196+
}
197+
if err := config.validate(networkID); err != nil {
198+
return Config{}, "", err
199+
}
200+
// We should deprecate config flags as the first thing, before we do anything else
201+
// because this can set old flags to new flags. log the message after we have
202+
// initialized the logger.
203+
deprecateMsg := config.deprecate()
204+
return config, deprecateMsg, nil
265205
}
266206

267207
// EthAPIs returns an array of strings representing the Eth APIs that should be enabled
268208
func (c Config) EthAPIs() []string {
269209
return c.EnabledEthAPIs
270210
}
271211

272-
func (c *Config) SetDefaults(txPoolConfig TxPoolConfig) {
273-
c.EnabledEthAPIs = defaultEnabledAPIs
274-
c.RPCGasCap = defaultRpcGasCap
275-
c.RPCTxFeeCap = defaultRpcTxFeeCap
276-
c.MetricsExpensiveEnabled = defaultMetricsExpensiveEnabled
277-
278-
// TxPool settings
279-
c.TxPoolPriceLimit = txPoolConfig.PriceLimit
280-
c.TxPoolPriceBump = txPoolConfig.PriceBump
281-
c.TxPoolAccountSlots = txPoolConfig.AccountSlots
282-
c.TxPoolGlobalSlots = txPoolConfig.GlobalSlots
283-
c.TxPoolAccountQueue = txPoolConfig.AccountQueue
284-
c.TxPoolGlobalQueue = txPoolConfig.GlobalQueue
285-
c.TxPoolLifetime.Duration = txPoolConfig.Lifetime
286-
287-
c.APIMaxDuration.Duration = defaultApiMaxDuration
288-
c.WSCPURefillRate.Duration = defaultWsCpuRefillRate
289-
c.WSCPUMaxStored.Duration = defaultWsCpuMaxStored
290-
c.MaxBlocksPerRequest = defaultMaxBlocksPerRequest
291-
c.ContinuousProfilerFrequency.Duration = defaultContinuousProfilerFrequency
292-
c.ContinuousProfilerMaxFiles = defaultContinuousProfilerMaxFiles
293-
c.Pruning = defaultPruningEnabled
294-
c.TrieCleanCache = defaultTrieCleanCache
295-
c.TrieDirtyCache = defaultTrieDirtyCache
296-
c.TrieDirtyCommitTarget = defaultTrieDirtyCommitTarget
297-
c.TriePrefetcherParallelism = defaultTriePrefetcherParallelism
298-
c.SnapshotCache = defaultSnapshotCache
299-
c.AcceptorQueueLimit = defaultAcceptorQueueLimit
300-
c.CommitInterval = defaultCommitInterval
301-
c.SnapshotWait = defaultSnapshotWait
302-
c.PushGossipPercentStake = defaultPushGossipPercentStake
303-
c.PushGossipNumValidators = defaultPushGossipNumValidators
304-
c.PushGossipNumPeers = defaultPushGossipNumPeers
305-
c.PushRegossipNumValidators = defaultPushRegossipNumValidators
306-
c.PushRegossipNumPeers = defaultPushRegossipNumPeers
307-
c.PushGossipFrequency.Duration = defaultPushGossipFrequency
308-
c.PullGossipFrequency.Duration = defaultPullGossipFrequency
309-
c.RegossipFrequency.Duration = defaultRegossipFrequency
310-
c.OfflinePruningBloomFilterSize = defaultOfflinePruningBloomFilterSize
311-
c.LogLevel = defaultLogLevel
312-
c.LogJSONFormat = defaultLogJSONFormat
313-
c.MaxOutboundActiveRequests = defaultMaxOutboundActiveRequests
314-
c.PopulateMissingTriesParallelism = defaultPopulateMissingTriesParallelism
315-
c.StateSyncServerTrieCache = defaultStateSyncServerTrieCache
316-
c.StateSyncCommitInterval = defaultSyncableCommitInterval
317-
c.StateSyncMinBlocks = defaultStateSyncMinBlocks
318-
c.StateSyncRequestSize = defaultStateSyncRequestSize
319-
c.AllowUnprotectedTxHashes = defaultAllowUnprotectedTxHashes
320-
c.AcceptedCacheSize = defaultAcceptedCacheSize
321-
c.DatabaseType = defaultDBType
322-
c.ValidatorsAPIEnabled = defaultValidatorAPIEnabled
323-
c.HistoricalProofQueryWindow = defaultHistoricalProofQueryWindow
324-
c.StateHistory = defaultStateHistory
325-
}
326-
327212
func (d *Duration) UnmarshalJSON(data []byte) (err error) {
328213
var v interface{}
329214
if err := json.Unmarshal(data, &v); err != nil {
@@ -343,8 +228,8 @@ func (d Duration) MarshalJSON() ([]byte, error) {
343228
return json.Marshal(d.Duration.String())
344229
}
345230

346-
// Validate returns an error if this is an invalid config.
347-
func (c *Config) Validate() error {
231+
// validate returns an error if this is an invalid config.
232+
func (c *Config) validate(_ uint32) error {
348233
if c.PopulateMissingTries != nil && (c.OfflinePruning || c.Pruning) {
349234
return fmt.Errorf("cannot enable populate missing tries while offline pruning (enabled: %t)/pruning (enabled: %t) are enabled", c.OfflinePruning, c.Pruning)
350235
}
@@ -369,13 +254,11 @@ func (c *Config) Validate() error {
369254
return nil
370255
}
371256

372-
func (c *Config) Deprecate() string {
257+
// deprecate returns a string of deprecation messages for the config.
258+
// This is used to log a message when the config is loaded and contains deprecated flags.
259+
// This function should be kept as a placeholder even if it is empty.
260+
func (c *Config) deprecate() string {
373261
msg := ""
374-
// Deprecate the old config options and set the new ones.
375-
if c.TxLookupLimit != 0 {
376-
msg += "tx-lookup-limit is deprecated, use transaction-history instead. "
377-
c.TransactionHistory = c.TxLookupLimit
378-
}
379262

380263
return msg
381264
}

plugin/evm/config/config_test.go

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ import (
99
"testing"
1010
"time"
1111

12+
"github.com/ava-labs/avalanchego/utils/constants"
1213
"github.com/ava-labs/libevm/common"
1314
"github.com/stretchr/testify/assert"
15+
"github.com/stretchr/testify/require"
1416
)
1517

1618
func TestUnmarshalConfig(t *testing.T) {
@@ -99,12 +101,6 @@ func TestUnmarshalConfig(t *testing.T) {
99101
Config{},
100102
true,
101103
},
102-
{
103-
"deprecated tx lookup limit",
104-
[]byte(`{"tx-lookup-limit": 1}`),
105-
Config{TransactionHistory: 1, TxLookupLimit: 1},
106-
false,
107-
},
108104
{
109105
"allow unprotected tx hashes",
110106
[]byte(`{"allow-unprotected-tx-hashes": ["0x803351deb6d745e91545a6a3e1c0ea3e9a6a02a1a4193b70edfcd2f40f71a01c"]}`),
@@ -121,9 +117,60 @@ func TestUnmarshalConfig(t *testing.T) {
121117
assert.Error(t, err)
122118
} else {
123119
assert.NoError(t, err)
124-
tmp.Deprecate()
120+
tmp.deprecate()
125121
assert.Equal(t, tt.expected, tmp)
126122
}
127123
})
128124
}
129125
}
126+
127+
func TestGetConfig(t *testing.T) {
128+
tests := []struct {
129+
name string
130+
configJSON []byte
131+
networkID uint32
132+
expected func(*testing.T, Config)
133+
expectError bool
134+
}{
135+
{
136+
name: "custom config values",
137+
configJSON: []byte(`{"rpc-tx-fee-cap": 11,"eth-apis": ["debug"]}`),
138+
networkID: constants.TestnetID,
139+
expected: func(t *testing.T, config Config) {
140+
require.Equal(t, float64(11), config.RPCTxFeeCap, "Tx Fee Cap should be set")
141+
require.Equal(t, []string{"debug"}, config.EthAPIs(), "EnabledEthAPIs should be set")
142+
},
143+
},
144+
{
145+
name: "partial config with defaults",
146+
configJSON: []byte(`{"rpc-tx-fee-cap": 11,"eth-apis": ["debug"], "tx-pool-price-limit": 100}`),
147+
networkID: constants.TestnetID,
148+
expected: func(t *testing.T, config Config) {
149+
require.Equal(t, float64(11), config.RPCTxFeeCap)
150+
require.Equal(t, []string{"debug"}, config.EthAPIs())
151+
require.Equal(t, uint64(100), config.TxPoolPriceLimit)
152+
},
153+
},
154+
{
155+
name: "nil config uses defaults",
156+
configJSON: nil,
157+
networkID: constants.TestnetID,
158+
expected: func(t *testing.T, config Config) {
159+
defaultConfig := NewDefaultConfig()
160+
require.Equal(t, defaultConfig, config)
161+
},
162+
},
163+
}
164+
165+
for _, tt := range tests {
166+
t.Run(tt.name, func(t *testing.T) {
167+
config, _, err := GetConfig(tt.configJSON, tt.networkID)
168+
if tt.expectError {
169+
require.Error(t, err)
170+
return
171+
}
172+
require.NoError(t, err)
173+
tt.expected(t, config)
174+
})
175+
}
176+
}

0 commit comments

Comments
 (0)