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