hermez-node/eth/ethereum.go
eth/ethereum.goRaw
1package eth
2
3import (
4 "context"
5 "fmt"
6 "math/big"
7 "time"
8
9 "github.com/ethereum/go-ethereum/accounts"
10 "github.com/ethereum/go-ethereum/accounts/abi/bind"
11 ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore"
12 ethCommon "github.com/ethereum/go-ethereum/common"
13 "github.com/ethereum/go-ethereum/core/types"
14 "github.com/ethereum/go-ethereum/ethclient"
15 "github.com/hermeznetwork/hermez-node/common"
16 HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
17 "github.com/hermeznetwork/hermez-node/log"
18 "github.com/hermeznetwork/tracerr"
19)
20
21// ERC20Consts are the constants defined in a particular ERC20 Token instance
22type ERC20Consts struct {
23 Name string
24 Symbol string
25 Decimals uint64
26}
27
28// EthereumInterface is the interface to Ethereum
29type EthereumInterface interface {
30 EthLastBlock() (int64, error)
31 // EthHeaderByNumber(context.Context, *big.Int) (*types.Header, error)
32 EthBlockByNumber(context.Context, int64) (*common.Block, error)
33 EthAddress() (*ethCommon.Address, error)
34 EthTransactionReceipt(context.Context, ethCommon.Hash) (*types.Receipt, error)
35
36 EthERC20Consts(ethCommon.Address) (*ERC20Consts, error)
37 EthChainID() (*big.Int, error)
38}
39
40var (
41 // ErrAccountNil is used when the calls can not be made because the account is nil
42 ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil")
43 // ErrReceiptStatusFailed is used when receiving a failed transaction
44 ErrReceiptStatusFailed = fmt.Errorf("receipt status is failed")
45 // ErrReceiptNotReceived is used when unable to retrieve a transaction
46 ErrReceiptNotReceived = fmt.Errorf("receipt not available")
47 // ErrBlockHashMismatchEvent is used when there's a block hash mismatch
48 // beetween different events of the same block
49 ErrBlockHashMismatchEvent = fmt.Errorf("block hash mismatch in event log")
50)
51
52const (
53 errStrDeploy = "deployment of %s failed: %w"
54 errStrWaitReceipt = "wait receipt of %s deploy failed: %w"
55
56 // default values
57 defaultCallGasLimit = 300000
58 defaultDeployGasLimit = 1000000
59 defaultGasPriceDiv = 100
60 defaultReceiptTimeout = 60
61 defaultIntervalReceiptLoop = 200
62)
63
64// EthereumConfig defines the configuration parameters of the EthereumClient
65type EthereumConfig struct {
66 CallGasLimit uint64
67 DeployGasLimit uint64
68 GasPriceDiv uint64
69 ReceiptTimeout time.Duration
70 IntervalReceiptLoop time.Duration
71}
72
73// EthereumClient is an ethereum client to call Smart Contract methods and check blockchain information.
74type EthereumClient struct {
75 client *ethclient.Client
76 chainID *big.Int
77 account *accounts.Account
78 ks *ethKeystore.KeyStore
79 ReceiptTimeout time.Duration
80 config *EthereumConfig
81 opts *bind.CallOpts
82}
83
84// NewEthereumClient creates a EthereumClient instance. The account is not mandatory (it can
85// be nil). If the account is nil, CallAuth will fail with ErrAccountNil.
86func NewEthereumClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *EthereumConfig) (*EthereumClient, error) {
87 if config == nil {
88 config = &EthereumConfig{
89 CallGasLimit: defaultCallGasLimit,
90 DeployGasLimit: defaultDeployGasLimit,
91 GasPriceDiv: defaultGasPriceDiv,
92 ReceiptTimeout: defaultReceiptTimeout,
93 IntervalReceiptLoop: defaultIntervalReceiptLoop,
94 }
95 }
96 c := &EthereumClient{
97 client: client,
98 account: account,
99 ks: ks,
100 ReceiptTimeout: config.ReceiptTimeout * time.Second,
101 config: config,
102 opts: newCallOpts(),
103 }
104 chainID, err := c.EthChainID()
105 if err != nil {
106 return nil, tracerr.Wrap(err)
107 }
108 c.chainID = chainID
109 return c, nil
110}
111
112// EthChainID returns the ChainID of the ethereum network
113func (c *EthereumClient) EthChainID() (*big.Int, error) {
114 chainID, err := c.client.ChainID(context.Background())
115 if err != nil {
116 return nil, tracerr.Wrap(err)
117 }
118 return chainID, nil
119}
120
121// BalanceAt retieves information about the default account
122func (c *EthereumClient) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
123 return c.client.BalanceAt(context.TODO(), addr, nil)
124}
125
126// Account returns the underlying ethereum account
127func (c *EthereumClient) Account() *accounts.Account {
128 return c.account
129}
130
131// EthAddress returns the ethereum address of the account loaded into the EthereumClient
132func (c *EthereumClient) EthAddress() (*ethCommon.Address, error) {
133 if c.account == nil {
134 return nil, tracerr.Wrap(ErrAccountNil)
135 }
136 return &c.account.Address, nil
137}
138
139// CallAuth performs a Smart Contract method call that requires authorization.
140// This call requires a valid account with Ether that can be spend during the
141// call.
142func (c *EthereumClient) CallAuth(gasLimit uint64,
143 fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
144 if c.account == nil {
145 return nil, tracerr.Wrap(ErrAccountNil)
146 }
147
148 gasPrice, err := c.client.SuggestGasPrice(context.Background())
149 if err != nil {
150 return nil, tracerr.Wrap(err)
151 }
152 inc := new(big.Int).Set(gasPrice)
153 inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
154 gasPrice.Add(gasPrice, inc)
155 log.Debugw("Transaction metadata", "gasPrice", gasPrice)
156
157 auth, err := bind.NewKeyStoreTransactorWithChainID(c.ks, *c.account, c.chainID)
158 if err != nil {
159 return nil, tracerr.Wrap(err)
160 }
161 auth.Value = big.NewInt(0) // in wei
162 if gasLimit == 0 {
163 auth.GasLimit = c.config.CallGasLimit // in units
164 } else {
165 auth.GasLimit = gasLimit // in units
166 }
167 auth.GasPrice = gasPrice
168
169 tx, err := fn(c.client, auth)
170 if tx != nil {
171 log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
172 }
173 return tx, tracerr.Wrap(err)
174}
175
176// ContractData contains the contract data
177type ContractData struct {
178 Address ethCommon.Address
179 Tx *types.Transaction
180 Receipt *types.Receipt
181}
182
183// Deploy a smart contract. `name` is used to log deployment information. fn
184// is a wrapper to the deploy function generated by abigen. In case of error,
185// the returned `ContractData` may have some parameters filled depending on the
186// kind of error that occurred.
187func (c *EthereumClient) Deploy(name string,
188 fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
189 var contractData ContractData
190 log.Infow("Deploying", "contract", name)
191 tx, err := c.CallAuth(
192 c.config.DeployGasLimit,
193 func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
194 addr, tx, _, err := fn(client, auth)
195 if err != nil {
196 return nil, tracerr.Wrap(err)
197 }
198 contractData.Address = addr
199 return tx, nil
200 },
201 )
202 if err != nil {
203 return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err))
204 }
205 log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
206 contractData.Tx = tx
207 receipt, err := c.WaitReceipt(tx)
208 if err != nil {
209 return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err))
210 }
211 contractData.Receipt = receipt
212 return contractData, nil
213}
214
215// Call performs a read only Smart Contract method call.
216func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
217 return fn(c.client)
218}
219
220// WaitReceipt will block until a transaction is confirmed. Internally it
221// polls the state every 200 milliseconds.
222func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
223 return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
224}
225
226// GetReceipt will check if a transaction is confirmed and return
227// immediately, waiting at most 1 second and returning error if the transaction
228// is still pending.
229func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
230 ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
231 defer cancel()
232 return c.waitReceipt(ctx, tx, 0)
233}
234
235// EthTransactionReceipt returns the transaction receipt of the given txHash
236func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
237 return c.client.TransactionReceipt(ctx, txHash)
238}
239
240func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
241 var err error
242 var receipt *types.Receipt
243
244 txHash := tx.Hash()
245 log.Debugw("Waiting for receipt", "tx", txHash.Hex())
246
247 start := time.Now()
248 for {
249 receipt, err = c.client.TransactionReceipt(ctx, txHash)
250 if receipt != nil || time.Since(start) >= timeout {
251 break
252 }
253 time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
254 }
255
256 if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
257 log.Errorw("Failed transaction", "tx", txHash.Hex())
258 return receipt, tracerr.Wrap(ErrReceiptStatusFailed)
259 }
260
261 if receipt == nil {
262 log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err)
263 return receipt, tracerr.Wrap(ErrReceiptNotReceived)
264 }
265 log.Debugw("Successful transaction", "tx", txHash.Hex())
266
267 return receipt, tracerr.Wrap(err)
268}
269
270// EthLastBlock returns the last block number in the blockchain
271func (c *EthereumClient) EthLastBlock() (int64, error) {
272 ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
273 defer cancel()
274 header, err := c.client.HeaderByNumber(ctx, nil)
275 if err != nil {
276 return 0, tracerr.Wrap(err)
277 }
278 return header.Number.Int64(), nil
279}
280
281// EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
282// func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
283// return c.client.HeaderByNumber(ctx, number)
284// }
285
286// EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns
287// *common.Block. If number == -1, the latests known block is returned.
288func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
289 blockNum := big.NewInt(number)
290 if number == -1 {
291 blockNum = nil
292 }
293 block, err := c.client.BlockByNumber(ctx, blockNum)
294 if err != nil {
295 return nil, tracerr.Wrap(err)
296 }
297 b := &common.Block{
298 Num: block.Number().Int64(),
299 Timestamp: time.Unix(int64(block.Time()), 0),
300 ParentHash: block.ParentHash(),
301 Hash: block.Hash(),
302 }
303 return b, nil
304}
305
306// EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
307func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
308 // We use the HEZ token smart contract interfacehere because it's an
309 // ERC20, which allows us to access the standard ERC20 constants.
310 instance, err := HEZ.NewHEZ(tokenAddress, c.client)
311 if err != nil {
312 return nil, tracerr.Wrap(err)
313 }
314 name, err := instance.Name(c.opts)
315 if err != nil {
316 return nil, tracerr.Wrap(err)
317 }
318
319 symbol, err := instance.Symbol(c.opts)
320 if err != nil {
321 return nil, tracerr.Wrap(err)
322 }
323
324 decimals, err := instance.Decimals(c.opts)
325 if err != nil {
326 return nil, tracerr.Wrap(err)
327 }
328 return &ERC20Consts{
329 Name: name,
330 Symbol: symbol,
331 Decimals: uint64(decimals),
332 }, nil
333}
334
335// Client returns the internal ethclient.Client
336func (c *EthereumClient) Client() *ethclient.Client {
337 return c.client
338}
339
340// newCallOpts returns a CallOpts to be used in ethereum calls with a non-zero
341// From address. This is a workaround for a bug in ethereumjs-vm that shows up
342// in ganache: https://github.com/hermeznetwork/hermez-node/issues/317
343func newCallOpts() *bind.CallOpts {
344 return &bind.CallOpts{
345 From: ethCommon.HexToAddress("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"),
346 }
347}