arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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	"github.com/hermeznetwork/hermez-node/common"
 11	"github.com/hermeznetwork/tracerr"
 12	"github.com/iden3/go-iden3-crypto/babyjub"
 13	"gopkg.in/go-playground/validator.v9"
 14)
 15
 16// Duration is a wrapper type that parses time duration from text.
 17type Duration struct {
 18	time.Duration `validate:"required"`
 19}
 20
 21// UnmarshalText unmarshalls time duration from text.
 22func (d *Duration) UnmarshalText(data []byte) error {
 23	duration, err := time.ParseDuration(string(data))
 24	if err != nil {
 25		return tracerr.Wrap(err)
 26	}
 27	d.Duration = duration
 28	return nil
 29}
 30
 31// ServerProof is the server proof configuration data.
 32type ServerProof struct {
 33	// URL is the server proof API URL
 34	URL string `validate:"required"`
 35}
 36
 37// Coordinator is the coordinator specific configuration.
 38type Coordinator struct {
 39	// ForgerAddress is the address under which this coordinator is forging
 40	ForgerAddress ethCommon.Address `validate:"required"`
 41	// FeeAccount is the Hermez account that the coordinator uses to receive fees
 42	FeeAccount struct {
 43		// Address is the ethereum address of the account to receive fees
 44		Address ethCommon.Address `validate:"required"`
 45		// BJJ is the baby jub jub public key of the account to receive fees
 46		BJJ babyjub.PublicKeyComp `validate:"required"`
 47	} `validate:"required"`
 48	// ConfirmBlocks is the number of confirmation blocks to wait for sent
 49	// ethereum transactions before forgetting about them
 50	ConfirmBlocks int64 `validate:"required"`
 51	// L1BatchTimeoutPerc is the portion of the range before the L1Batch
 52	// timeout that will trigger a schedule to forge an L1Batch
 53	L1BatchTimeoutPerc float64 `validate:"required"`
 54	// ProofServerPollInterval is the waiting interval between polling the
 55	// ProofServer while waiting for a particular status
 56	ProofServerPollInterval Duration `validate:"required"`
 57	// ForgeRetryInterval is the waiting interval between calls forge a
 58	// batch after an error
 59	ForgeRetryInterval Duration `validate:"required"`
 60	// SyncRetryInterval is the waiting interval between calls to the main
 61	// handler of a synced block after an error
 62	SyncRetryInterval Duration `validate:"required"`
 63	// L2DB is the DB that holds the pool of L2Txs
 64	L2DB struct {
 65		// SafetyPeriod is the number of batches after which
 66		// non-pending L2Txs are deleted from the pool
 67		SafetyPeriod common.BatchNum `validate:"required"`
 68		// MaxTxs is the number of L2Txs that once reached triggers
 69		// deletion of old L2Txs
 70		MaxTxs uint32 `validate:"required"`
 71		// TTL is the Time To Live for L2Txs in the pool.  Once MaxTxs
 72		// L2Txs is reached, L2Txs older than TTL will be deleted.
 73		TTL Duration `validate:"required"`
 74		// PurgeBatchDelay is the delay between batches to purge outdated transactions
 75		PurgeBatchDelay int64 `validate:"required"`
 76		// InvalidateBatchDelay is the delay between batches to mark invalid transactions
 77		InvalidateBatchDelay int64 `validate:"required"`
 78		// PurgeBlockDelay is the delay between blocks to purge outdated transactions
 79		PurgeBlockDelay int64 `validate:"required"`
 80		// InvalidateBlockDelay is the delay between blocks to mark invalid transactions
 81		InvalidateBlockDelay int64 `validate:"required"`
 82	} `validate:"required"`
 83	TxSelector struct {
 84		// Path where the TxSelector StateDB is stored
 85		Path string `validate:"required"`
 86	} `validate:"required"`
 87	BatchBuilder struct {
 88		// Path where the BatchBuilder StateDB is stored
 89		Path string `validate:"required"`
 90	} `validate:"required"`
 91	ServerProofs []ServerProof `validate:"required"`
 92	Circuit      struct {
 93		// MaxTx is the maximum number of txs supported by the circuit
 94		MaxTx int64 `validate:"required"`
 95		// NLevels is the maximum number of merkle tree levels
 96		// supported by the circuit
 97		NLevels int64 `validate:"required"`
 98	} `validate:"required"`
 99	EthClient struct {
100		// CallGasLimit is the default gas limit set for ethereum
101		// calls, except for methods  where a particular gas limit is
102		// harcoded because it's known to be a big value
103		CallGasLimit uint64 `validate:"required"`
104		// GasPriceDiv is the gas price division
105		GasPriceDiv uint64 `validate:"required"`
106		// CheckLoopInterval is the waiting interval between receipt
107		// checks of ethereum transactions in the TxManager
108		CheckLoopInterval Duration `validate:"required"`
109		// Attempts is the number of attempts to do an eth client RPC
110		// call before giving up
111		Attempts int `validate:"required"`
112		// AttemptsDelay is delay between attempts do do an eth client
113		// RPC call
114		AttemptsDelay Duration `validate:"required"`
115		// Keystore is the ethereum keystore where private keys are kept
116		Keystore struct {
117			// Path to the keystore
118			Path string `validate:"required"`
119			// Password used to decrypt the keys in the keystore
120			Password string `validate:"required"`
121		} `validate:"required"`
122	} `validate:"required"`
123	API struct {
124		// Coordinator enables the coordinator API endpoints
125		Coordinator bool
126	} `validate:"required"`
127	Debug struct {
128		// BatchPath if set, specifies the path where batchInfo is stored
129		// in JSON in every step/update of the pipeline
130		BatchPath string
131		// LightScrypt if set, uses light parameters for the ethereum
132		// keystore encryption algorithm.
133		LightScrypt bool
134		// RollupVerifierIndex is the index of the verifier to use in
135		// the Rollup smart contract.  The verifier chosen by index
136		// must match with the Circuit parameters.
137		RollupVerifierIndex *int
138	}
139}
140
141// Node is the hermez node configuration.
142type Node struct {
143	PriceUpdater struct {
144		// Interval between price updater calls
145		Interval Duration `valudate:"required"`
146		// URL of the token prices provider
147		URL string `valudate:"required"`
148		// Type of the API of the token prices provider
149		Type string `valudate:"required"`
150	} `validate:"required"`
151	StateDB struct {
152		// Path where the synchronizer StateDB is stored
153		Path string `validate:"required"`
154		// Keep is the number of checkpoints to keep
155		Keep int `validate:"required"`
156	} `validate:"required"`
157	PostgreSQL struct {
158		// Port of the PostgreSQL server
159		Port int `validate:"required"`
160		// Host of the PostgreSQL server
161		Host string `validate:"required"`
162		// User of the PostgreSQL server
163		User string `validate:"required"`
164		// Password of the PostgreSQL server
165		Password string `validate:"required"`
166		// Name of the PostgreSQL server database
167		Name string `validate:"required"`
168	} `validate:"required"`
169	Web3 struct {
170		// URL is the URL of the web3 ethereum-node RPC server
171		URL string `validate:"required"`
172	} `validate:"required"`
173	Synchronizer struct {
174		// SyncLoopInterval is the interval between attempts to
175		// synchronize a new block from an ethereum node
176		SyncLoopInterval Duration `validate:"required"`
177		// StatsRefreshPeriod is the interval between updates of the
178		// synchronizer state Eth parameters (`Eth.LastBlock` and
179		// `Eth.LastBatch`).  This value only affects the reported % of
180		// synchronization of blocks and batches, nothing else.
181		StatsRefreshPeriod Duration `validate:"required"`
182	} `validate:"required"`
183	SmartContracts struct {
184		// Rollup is the address of the Hermez.sol smart contract
185		Rollup ethCommon.Address `validate:"required"`
186		// Rollup is the address of the HermezAuctionProtocol.sol smart
187		// contract
188		Auction ethCommon.Address `validate:"required"`
189		// WDelayer is the address of the WithdrawalDelayer.sol smart
190		// contract
191		WDelayer ethCommon.Address `validate:"required"`
192		// TokenHEZ is the address of the HEZTokenFull.sol smart
193		// contract
194		TokenHEZ ethCommon.Address `validate:"required"`
195		// TokenHEZName is the name of the HEZ token deployed at
196		// TokenHEZ address
197		TokenHEZName string `validate:"required"`
198	} `validate:"required"`
199	API struct {
200		// Address where the API will listen if set
201		Address string
202		// Explorer enables the Explorer API endpoints
203		Explorer bool
204		// UpdateMetricsInterval is the interval between updates of the
205		// API metrics
206		UpdateMetricsInterval Duration
207		// UpdateMetricsInterval is the interval between updates of the
208		// recommended fees
209		UpdateRecommendedFeeInterval Duration
210	} `validate:"required"`
211	Debug struct {
212		// APIAddress is the address where the debugAPI will listen if
213		// set
214		APIAddress string
215		// MeddlerLogs enables meddler debug mode, where unused columns and struct
216		// fields will be logged
217		MeddlerLogs bool
218	}
219	Coordinator Coordinator `validate:"-"`
220}
221
222// Load loads a generic config.
223func Load(path string, cfg interface{}) error {
224	bs, err := ioutil.ReadFile(path) //nolint:gosec
225	if err != nil {
226		return tracerr.Wrap(err)
227	}
228	cfgToml := string(bs)
229	if _, err := toml.Decode(cfgToml, cfg); err != nil {
230		return tracerr.Wrap(err)
231	}
232	return nil
233}
234
235// LoadCoordinator loads the Coordinator configuration from path.
236func LoadCoordinator(path string) (*Node, error) {
237	var cfg Node
238	if err := Load(path, &cfg); err != nil {
239		return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err))
240	}
241	validate := validator.New()
242	if err := validate.Struct(cfg); err != nil {
243		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
244	}
245	if err := validate.Struct(cfg.Coordinator); err != nil {
246		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
247	}
248	return &cfg, nil
249}
250
251// LoadNode loads the Node configuration from path.
252func LoadNode(path string) (*Node, error) {
253	var cfg Node
254	if err := Load(path, &cfg); err != nil {
255		return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err))
256	}
257	validate := validator.New()
258	if err := validate.Struct(cfg); err != nil {
259		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
260	}
261	return &cfg, nil
262}