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