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"
 10	"github.com/ethereum/go-ethereum/accounts"
 11	"github.com/ethereum/go-ethereum/accounts/abi/bind"
 12	ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore"
 13	ethCommon "github.com/ethereum/go-ethereum/common"
 14	"github.com/ethereum/go-ethereum/core/types"
 15	"github.com/ethereum/go-ethereum/ethclient"
 16	"github.com/hermeznetwork/hermez-node/common"
 17	HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
 18	"github.com/hermeznetwork/hermez-node/log"
 19	"github.com/hermeznetwork/tracerr"
 20)
 21
 22// ERC20Consts are the constants defined in a particular ERC20 Token instance
 23type ERC20Consts struct {
 24	Name     string
 25	Symbol   string
 26	Decimals uint64
 27}
 28
 29// EthereumInterface is the interface to Ethereum
 30type EthereumInterface interface {
 31	EthLastBlock() (int64, error)
 32	// EthHeaderByNumber(context.Context, *big.Int) (*types.Header, error)
 33	EthBlockByNumber(context.Context, int64) (*common.Block, error)
 34	EthAddress() (*ethCommon.Address, error)
 35	EthTransactionReceipt(context.Context, ethCommon.Hash) (*types.Receipt, error)
 36
 37	EthERC20Consts(ethCommon.Address) (*ERC20Consts, error)
 38	EthChainID() (*big.Int, error)
 39
 40	EthPendingNonceAt(ctx context.Context, account ethCommon.Address) (uint64, error)
 41	EthNonceAt(ctx context.Context, account ethCommon.Address, blockNumber *big.Int) (uint64, error)
 42	EthSuggestGasPrice(ctx context.Context) (*big.Int, error)
 43	EthKeyStore() *ethKeystore.KeyStore
 44	EthCall(ctx context.Context, tx *types.Transaction, blockNum *big.Int) ([]byte, error)
 45}
 46
 47var (
 48	// ErrAccountNil is used when the calls can not be made because the account is nil
 49	ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil")
 50	// ErrBlockHashMismatchEvent is used when there's a block hash mismatch
 51	// beetween different events of the same block
 52	ErrBlockHashMismatchEvent = fmt.Errorf("block hash mismatch in event log")
 53)
 54
 55const (
 56	// default values
 57	defaultCallGasLimit = 300000
 58	defaultGasPriceDiv  = 100
 59)
 60
 61// EthereumConfig defines the configuration parameters of the EthereumClient
 62type EthereumConfig struct {
 63	CallGasLimit uint64
 64	GasPriceDiv  uint64
 65}
 66
 67// EthereumClient is an ethereum client to call Smart Contract methods and check blockchain information.
 68type EthereumClient struct {
 69	client  *ethclient.Client
 70	chainID *big.Int
 71	account *accounts.Account
 72	ks      *ethKeystore.KeyStore
 73	config  *EthereumConfig
 74	opts    *bind.CallOpts
 75}
 76
 77// NewEthereumClient creates a EthereumClient instance.  The account is not mandatory (it can
 78// be nil).  If the account is nil, CallAuth will fail with ErrAccountNil.
 79func NewEthereumClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *EthereumConfig) (*EthereumClient, error) {
 80	if config == nil {
 81		config = &EthereumConfig{
 82			CallGasLimit: defaultCallGasLimit,
 83			GasPriceDiv:  defaultGasPriceDiv,
 84		}
 85	}
 86	c := &EthereumClient{
 87		client:  client,
 88		account: account,
 89		ks:      ks,
 90		config:  config,
 91		opts:    newCallOpts(),
 92	}
 93	chainID, err := c.EthChainID()
 94	if err != nil {
 95		return nil, tracerr.Wrap(err)
 96	}
 97	c.chainID = chainID
 98	return c, nil
 99}
100
101// EthChainID returns the ChainID of the ethereum network
102func (c *EthereumClient) EthChainID() (*big.Int, error) {
103	chainID, err := c.client.ChainID(context.Background())
104	if err != nil {
105		return nil, tracerr.Wrap(err)
106	}
107	return chainID, nil
108}
109
110// BalanceAt retieves information about the default account
111func (c *EthereumClient) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
112	return c.client.BalanceAt(context.TODO(), addr, nil)
113}
114
115// Account returns the underlying ethereum account
116func (c *EthereumClient) Account() *accounts.Account {
117	return c.account
118}
119
120// EthAddress returns the ethereum address of the account loaded into the EthereumClient
121func (c *EthereumClient) EthAddress() (*ethCommon.Address, error) {
122	if c.account == nil {
123		return nil, tracerr.Wrap(ErrAccountNil)
124	}
125	return &c.account.Address, nil
126}
127
128// EthSuggestGasPrice retrieves the currently suggested gas price to allow a
129// timely execution of a transaction.
130func (c *EthereumClient) EthSuggestGasPrice(ctx context.Context) (*big.Int, error) {
131	return c.client.SuggestGasPrice(ctx)
132}
133
134// EthKeyStore returns the keystore in the EthereumClient
135func (c *EthereumClient) EthKeyStore() *ethKeystore.KeyStore {
136	return c.ks
137}
138
139// NewAuth builds a new auth object to make a transaction
140func (c *EthereumClient) NewAuth() (*bind.TransactOpts, error) {
141	if c.account == nil {
142		return nil, tracerr.Wrap(ErrAccountNil)
143	}
144
145	gasPrice, err := c.client.SuggestGasPrice(context.Background())
146	if err != nil {
147		return nil, tracerr.Wrap(err)
148	}
149	inc := new(big.Int).Set(gasPrice)
150	inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
151	gasPrice.Add(gasPrice, inc)
152	log.Debugw("Transaction metadata", "gasPrice", gasPrice)
153
154	auth, err := bind.NewKeyStoreTransactorWithChainID(c.ks, *c.account, c.chainID)
155	if err != nil {
156		return nil, tracerr.Wrap(err)
157	}
158	auth.Value = big.NewInt(0) // in wei
159	auth.GasLimit = c.config.CallGasLimit
160	auth.GasPrice = gasPrice
161
162	return auth, nil
163}
164
165// CallAuth performs a Smart Contract method call that requires authorization.
166// This call requires a valid account with Ether that can be spend during the
167// call.
168func (c *EthereumClient) CallAuth(gasLimit uint64,
169	fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
170	if c.account == nil {
171		return nil, tracerr.Wrap(ErrAccountNil)
172	}
173
174	gasPrice, err := c.client.SuggestGasPrice(context.Background())
175	if err != nil {
176		return nil, tracerr.Wrap(err)
177	}
178	inc := new(big.Int).Set(gasPrice)
179	inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
180	gasPrice.Add(gasPrice, inc)
181	log.Debugw("Transaction metadata", "gasPrice", gasPrice)
182
183	auth, err := bind.NewKeyStoreTransactorWithChainID(c.ks, *c.account, c.chainID)
184	if err != nil {
185		return nil, tracerr.Wrap(err)
186	}
187	auth.Value = big.NewInt(0) // in wei
188	if gasLimit == 0 {
189		auth.GasLimit = c.config.CallGasLimit // in units
190	} else {
191		auth.GasLimit = gasLimit // in units
192	}
193	auth.GasPrice = gasPrice
194
195	tx, err := fn(c.client, auth)
196	if tx != nil {
197		log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
198	}
199	return tx, tracerr.Wrap(err)
200}
201
202// ContractData contains the contract data
203type ContractData struct {
204	Address ethCommon.Address
205	Tx      *types.Transaction
206	Receipt *types.Receipt
207}
208
209// Call performs a read only Smart Contract method call.
210func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
211	return fn(c.client)
212}
213
214// EthTransactionReceipt returns the transaction receipt of the given txHash
215func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
216	return c.client.TransactionReceipt(ctx, txHash)
217}
218
219// EthLastBlock returns the last block number in the blockchain
220func (c *EthereumClient) EthLastBlock() (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, tracerr.Wrap(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
236// *common.Block.  If number == -1, the latests known block is returned.
237func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
238	blockNum := big.NewInt(number)
239	if number == -1 {
240		blockNum = nil
241	}
242	block, err := c.client.BlockByNumber(ctx, blockNum)
243	if err != nil {
244		return nil, tracerr.Wrap(err)
245	}
246	b := &common.Block{
247		Num:        block.Number().Int64(),
248		Timestamp:  time.Unix(int64(block.Time()), 0),
249		ParentHash: block.ParentHash(),
250		Hash:       block.Hash(),
251	}
252	return b, nil
253}
254
255// EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
256func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
257	// We use the HEZ token smart contract interfacehere because it's an
258	// ERC20, which allows us to access the standard ERC20 constants.
259	instance, err := HEZ.NewHEZ(tokenAddress, c.client)
260	if err != nil {
261		return nil, tracerr.Wrap(err)
262	}
263	name, err := instance.Name(c.opts)
264	if err != nil {
265		return nil, tracerr.Wrap(err)
266	}
267
268	symbol, err := instance.Symbol(c.opts)
269	if err != nil {
270		return nil, tracerr.Wrap(err)
271	}
272
273	decimals, err := instance.Decimals(c.opts)
274	if err != nil {
275		return nil, tracerr.Wrap(err)
276	}
277	return &ERC20Consts{
278		Name:     name,
279		Symbol:   symbol,
280		Decimals: uint64(decimals),
281	}, nil
282}
283
284// Client returns the internal ethclient.Client
285func (c *EthereumClient) Client() *ethclient.Client {
286	return c.client
287}
288
289// newCallOpts returns a CallOpts to be used in ethereum calls with a non-zero
290// From address.  This is a workaround for a bug in ethereumjs-vm that shows up
291// in ganache: https://github.com/hermeznetwork/hermez-node/issues/317
292func newCallOpts() *bind.CallOpts {
293	return &bind.CallOpts{
294		From: ethCommon.HexToAddress("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"),
295	}
296}
297
298// EthPendingNonceAt returns the account nonce of the given account in the pending
299// state. This is the nonce that should be used for the next transaction.
300func (c *EthereumClient) EthPendingNonceAt(ctx context.Context,
301	account ethCommon.Address) (uint64, error) {
302	return c.client.PendingNonceAt(ctx, account)
303}
304
305// EthNonceAt returns the account nonce of the given account. The block number can
306// be nil, in which case the nonce is taken from the latest known block.
307func (c *EthereumClient) EthNonceAt(ctx context.Context,
308	account ethCommon.Address, blockNumber *big.Int) (uint64, error) {
309	return c.client.NonceAt(ctx, account, blockNumber)
310}
311
312// EthCall runs the transaction as a call (without paying) in the local node at
313// blockNum.
314func (c *EthereumClient) EthCall(ctx context.Context, tx *types.Transaction,
315	blockNum *big.Int) ([]byte, error) {
316	if c.account == nil {
317		return nil, tracerr.Wrap(ErrAccountNil)
318	}
319	msg := ethereum.CallMsg{
320		From:     c.account.Address,
321		To:       tx.To(),
322		Gas:      tx.Gas(),
323		GasPrice: tx.GasPrice(),
324		Value:    tx.Value(),
325		Data:     tx.Data(),
326	}
327	result, err := c.client.CallContract(ctx, msg, blockNum)
328	return result, tracerr.Wrap(err)
329}