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