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