You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

248 lines
8.1 KiB

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