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