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 "github.com/hermeznetwork/hermez-node/log"
17)
18
19// EthereumInterface is the interface to Ethereum
20type EthereumInterface interface {
21 EthCurrentBlock() (int64, error)
22 // EthHeaderByNumber(context.Context, *big.Int) (*types.Header, error)
23 EthBlockByNumber(context.Context, int64) (*common.Block, error)
24}
25
26var (
27 // ErrAccountNil is used when the calls can not be made because the account is nil
28 ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil")
29 // ErrReceiptStatusFailed is used when receiving a failed transaction
30 ErrReceiptStatusFailed = fmt.Errorf("receipt status is failed")
31 // ErrReceiptNotReceived is used when unable to retrieve a transaction
32 ErrReceiptNotReceived = fmt.Errorf("receipt not available")
33 // ErrBlockHashMismatchEvent is used when there's a block hash mismatch
34 // beetween different events of the same block
35 ErrBlockHashMismatchEvent = fmt.Errorf("block hash mismatch in event log")
36)
37
38const (
39 errStrDeploy = "deployment of %s failed: %w"
40 errStrWaitReceipt = "wait receipt of %s deploy failed: %w"
41
42 // default values
43 defaultCallGasLimit = 300000
44 defaultDeployGasLimit = 1000000
45 defaultGasPriceDiv = 100
46 defaultReceiptTimeout = 60
47 defaultIntervalReceiptLoop = 200
48)
49
50// EthereumConfig defines the configuration parameters of the EthereumClient
51type EthereumConfig struct {
52 CallGasLimit uint64
53 DeployGasLimit uint64
54 GasPriceDiv uint64
55 ReceiptTimeout time.Duration // in seconds
56 IntervalReceiptLoop time.Duration // in milliseconds
57}
58
59// EthereumClient is an ethereum client to call Smart Contract methods and check blockchain information.
60type EthereumClient struct {
61 client *ethclient.Client
62 account *accounts.Account
63 ks *ethKeystore.KeyStore
64 ReceiptTimeout time.Duration
65 config *EthereumConfig
66}
67
68// NewEthereumClient creates a EthereumClient instance. The account is not mandatory (it can
69// be nil). If the account is nil, CallAuth will fail with ErrAccountNil.
70func NewEthereumClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *EthereumConfig) *EthereumClient {
71 if config == nil {
72 config = &EthereumConfig{
73 CallGasLimit: defaultCallGasLimit,
74 DeployGasLimit: defaultDeployGasLimit,
75 GasPriceDiv: defaultGasPriceDiv,
76 ReceiptTimeout: defaultReceiptTimeout,
77 IntervalReceiptLoop: defaultIntervalReceiptLoop,
78 }
79 }
80 return &EthereumClient{client: client, account: account, ks: ks, ReceiptTimeout: config.ReceiptTimeout * time.Second, config: config}
81}
82
83// BalanceAt retieves information about the default account
84func (c *EthereumClient) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
85 return c.client.BalanceAt(context.TODO(), addr, nil)
86}
87
88// Account returns the underlying ethereum account
89func (c *EthereumClient) Account() *accounts.Account {
90 return c.account
91}
92
93// CallAuth performs a Smart Contract method call that requires authorization.
94// This call requires a valid account with Ether that can be spend during the
95// call.
96func (c *EthereumClient) CallAuth(gasLimit uint64,
97 fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
98 if c.account == nil {
99 return nil, ErrAccountNil
100 }
101
102 gasPrice, err := c.client.SuggestGasPrice(context.Background())
103 if err != nil {
104 return nil, err
105 }
106 inc := new(big.Int).Set(gasPrice)
107 inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
108 gasPrice.Add(gasPrice, inc)
109 log.Debugw("Transaction metadata", "gasPrice", gasPrice)
110
111 auth, err := bind.NewKeyStoreTransactor(c.ks, *c.account)
112 if err != nil {
113 return nil, err
114 }
115 auth.Value = big.NewInt(0) // in wei
116 if gasLimit == 0 {
117 auth.GasLimit = c.config.CallGasLimit // in units
118 } else {
119 auth.GasLimit = gasLimit // in units
120 }
121 auth.GasPrice = gasPrice
122
123 tx, err := fn(c.client, auth)
124 if tx != nil {
125 log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
126 }
127 return tx, err
128}
129
130// ContractData contains the contract data
131type ContractData struct {
132 Address ethCommon.Address
133 Tx *types.Transaction
134 Receipt *types.Receipt
135}
136
137// Deploy a smart contract. `name` is used to log deployment information. fn
138// is a wrapper to the deploy function generated by abigen. In case of error,
139// the returned `ContractData` may have some parameters filled depending on the
140// kind of error that occurred.
141func (c *EthereumClient) Deploy(name string,
142 fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
143 var contractData ContractData
144 log.Infow("Deploying", "contract", name)
145 tx, err := c.CallAuth(
146 c.config.DeployGasLimit,
147 func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
148 addr, tx, _, err := fn(client, auth)
149 if err != nil {
150 return nil, err
151 }
152 contractData.Address = addr
153 return tx, nil
154 },
155 )
156 if err != nil {
157 return contractData, fmt.Errorf(errStrDeploy, name, err)
158 }
159 log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
160 contractData.Tx = tx
161 receipt, err := c.WaitReceipt(tx)
162 if err != nil {
163 return contractData, fmt.Errorf(errStrWaitReceipt, name, err)
164 }
165 contractData.Receipt = receipt
166 return contractData, nil
167}
168
169// Call performs a read only Smart Contract method call.
170func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
171 return fn(c.client)
172}
173
174// WaitReceipt will block until a transaction is confirmed. Internally it
175// polls the state every 200 milliseconds.
176func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
177 return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
178}
179
180// GetReceipt will check if a transaction is confirmed and return
181// immediately, waiting at most 1 second and returning error if the transaction
182// is still pending.
183func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
184 ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
185 defer cancel()
186 return c.waitReceipt(ctx, tx, 0)
187}
188
189func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
190 var err error
191 var receipt *types.Receipt
192
193 txid := tx.Hash()
194 log.Debugw("Waiting for receipt", "tx", txid.Hex())
195
196 start := time.Now()
197 for {
198 receipt, err = c.client.TransactionReceipt(ctx, txid)
199 if receipt != nil || time.Since(start) >= timeout {
200 break
201 }
202 time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
203 }
204
205 if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
206 log.Errorw("Failed transaction", "tx", txid.Hex())
207 return receipt, ErrReceiptStatusFailed
208 }
209
210 if receipt == nil {
211 log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txid.Hex(), "lasterr", err)
212 return receipt, ErrReceiptNotReceived
213 }
214 log.Debugw("Successful transaction", "tx", txid.Hex())
215
216 return receipt, err
217}
218
219// EthCurrentBlock returns the current block number in the blockchain
220func (c *EthereumClient) EthCurrentBlock() (int64, error) {
221 ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
222 defer cancel()
223 header, err := c.client.HeaderByNumber(ctx, nil)
224 if err != nil {
225 return 0, err
226 }
227 return header.Number.Int64(), nil
228}
229
230// EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
231// func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
232// return c.client.HeaderByNumber(ctx, number)
233// }
234
235// EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns *common.Block
236func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
237 blockNum := big.NewInt(number)
238 if number == 0 {
239 blockNum = nil
240 }
241 block, err := c.client.BlockByNumber(ctx, blockNum)
242 if err != nil {
243 return nil, err
244 }
245 b := &common.Block{
246 EthBlockNum: block.Number().Int64(),
247 Timestamp: time.Unix(int64(block.Time()), 0),
248 Hash: block.Hash(),
249 }
250 return b, nil
251}