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