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	// L2DB is the DB that holds the pool of L2Txs
 95	L2DB struct {
 96		// SafetyPeriod is the number of batches after which
 97		// non-pending L2Txs are deleted from the pool
 98		SafetyPeriod common.BatchNum `validate:"required"`
 99		// MaxTxs is the maximum number of pending L2Txs that can be
100		// stored in the pool.  Once this number of pending L2Txs is
101		// reached, inserts to the pool will be denied until some of
102		// the pending txs are forged.
103		MaxTxs uint32 `validate:"required"`
104		// TTL is the Time To Live for L2Txs in the pool.  Once MaxTxs
105		// L2Txs is reached, L2Txs older than TTL will be deleted.
106		TTL Duration `validate:"required"`
107		// PurgeBatchDelay is the delay between batches to purge
108		// outdated transactions.  Oudated L2Txs are those that have
109		// been forged or marked as invalid for longer than the
110		// SafetyPeriod and pending L2Txs that have been in the pool
111		// for longer than TTL once there are MaxTxs.
112		PurgeBatchDelay int64 `validate:"required"`
113		// InvalidateBatchDelay is the delay between batches to mark
114		// invalid transactions due to nonce lower than the account
115		// nonce.
116		InvalidateBatchDelay int64 `validate:"required"`
117		// PurgeBlockDelay is the delay between blocks to purge
118		// outdated transactions.  Oudated L2Txs are those that have
119		// been forged or marked as invalid for longer than the
120		// SafetyPeriod and pending L2Txs that have been in the pool
121		// for longer than TTL once there are MaxTxs.
122		PurgeBlockDelay int64 `validate:"required"`
123		// InvalidateBlockDelay is the delay between blocks to mark
124		// invalid transactions due to nonce lower than the account
125		// nonce.
126		InvalidateBlockDelay int64 `validate:"required"`
127	} `validate:"required"`
128	TxSelector struct {
129		// Path where the TxSelector StateDB is stored
130		Path string `validate:"required"`
131	} `validate:"required"`
132	BatchBuilder struct {
133		// Path where the BatchBuilder StateDB is stored
134		Path string `validate:"required"`
135	} `validate:"required"`
136	ServerProofs []ServerProof `validate:"required"`
137	Circuit      struct {
138		// MaxTx is the maximum number of txs supported by the circuit
139		MaxTx int64 `validate:"required"`
140		// NLevels is the maximum number of merkle tree levels
141		// supported by the circuit
142		NLevels int64 `validate:"required"`
143	} `validate:"required"`
144	EthClient struct {
145		// MaxGasPrice is the maximum gas price allowed for ethereum
146		// transactions
147		MaxGasPrice *big.Int `validate:"required"`
148		// GasPriceIncPerc is the percentage increase of gas price set
149		// in an ethereum transaction from the suggested gas price by
150		// the ehtereum node
151		GasPriceIncPerc int64
152		// CheckLoopInterval is the waiting interval between receipt
153		// checks of ethereum transactions in the TxManager
154		CheckLoopInterval Duration `validate:"required"`
155		// Attempts is the number of attempts to do an eth client RPC
156		// call before giving up
157		Attempts int `validate:"required"`
158		// AttemptsDelay is delay between attempts do do an eth client
159		// RPC call
160		AttemptsDelay Duration `validate:"required"`
161		// TxResendTimeout is the timeout after which a non-mined
162		// ethereum transaction will be resent (reusing the nonce) with
163		// a newly calculated gas price
164		TxResendTimeout Duration `validate:"required"`
165		// NoReuseNonce disables reusing nonces of pending transactions for
166		// new replacement transactions
167		NoReuseNonce bool
168		// Keystore is the ethereum keystore where private keys are kept
169		Keystore struct {
170			// Path to the keystore
171			Path string `validate:"required"`
172			// Password used to decrypt the keys in the keystore
173			Password string `validate:"required"`
174		} `validate:"required"`
175	} `validate:"required"`
176	API struct {
177		// Coordinator enables the coordinator API endpoints
178		Coordinator bool
179	} `validate:"required"`
180	Debug struct {
181		// BatchPath if set, specifies the path where batchInfo is stored
182		// in JSON in every step/update of the pipeline
183		BatchPath string
184		// LightScrypt if set, uses light parameters for the ethereum
185		// keystore encryption algorithm.
186		LightScrypt bool
187		// RollupVerifierIndex is the index of the verifier to use in
188		// the Rollup smart contract.  The verifier chosen by index
189		// must match with the Circuit parameters.
190		RollupVerifierIndex *int
191	}
192}
193
194// Node is the hermez node configuration.
195type Node struct {
196	PriceUpdater struct {
197		// Interval between price updater calls
198		Interval Duration `valudate:"required"`
199		// URL of the token prices provider
200		URL string `valudate:"required"`
201		// Type of the API of the token prices provider
202		Type string `valudate:"required"`
203	} `validate:"required"`
204	StateDB struct {
205		// Path where the synchronizer StateDB is stored
206		Path string `validate:"required"`
207		// Keep is the number of checkpoints to keep
208		Keep int `validate:"required"`
209	} `validate:"required"`
210	PostgreSQL struct {
211		// Port of the PostgreSQL server
212		Port int `validate:"required"`
213		// Host of the PostgreSQL server
214		Host string `validate:"required"`
215		// User of the PostgreSQL server
216		User string `validate:"required"`
217		// Password of the PostgreSQL server
218		Password string `validate:"required"`
219		// Name of the PostgreSQL server database
220		Name string `validate:"required"`
221	} `validate:"required"`
222	Web3 struct {
223		// URL is the URL of the web3 ethereum-node RPC server
224		URL string `validate:"required"`
225	} `validate:"required"`
226	Synchronizer struct {
227		// SyncLoopInterval is the interval between attempts to
228		// synchronize a new block from an ethereum node
229		SyncLoopInterval Duration `validate:"required"`
230		// StatsRefreshPeriod is the interval between updates of the
231		// synchronizer state Eth parameters (`Eth.LastBlock` and
232		// `Eth.LastBatch`).  This value only affects the reported % of
233		// synchronization of blocks and batches, nothing else.
234		StatsRefreshPeriod Duration `validate:"required"`
235	} `validate:"required"`
236	SmartContracts struct {
237		// Rollup is the address of the Hermez.sol smart contract
238		Rollup ethCommon.Address `validate:"required"`
239		// Rollup is the address of the HermezAuctionProtocol.sol smart
240		// contract
241		Auction ethCommon.Address `validate:"required"`
242		// WDelayer is the address of the WithdrawalDelayer.sol smart
243		// contract
244		WDelayer ethCommon.Address `validate:"required"`
245		// TokenHEZ is the address of the HEZTokenFull.sol smart
246		// contract
247		TokenHEZ ethCommon.Address `validate:"required"`
248		// TokenHEZName is the name of the HEZ token deployed at
249		// TokenHEZ address
250		TokenHEZName string `validate:"required"`
251	} `validate:"required"`
252	API struct {
253		// Address where the API will listen if set
254		Address string
255		// Explorer enables the Explorer API endpoints
256		Explorer bool
257		// UpdateMetricsInterval is the interval between updates of the
258		// API metrics
259		UpdateMetricsInterval Duration
260		// UpdateRecommendedFeeInterval is the interval between updates of the
261		// recommended fees
262		UpdateRecommendedFeeInterval Duration
263		// Maximum concurrent connections allowed between API and SQL
264		MaxSQLConnections int `validate:"required"`
265		// SQLConnectionTimeout is the maximum amount of time that an API request
266		// can wait to stablish a SQL connection
267		SQLConnectionTimeout Duration
268	} `validate:"required"`
269	Debug struct {
270		// APIAddress is the address where the debugAPI will listen if
271		// set
272		APIAddress string
273		// MeddlerLogs enables meddler debug mode, where unused columns and struct
274		// fields will be logged
275		MeddlerLogs bool
276	}
277	Coordinator Coordinator `validate:"-"`
278}
279
280// Load loads a generic config.
281func Load(path string, cfg interface{}) error {
282	bs, err := ioutil.ReadFile(path) //nolint:gosec
283	if err != nil {
284		return tracerr.Wrap(err)
285	}
286	cfgToml := string(bs)
287	if _, err := toml.Decode(cfgToml, cfg); err != nil {
288		return tracerr.Wrap(err)
289	}
290	return nil
291}
292
293// LoadCoordinator loads the Coordinator configuration from path.
294func LoadCoordinator(path string) (*Node, error) {
295	var cfg Node
296	if err := Load(path, &cfg); err != nil {
297		return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err))
298	}
299	validate := validator.New()
300	if err := validate.Struct(cfg); err != nil {
301		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
302	}
303	if err := validate.Struct(cfg.Coordinator); err != nil {
304		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
305	}
306	return &cfg, nil
307}
308
309// LoadNode loads the Node configuration from path.
310func LoadNode(path string) (*Node, error) {
311	var cfg Node
312	if err := Load(path, &cfg); err != nil {
313		return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err))
314	}
315	validate := validator.New()
316	if err := validate.Struct(cfg); err != nil {
317		return nil, tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err))
318	}
319	return &cfg, nil
320}