/
config.go
432 lines (385 loc) · 12.9 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package launcher
import (
"bufio"
"bytes"
"errors"
"fmt"
"math/big"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/params"
"github.com/metatechchain/meta-base/abft"
"github.com/metatechchain/meta-base/hash"
"github.com/metatechchain/meta-base/utils/cachescale"
"github.com/naoina/toml"
"gopkg.in/urfave/cli.v1"
"github.com/metatechchain/go-metatechchain/evmcore"
"github.com/metatechchain/go-metatechchain/gossip"
"github.com/metatechchain/go-metatechchain/gossip/gasprice"
"github.com/metatechchain/go-metatechchain/integration"
"github.com/metatechchain/go-metatechchain/integration/makegenesis"
"github.com/metatechchain/go-metatechchain/metatechchain"
"github.com/metatechchain/go-metatechchain/metatechchain/genesisstore"
futils "github.com/metatechchain/go-metatechchain/utils"
"github.com/metatechchain/go-metatechchain/vecmt"
)
var (
dumpConfigCommand = cli.Command{
Action: utils.MigrateFlags(dumpConfig),
Name: "dumpconfig",
Usage: "Show configuration values",
ArgsUsage: "",
Flags: append(nodeFlags, testFlags...),
Category: "MISCELLANEOUS COMMANDS",
Description: `The dumpconfig command shows configuration values.`,
}
checkConfigCommand = cli.Command{
Action: utils.MigrateFlags(checkConfig),
Name: "checkconfig",
Usage: "Checks configuration file",
ArgsUsage: "",
Flags: append(nodeFlags, testFlags...),
Category: "MISCELLANEOUS COMMANDS",
Description: `The checkconfig checks configuration file.`,
}
configFileFlag = cli.StringFlag{
Name: "config",
Usage: "TOML configuration file",
}
// DataDirFlag defines directory to store Meta state and user's wallets
DataDirFlag = utils.DirectoryFlag{
Name: "datadir",
Usage: "Data directory for the databases and keystore",
Value: utils.DirectoryString(DefaultDataDir()),
}
CacheFlag = cli.IntFlag{
Name: "cache",
Usage: "Megabytes of memory allocated to internal caching",
Value: DefaultCacheSize,
}
// GenesisFlag specifies network genesis configuration
GenesisFlag = cli.StringFlag{
Name: "genesis",
Usage: "'path to genesis file' - sets the network genesis configuration.",
}
RPCGlobalGasCapFlag = cli.Uint64Flag{
Name: "rpc.gascap",
Usage: "Sets a cap on gas that can be used in mtc_call/estimateGas (0=infinite)",
Value: gossip.DefaultConfig(cachescale.Identity).RPCGasCap,
}
RPCGlobalTxFeeCapFlag = cli.Float64Flag{
Name: "rpc.txfeecap",
Usage: "Sets a cap on transaction fee (in MTC) that can be sent via the RPC APIs (0 = no cap)",
Value: gossip.DefaultConfig(cachescale.Identity).RPCTxFeeCap,
}
AllowedMetatechchainGenesisHashes = map[uint64]hash.Hash{
metatechchain.MainNetworkID: hash.HexToHash("0x8895b98d25c653773a31be420a6a29d322a10107e76dff37dc694ad02ebacd01"),
metatechchain.TestNetworkID: hash.HexToHash("0xc4a5fc96e575a16a9a0c7349d44dc4d0f602a54e0a8543360c2fee4c3937b49e"),
}
)
const (
// DefaultCacheSize is calculated as memory consumption in a worst case scenario with default configuration
// Average memory consumption might be 3-5 times lower than the maximum
DefaultCacheSize = 3200
ConstantCacheSize = 1024
)
// These settings ensure that TOML keys use the same names as Go struct fields.
var tomlSettings = toml.Config{
NormFieldName: func(rt reflect.Type, key string) string {
return key
},
FieldToKey: func(rt reflect.Type, field string) string {
return field
},
MissingField: func(rt reflect.Type, field string) error {
return fmt.Errorf("field '%s' is not defined in %s", field, rt.String())
},
}
type config struct {
Node node.Config
Metatechchain gossip.Config
MetatechchainStore gossip.StoreConfig
Meta abft.Config
MetaStore abft.StoreConfig
VectorClock vecmt.IndexConfig
}
func (c *config) AppConfigs() integration.Configs {
return integration.Configs{
Metatechchain: c.Metatechchain,
MetatechchainStore: c.MetatechchainStore,
Meta: c.Meta,
MetaStore: c.MetaStore,
VectorClock: c.VectorClock,
AllowedGenesis: AllowedMetatechchainGenesisHashes,
}
}
func loadAllConfigs(file string, cfg *config) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg)
// Add file name to errors that have a line number.
if _, ok := err.(*toml.LineError); ok {
err = errors.New(file + ", " + err.Error())
}
if err != nil {
return errors.New(fmt.Sprintf("TOML config file error: %v.\n"+
"Use 'dumpconfig' command to get an example config file.\n"+
"If node was recently upgraded and a previous network config file is used, then check updates for the config file.", err))
}
return err
}
func getMetatechchainGenesis(ctx *cli.Context) integration.InputGenesis {
var genesis integration.InputGenesis
switch {
case ctx.GlobalIsSet(FakeNetFlag.Name):
_, num, err := parseFakeGen(ctx.GlobalString(FakeNetFlag.Name))
if err != nil {
log.Crit("Invalid flag", "flag", FakeNetFlag.Name, "err", err)
}
fakeGenesisStore := makegenesis.FakeGenesisStore(num, futils.ToMtc(1000000000), futils.ToMtc(5000000))
genesis = integration.InputGenesis{
Hash: fakeGenesisStore.Hash(),
Read: func(store *genesisstore.Store) error {
buf := bytes.NewBuffer(nil)
err = fakeGenesisStore.Export(buf)
if err != nil {
return err
}
return store.Import(buf)
},
Close: func() error {
return nil
},
}
case ctx.GlobalIsSet(GenesisFlag.Name):
genesisPath := ctx.GlobalString(GenesisFlag.Name)
genesisFile, err := os.Open(genesisPath)
if err != nil {
utils.Fatalf("Failed to open genesis file: %v", err)
}
inputGenesisHash, readGenesisStore, err := genesisstore.OpenGenesisStore(genesisFile)
if err != nil {
utils.Fatalf("Failed to read genesis file: %v", err)
}
genesis = integration.InputGenesis{
Hash: inputGenesisHash,
Read: readGenesisStore,
Close: genesisFile.Close,
}
default:
log.Crit("Network genesis is not specified")
}
return genesis
}
func setBootnodes(ctx *cli.Context, urls []string, cfg *node.Config) {
cfg.P2P.BootstrapNodesV5 = []*enode.Node{}
for _, url := range urls {
if url != "" {
node, err := enode.Parse(enode.ValidSchemes, url)
if err != nil {
log.Error("Bootstrap URL invalid", "enode", url, "err", err)
continue
}
cfg.P2P.BootstrapNodesV5 = append(cfg.P2P.BootstrapNodesV5, node)
}
}
cfg.P2P.BootstrapNodes = cfg.P2P.BootstrapNodesV5
}
func setDataDir(ctx *cli.Context, cfg *node.Config) {
defaultDataDir := DefaultDataDir()
switch {
case ctx.GlobalIsSet(utils.DataDirFlag.Name):
cfg.DataDir = ctx.GlobalString(utils.DataDirFlag.Name)
case ctx.GlobalIsSet(FakeNetFlag.Name):
_, num, err := parseFakeGen(ctx.GlobalString(FakeNetFlag.Name))
if err != nil {
log.Crit("Invalid flag", "flag", FakeNetFlag.Name, "err", err)
}
cfg.DataDir = filepath.Join(defaultDataDir, fmt.Sprintf("fakenet-%d", num))
default:
cfg.DataDir = defaultDataDir
}
}
func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
if ctx.GlobalIsSet(utils.GpoMaxGasPriceFlag.Name) {
cfg.MaxPrice = big.NewInt(ctx.GlobalInt64(utils.GpoMaxGasPriceFlag.Name))
}
}
func setTxPool(ctx *cli.Context, cfg *evmcore.TxPoolConfig) {
if ctx.GlobalIsSet(utils.TxPoolLocalsFlag.Name) {
locals := strings.Split(ctx.GlobalString(utils.TxPoolLocalsFlag.Name), ",")
for _, account := range locals {
if trimmed := strings.TrimSpace(account); !common.IsHexAddress(trimmed) {
utils.Fatalf("Invalid account in --txpool.locals: %s", trimmed)
} else {
cfg.Locals = append(cfg.Locals, common.HexToAddress(account))
}
}
}
if ctx.GlobalIsSet(utils.TxPoolNoLocalsFlag.Name) {
cfg.NoLocals = ctx.GlobalBool(utils.TxPoolNoLocalsFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolJournalFlag.Name) {
cfg.Journal = ctx.GlobalString(utils.TxPoolJournalFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolRejournalFlag.Name) {
cfg.Rejournal = ctx.GlobalDuration(utils.TxPoolRejournalFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolPriceLimitFlag.Name) {
cfg.PriceLimit = ctx.GlobalUint64(utils.TxPoolPriceLimitFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolPriceBumpFlag.Name) {
cfg.PriceBump = ctx.GlobalUint64(utils.TxPoolPriceBumpFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolAccountSlotsFlag.Name) {
cfg.AccountSlots = ctx.GlobalUint64(utils.TxPoolAccountSlotsFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolGlobalSlotsFlag.Name) {
cfg.GlobalSlots = ctx.GlobalUint64(utils.TxPoolGlobalSlotsFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolAccountQueueFlag.Name) {
cfg.AccountQueue = ctx.GlobalUint64(utils.TxPoolAccountQueueFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolGlobalQueueFlag.Name) {
cfg.GlobalQueue = ctx.GlobalUint64(utils.TxPoolGlobalQueueFlag.Name)
}
if ctx.GlobalIsSet(utils.TxPoolLifetimeFlag.Name) {
cfg.Lifetime = ctx.GlobalDuration(utils.TxPoolLifetimeFlag.Name)
}
}
func gossipConfigWithFlags(ctx *cli.Context, src gossip.Config) (gossip.Config, error) {
cfg := src
setGPO(ctx, &cfg.GPO)
setTxPool(ctx, &cfg.TxPool)
if ctx.GlobalIsSet(RPCGlobalGasCapFlag.Name) {
cfg.RPCGasCap = ctx.GlobalUint64(RPCGlobalGasCapFlag.Name)
}
if ctx.GlobalIsSet(RPCGlobalTxFeeCapFlag.Name) {
cfg.RPCTxFeeCap = ctx.GlobalFloat64(RPCGlobalTxFeeCapFlag.Name)
}
err := setValidator(ctx, &cfg.Emitter)
if err != nil {
return cfg, err
}
return cfg, nil
}
func gossipStoreConfigWithFlags(ctx *cli.Context, src gossip.StoreConfig) (gossip.StoreConfig, error) {
cfg := src
if !ctx.GlobalBool(utils.SnapshotFlag.Name) {
cfg.EVM.EnableSnapshots = false
}
return cfg, nil
}
func nodeConfigWithFlags(ctx *cli.Context, cfg node.Config) node.Config {
utils.SetNodeConfig(ctx, &cfg)
if !ctx.GlobalIsSet(FakeNetFlag.Name) {
setBootnodes(ctx, Bootnodes, &cfg)
}
setDataDir(ctx, &cfg)
return cfg
}
func cacheScaler(ctx *cli.Context) cachescale.Func {
if !ctx.GlobalIsSet(CacheFlag.Name) {
return cachescale.Identity
}
totalCache := ctx.GlobalInt(CacheFlag.Name)
if totalCache < DefaultCacheSize {
log.Crit("Invalid flag", "flag", CacheFlag.Name, "err", fmt.Sprintf("minimum cache size is %d MB", DefaultCacheSize))
}
return cachescale.Ratio{
Base: DefaultCacheSize - ConstantCacheSize,
Target: uint64(totalCache - ConstantCacheSize),
}
}
func mayMakeAllConfigs(ctx *cli.Context) (*config, error) {
// Defaults (low priority)
cacheRatio := cacheScaler(ctx)
cfg := config{
Node: defaultNodeConfig(),
Metatechchain: gossip.DefaultConfig(cacheRatio),
MetatechchainStore: gossip.DefaultStoreConfig(cacheRatio),
Meta: abft.DefaultConfig(),
MetaStore: abft.DefaultStoreConfig(cacheRatio),
VectorClock: vecmt.DefaultConfig(cacheRatio),
}
if ctx.GlobalIsSet(FakeNetFlag.Name) {
_, num, _ := parseFakeGen(ctx.GlobalString(FakeNetFlag.Name))
cfg.Metatechchain = gossip.FakeConfig(num, cacheRatio)
}
// Load config file (medium priority)
if file := ctx.GlobalString(configFileFlag.Name); file != "" {
if err := loadAllConfigs(file, &cfg); err != nil {
return &cfg, err
}
}
// Apply flags (high priority)
var err error
cfg.Metatechchain, err = gossipConfigWithFlags(ctx, cfg.Metatechchain)
if err != nil {
return nil, err
}
cfg.MetatechchainStore, err = gossipStoreConfigWithFlags(ctx, cfg.MetatechchainStore)
if err != nil {
return nil, err
}
cfg.Node = nodeConfigWithFlags(ctx, cfg.Node)
if cfg.Metatechchain.Emitter.Validator.ID != 0 && len(cfg.Metatechchain.Emitter.PrevEmittedEventFile.Path) == 0 {
cfg.Metatechchain.Emitter.PrevEmittedEventFile.Path = cfg.Node.ResolvePath(path.Join("emitter", fmt.Sprintf("last-%d", cfg.Metatechchain.Emitter.Validator.ID)))
}
if err := cfg.Metatechchain.Validate(); err != nil {
return nil, err
}
return &cfg, nil
}
func makeAllConfigs(ctx *cli.Context) *config {
cfg, err := mayMakeAllConfigs(ctx)
if err != nil {
utils.Fatalf("%v", err)
}
return cfg
}
func defaultNodeConfig() node.Config {
cfg := NodeDefaultConfig
cfg.Name = clientIdentifier
cfg.Version = params.VersionWithCommit(gitCommit, gitDate)
cfg.HTTPModules = append(cfg.HTTPModules, "eth", "mtc", "dag", "sfc", "abft", "web3")
cfg.WSModules = append(cfg.WSModules, "eth", "mtc", "dag", "sfc", "abft", "web3")
cfg.IPCPath = "metatechchain.ipc"
cfg.DataDir = DefaultDataDir()
return cfg
}
// dumpConfig is the dumpconfig command.
func dumpConfig(ctx *cli.Context) error {
cfg := makeAllConfigs(ctx)
comment := ""
out, err := tomlSettings.Marshal(&cfg)
if err != nil {
return err
}
dump := os.Stdout
if ctx.NArg() > 0 {
dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer dump.Close()
}
dump.WriteString(comment)
dump.Write(out)
return nil
}
func checkConfig(ctx *cli.Context) error {
_, err := mayMakeAllConfigs(ctx)
return err
}