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