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.

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