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