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