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	"math/big"
  7	"time"
  8
  9	"github.com/BurntSushi/toml"
 10	ethCommon "github.com/ethereum/go-ethereum/common"
 11	"github.com/hermeznetwork/hermez-node/common"
 12	"github.com/hermeznetwork/tracerr"
 13	"github.com/iden3/go-iden3-crypto/babyjub"
 14	"gopkg.in/go-playground/validator.v9"
 15)
 16
 17// Duration is a wrapper type that parses time duration from text.
 18type Duration struct {
 19	time.Duration `validate:"required"`
 20}
 21
 22// UnmarshalText unmarshalls time duration from text.
 23func (d *Duration) UnmarshalText(data []byte) error {
 24	duration, err := time.ParseDuration(string(data))
 25	if err != nil {
 26		return tracerr.Wrap(err)
 27	}
 28	d.Duration = duration
 29	return nil
 30}
 31
 32// ServerProof is the server proof configuration data.
 33type ServerProof struct {
 34	// URL is the server proof API URL
 35	URL string `validate:"required"`
 36}
 37
 38// Coordinator is the coordinator specific configuration.
 39type Coordinator struct {
 40	// ForgerAddress is the address under which this coordinator is forging
 41	ForgerAddress ethCommon.Address `validate:"required"`
 42	// FeeAccount is the Hermez account that the coordinator uses to receive fees
 43	FeeAccount struct {
 44		// Address is the ethereum address of the account to receive fees
 45		Address ethCommon.Address `validate:"required"`
 46		// BJJ is the baby jub jub public key of the account to receive fees
 47		BJJ babyjub.PublicKeyComp `validate:"required"`
 48	} `validate:"required"`
 49	// ConfirmBlocks is the number of confirmation blocks to wait for sent
 50	// ethereum transactions before forgetting about them
 51	ConfirmBlocks int64 `validate:"required"`
 52	// L1BatchTimeoutPerc is the portion of the range before the L1Batch
 53	// timeout that will trigger a schedule to forge an L1Batch
 54	L1BatchTimeoutPerc float64 `validate:"required"`
 55	// StartSlotBlocksDelay is the number of blocks of delay to wait before
 56	// starting the pipeline when we reach a slot in which we can forge.
 57	StartSlotBlocksDelay int64
 58	// ScheduleBatchBlocksAheadCheck is the number of blocks ahead in which
 59	// the forger address is checked to be allowed to forge (apart from
 60	// checking the next block), used to decide when to stop scheduling new
 61	// batches (by stopping the pipeline).
 62	// For example, if we are at block 10 and ScheduleBatchBlocksAheadCheck
 63	// is 5, eventhough at block 11 we canForge, the pipeline will be
 64	// stopped if we can't forge at block 15.
 65	// This value should be the expected number of blocks it takes between
 66	// scheduling a batch and having it mined.
 67	ScheduleBatchBlocksAheadCheck int64
 68	// SendBatchBlocksMarginCheck is the number of margin blocks ahead in
 69	// which the coordinator is also checked to be allowed to forge, apart
 70	// from the next block; used to decide when to stop sending batches to
 71	// the smart contract.
 72	// For example, if we are at block 10 and SendBatchBlocksMarginCheck is
 73	// 5, eventhough at block 11 we canForge, the batch will be discarded
 74	// if we can't forge at block 15.
 75	SendBatchBlocksMarginCheck int64
 76	// ProofServerPollInterval is the waiting interval between polling the
 77	// ProofServer while waiting for a particular status
 78	ProofServerPollInterval Duration `validate:"required"`
 79	// ForgeRetryInterval is the waiting interval between calls forge a
 80	// batch after an error
 81	ForgeRetryInterval Duration `validate:"required"`
 82	// ForgeDelay is the delay after which a batch is forged if the slot is
 83	// already committed.  If set to 0s, the coordinator will continuously
 84	// forge at the maximum rate.
 85	ForgeDelay Duration `validate:"-"`
 86	// ForgeNoTxsDelay is the delay after which a batch is forged even if
 87	// there are no txs to forge if the slot is already committed.  If set
 88	// to 0s, the coordinator will continuously forge even if the batches
 89	// are empty.
 90	ForgeNoTxsDelay Duration `validate:"-"`
 91	// SyncRetryInterval is the waiting interval between calls to the main
 92	// handler of a synced block after an error
 93	SyncRetryInterval Duration `validate:"required"`
 94	// PurgeByExtDelInterval is the waiting interval between calls
 95	// to the PurgeByExternalDelete function of the l2db which deletes
 96	// pending txs externally marked by the column `external_delete`
 97	PurgeByExtDelInterval Duration `validate:"required"`
 98	// L2DB is the DB that holds the pool of L2Txs
 99	L2DB struct {
100		// SafetyPeriod is the number of batches after which
101		// non-pending L2Txs are deleted from the pool
102		SafetyPeriod common.BatchNum `validate:"required"`
103		// MaxTxs is the maximum number of pending L2Txs that can be
104		// stored in the pool.  Once this number of pending L2Txs is
105		// reached, inserts to the pool will be denied until some of
106		// the pending txs are forged.
107		MaxTxs uint32 `validate:"required"`
108		// TTL is the Time To Live for L2Txs in the pool.  Once MaxTxs
109		// L2Txs is reached, L2Txs older than TTL will be deleted.
110		TTL Duration `validate:"required"`
111		// PurgeBatchDelay is the delay between batches to purge
112		// outdated transactions.  Oudated L2Txs are those that have
113		// been forged or marked as invalid for longer than the
114		// SafetyPeriod and pending L2Txs that have been in the pool
115		// for longer than TTL once there are MaxTxs.
116		PurgeBatchDelay int64 `validate:"required"`
117		// InvalidateBatchDelay is the delay between batches to mark
118		// invalid transactions due to nonce lower than the account
119		// nonce.
120		InvalidateBatchDelay int64 `validate:"required"`
121		// PurgeBlockDelay is the delay between blocks to purge
122		// outdated transactions.  Oudated L2Txs are those that have
123		// been forged or marked as invalid for longer than the
124		// SafetyPeriod and pending L2Txs that have been in the pool
125		// for longer than TTL once there are MaxTxs.
126		PurgeBlockDelay int64 `validate:"required"`
127		// InvalidateBlockDelay is the delay between blocks to mark
128		// invalid transactions due to nonce lower than the account
129		// nonce.
130		InvalidateBlockDelay int64 `validate:"required"`
131	} `validate:"required"`
132	TxSelector struct {
133		// Path where the TxSelector StateDB is stored
134		Path string `validate:"required"`
135	} `validate:"required"`
136	BatchBuilder struct {
137		// Path where the BatchBuilder StateDB is stored
138		Path string `validate:"required"`
139	} `validate:"required"`
140	ServerProofs []ServerProof `validate:"required"`
141	Circuit      struct {
142		// MaxTx is the maximum number of txs supported by the circuit
143		MaxTx int64 `validate:"required"`
144		// NLevels is the maximum number of merkle tree levels
145		// supported by the circuit
146		NLevels int64 `validate:"required"`
147	} `validate:"required"`
148	EthClient struct {
149		// MaxGasPrice is the maximum gas price allowed for ethereum
150		// transactions
151		MaxGasPrice *big.Int `validate:"required"`
152		// GasPriceIncPerc is the percentage increase of gas price set
153		// in an ethereum transaction from the suggested gas price by
154		// the ehtereum node
155		GasPriceIncPerc int64
156		// CheckLoopInterval is the waiting interval between receipt
157		// checks of ethereum transactions in the TxManager
158		CheckLoopInterval Duration `validate:"required"`
159		// Attempts is the number of attempts to do an eth client RPC
160		// call before giving up
161		Attempts int `validate:"required"`
162		// AttemptsDelay is delay between attempts do do an eth client
163		// RPC call
164		AttemptsDelay Duration `validate:"required"`
165		// TxResendTimeout is the timeout after which a non-mined
166		// ethereum transaction will be resent (reusing the nonce) with
167		// a newly calculated gas price
168		TxResendTimeout Duration `validate:"required"`
169		// NoReuseNonce disables reusing nonces of pending transactions for
170		// new replacement transactions
171		NoReuseNonce bool
172		// Keystore is the ethereum keystore where private keys are kept
173		Keystore struct {
174			// Path to the keystore
175			Path string `validate:"required"`
176			// Password used to decrypt the keys in the keystore
177			Password string `validate:"required"`
178		} `validate:"required"`
179	} `validate:"required"`
180	API struct {
181		// Coordinator enables the coordinator API endpoints
182		Coordinator bool
183	} `validate:"required"`
184	Debug struct {
185		// BatchPath if set, specifies the path where batchInfo is stored
186		// in JSON in every step/update of the pipeline
187		BatchPath string
188		// LightScrypt if set, uses light parameters for the ethereum
189		// keystore encryption algorithm.
190		LightScrypt bool
191		// RollupVerifierIndex is the index of the verifier to use in
192		// the Rollup smart contract.  The verifier chosen by index
193		// must match with the Circuit parameters.
194		RollupVerifierIndex *int
195	}
196}
197
198// Node is the hermez node configuration.
199type Node struct {
200	PriceUpdater struct {
201		// Interval between price updater calls
202		Interval Duration `valudate:"required"`
203		// URL of the token prices provider
204		URL string `valudate:"required"`
205		// Type of the API of the token prices provider
206		Type string `valudate:"required"`
207	} `validate:"required"`
208	StateDB struct {
209		// Path where the synchronizer StateDB is stored
210		Path string `validate:"required"`
211		// Keep is the number of checkpoints to keep
212		Keep int `validate:"required"`
213	} `validate:"required"`
214	PostgreSQL struct {
215		// Port of the PostgreSQL server
216		Port int `validate:"required"`
217		// Host of the PostgreSQL server
218		Host string `validate:"required"`
219		// User of the PostgreSQL server
220		User string `validate:"required"`
221		// Password of the PostgreSQL server
222		Password string `validate:"required"`
223		// Name of the PostgreSQL server database
224		Name string `validate:"required"`
225	} `validate:"required"`
226	Web3 struct {
227		// URL is the URL of the web3 ethereum-node RPC server
228		URL string `validate:"required"`
229	} `validate:"required"`
230	Synchronizer struct {
231		// SyncLoopInterval is the interval between attempts to
232		// synchronize a new block from an ethereum node
233		SyncLoopInterval Duration `validate:"required"`
234		// StatsRefreshPeriod is the interval between updates of the
235		// synchronizer state Eth parameters (`Eth.LastBlock` and
236		// `Eth.LastBatch`).  This value only affects the reported % of
237		// synchronization of blocks and batches, nothing else.
238		StatsRefreshPeriod Duration `validate:"required"`
239		// StoreAccountUpdates when set to true makes the synchronizer
240		// store every account update in the account_update SQL table.
241		// This allows querying nonces and balances from the HistoryDB
242		// via SQL.
243		StoreAccountUpdates bool
244	} `validate:"required"`
245	SmartContracts struct {
246		// Rollup is the address of the Hermez.sol smart contract
247		Rollup ethCommon.Address `validate:"required"`
248		// Rollup is the address of the HermezAuctionProtocol.sol smart
249		// contract
250		Auction ethCommon.Address `validate:"required"`
251		// WDelayer is the address of the WithdrawalDelayer.sol smart
252		// contract
253		WDelayer ethCommon.Address `validate:"required"`
254		// TokenHEZ is the address of the HEZTokenFull.sol smart
255		// contract
256		TokenHEZ ethCommon.Address `validate:"required"`
257		// TokenHEZName is the name of the HEZ token deployed at
258		// TokenHEZ address
259		TokenHEZName string `validate:"required"`
260	} `validate:"required"`
261	API struct {
262		// Address where the API will listen if set
263		Address string
264		// Explorer enables the Explorer API endpoints
265		Explorer bool
266		// UpdateMetricsInterval is the interval between updates of the
267		// API metrics
268		UpdateMetricsInterval Duration
269		// UpdateRecommendedFeeInterval is the interval between updates of the
270		// recommended fees
271		UpdateRecommendedFeeInterval Duration
272		// Maximum concurrent connections allowed between API and SQL
273		MaxSQLConnections int `validate:"required"`
274		// SQLConnectionTimeout is the maximum amount of time that an API request
275		// can wait to stablish a SQL connection
276		SQLConnectionTimeout Duration
277	} `validate:"required"`
278	Debug struct {
279		// APIAddress is the address where the debugAPI will listen if
280		// set
281		APIAddress string
282		// MeddlerLogs enables meddler debug mode, where unused columns and struct
283		// fields will be logged
284		MeddlerLogs bool
285	}
286	Coordinator Coordinator `validate:"-"`
287}
288
289// Load loads a generic config.
290func Load(path string, cfg interface{}) error {
291	bs, err := ioutil.ReadFile(path) //nolint:gosec
292	if err != nil {
293		return tracerr.Wrap(err)
294	}
295	cfgToml := string(bs)
296	if _, err := toml.Decode(cfgToml, cfg); err != nil {
297		return tracerr.Wrap(err)
298	}
299	return nil
300}
301
302// LoadCoordinator loads the Coordinator configuration from path.
303func LoadCoordinator(path string) (*Node, error) {
304	var cfg Node
305	if err := Load(path, &cfg); err != nil {
306		return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err))
307	}
308	validate := validator.New()
309	if err := validate.Struct(cfg); err != nil {
310		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
311	}
312	if err := validate.Struct(cfg.Coordinator); err != nil {
313		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
314	}
315	return &cfg, nil
316}
317
318// LoadNode loads the Node configuration from path.
319func LoadNode(path string) (*Node, error) {
320	var cfg Node
321	if err := Load(path, &cfg); err != nil {
322		return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err))
323	}
324	validate := validator.New()
325	if err := validate.Struct(cfg); err != nil {
326		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
327	}
328	return &cfg, nil
329}