hermez-node/config/config.go
config/config.goRaw
1package config
2
3import (
4 "fmt"
5 "io/ioutil"
6 "time"
7
8 "github.com/BurntSushi/toml"
9 ethCommon "github.com/ethereum/go-ethereum/common"
10 "gopkg.in/go-playground/validator.v9"
11)
12
13// Duration is a wrapper type that parses time duration from text.
14type Duration struct {
15 time.Duration
16}
17
18// UnmarshalText unmarshalls time duration from text.
19func (d *Duration) UnmarshalText(data []byte) error {
20 duration, err := time.ParseDuration(string(data))
21 if err != nil {
22 return err
23 }
24 d.Duration = duration
25 return nil
26}
27
28// Coordinator is the coordinator specific configuration.
29type Coordinator struct {
30 ForgerAddress ethCommon.Address `validate:"required"`
31 ForgeLoopInterval Duration `validate:"required"`
32}
33
34// Node is the hermez node configuration.
35type Node struct {
36 StateDB struct {
37 Path string
38 } `validate:"required"`
39 PostgreSQL struct {
40 Port int `validate:"required"`
41 Host string `validate:"required"`
42 User string `validate:"required"`
43 Password string `validate:"required"`
44 } `validate:"required"`
45 L2DB struct {
46 Name string `validate:"required"`
47 SafetyPeriod uint16 `validate:"required"`
48 MaxTxs uint32 `validate:"required"`
49 TTL Duration `validate:"required"`
50 } `validate:"required"`
51 HistoryDB struct {
52 Name string `validate:"required"`
53 } `validate:"required"`
54 Web3 struct {
55 URL string `validate:"required"`
56 } `validate:"required"`
57 TxSelector struct {
58 Path string `validate:"required"`
59 } `validate:"required"`
60 BatchBuilder struct {
61 Path string `validate:"required"`
62 } `validate:"required"`
63 Synchronizer struct {
64 SyncLoopInterval Duration `validate:"required"`
65 } `validate:"required"`
66}
67
68// Load loads a generic config.
69func Load(path string, cfg interface{}) error {
70 bs, err := ioutil.ReadFile(path) //nolint:gosec
71 if err != nil {
72 return err
73 }
74 cfgToml := string(bs)
75 if _, err := toml.Decode(cfgToml, cfg); err != nil {
76 return err
77 }
78 validate := validator.New()
79 if err := validate.Struct(cfg); err != nil {
80 return fmt.Errorf("error validating configuration file: %w", err)
81 }
82 return nil
83}
84
85// LoadCoordinator loads the Coordinator configuration from path.
86func LoadCoordinator(path string) (*Coordinator, error) {
87 var cfg Coordinator
88 if err := Load(path, &cfg); err != nil {
89 return nil, fmt.Errorf("error loading coordinator configuration file: %w", err)
90 }
91 return &cfg, nil
92}
93
94// LoadNode loads the Node configuration from path.
95func LoadNode(path string) (*Node, error) {
96 var cfg Node
97 if err := Load(path, &cfg); err != nil {
98 return nil, fmt.Errorf("error loading node configuration file: %w", err)
99 }
100 return &cfg, nil
101}