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	"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
 69	IntervalReceiptLoop time.Duration
 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	// TODO: Set the correct chainID
141	auth, err := bind.NewKeyStoreTransactorWithChainID(c.ks, *c.account, big.NewInt(0))
142	if err != nil {
143		return nil, tracerr.Wrap(err)
144	}
145	auth.Value = big.NewInt(0) // in wei
146	if gasLimit == 0 {
147		auth.GasLimit = c.config.CallGasLimit // in units
148	} else {
149		auth.GasLimit = gasLimit // in units
150	}
151	auth.GasPrice = gasPrice
152
153	tx, err := fn(c.client, auth)
154	if tx != nil {
155		log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
156	}
157	return tx, tracerr.Wrap(err)
158}
159
160// ContractData contains the contract data
161type ContractData struct {
162	Address ethCommon.Address
163	Tx      *types.Transaction
164	Receipt *types.Receipt
165}
166
167// Deploy a smart contract.  `name` is used to log deployment information.  fn
168// is a wrapper to the deploy function generated by abigen.  In case of error,
169// the returned `ContractData` may have some parameters filled depending on the
170// kind of error that occurred.
171func (c *EthereumClient) Deploy(name string,
172	fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
173	var contractData ContractData
174	log.Infow("Deploying", "contract", name)
175	tx, err := c.CallAuth(
176		c.config.DeployGasLimit,
177		func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
178			addr, tx, _, err := fn(client, auth)
179			if err != nil {
180				return nil, tracerr.Wrap(err)
181			}
182			contractData.Address = addr
183			return tx, nil
184		},
185	)
186	if err != nil {
187		return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err))
188	}
189	log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
190	contractData.Tx = tx
191	receipt, err := c.WaitReceipt(tx)
192	if err != nil {
193		return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err))
194	}
195	contractData.Receipt = receipt
196	return contractData, nil
197}
198
199// Call performs a read only Smart Contract method call.
200func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
201	return fn(c.client)
202}
203
204// WaitReceipt will block until a transaction is confirmed.  Internally it
205// polls the state every 200 milliseconds.
206func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
207	return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
208}
209
210// GetReceipt will check if a transaction is confirmed and return
211// immediately, waiting at most 1 second and returning error if the transaction
212// is still pending.
213func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
214	ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
215	defer cancel()
216	return c.waitReceipt(ctx, tx, 0)
217}
218
219// EthTransactionReceipt returns the transaction receipt of the given txHash
220func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
221	return c.client.TransactionReceipt(ctx, txHash)
222}
223
224func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
225	var err error
226	var receipt *types.Receipt
227
228	txHash := tx.Hash()
229	log.Debugw("Waiting for receipt", "tx", txHash.Hex())
230
231	start := time.Now()
232	for {
233		receipt, err = c.client.TransactionReceipt(ctx, txHash)
234		if receipt != nil || time.Since(start) >= timeout {
235			break
236		}
237		time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
238	}
239
240	if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
241		log.Errorw("Failed transaction", "tx", txHash.Hex())
242		return receipt, tracerr.Wrap(ErrReceiptStatusFailed)
243	}
244
245	if receipt == nil {
246		log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err)
247		return receipt, tracerr.Wrap(ErrReceiptNotReceived)
248	}
249	log.Debugw("Successful transaction", "tx", txHash.Hex())
250
251	return receipt, tracerr.Wrap(err)
252}
253
254// EthLastBlock returns the last block number in the blockchain
255func (c *EthereumClient) EthLastBlock() (int64, error) {
256	ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
257	defer cancel()
258	header, err := c.client.HeaderByNumber(ctx, nil)
259	if err != nil {
260		return 0, tracerr.Wrap(err)
261	}
262	return header.Number.Int64(), nil
263}
264
265// EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
266// func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
267// 	return c.client.HeaderByNumber(ctx, number)
268// }
269
270// EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns
271// *common.Block.  If number == -1, the latests known block is returned.
272func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
273	blockNum := big.NewInt(number)
274	if number == -1 {
275		blockNum = nil
276	}
277	block, err := c.client.BlockByNumber(ctx, blockNum)
278	if err != nil {
279		return nil, tracerr.Wrap(err)
280	}
281	b := &common.Block{
282		Num:        block.Number().Int64(),
283		Timestamp:  time.Unix(int64(block.Time()), 0),
284		ParentHash: block.ParentHash(),
285		Hash:       block.Hash(),
286	}
287	return b, nil
288}
289
290// EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
291func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
292	// We use the HEZ token smart contract interfacehere because it's an
293	// ERC20, which allows us to access the standard ERC20 constants.
294	instance, err := HEZ.NewHEZ(tokenAddress, c.client)
295	if err != nil {
296		return nil, tracerr.Wrap(err)
297	}
298	name, err := instance.Name(c.opts)
299	if err != nil {
300		return nil, tracerr.Wrap(err)
301	}
302
303	symbol, err := instance.Symbol(c.opts)
304	if err != nil {
305		return nil, tracerr.Wrap(err)
306	}
307
308	decimals, err := instance.Decimals(c.opts)
309	if err != nil {
310		return nil, tracerr.Wrap(err)
311	}
312	return &ERC20Consts{
313		Name:     name,
314		Symbol:   symbol,
315		Decimals: uint64(decimals),
316	}, nil
317}
318
319// Client returns the internal ethclient.Client
320func (c *EthereumClient) Client() *ethclient.Client {
321	return c.client
322}
323
324// newCallOpts returns a CallOpts to be used in ethereum calls with a non-zero
325// From address.  This is a workaround for a bug in ethereumjs-vm that shows up
326// in ganache: https://github.com/hermeznetwork/hermez-node/issues/317
327func newCallOpts() *bind.CallOpts {
328	return &bind.CallOpts{
329		From: ethCommon.HexToAddress("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"),
330	}
331}