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