xeth.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package rpc implements the Ethereum JSON-RPC API.
  17. package rpc
  18. import (
  19. "encoding/json"
  20. "fmt"
  21. "reflect"
  22. "sync/atomic"
  23. "github.com/ethereum/go-ethereum/rpc/comms"
  24. "github.com/ethereum/go-ethereum/rpc/shared"
  25. )
  26. // Xeth is a native API interface to a remote node.
  27. type Xeth struct {
  28. client comms.EthereumClient
  29. reqId uint32
  30. }
  31. // NewXeth constructs a new native API interface to a remote node.
  32. func NewXeth(client comms.EthereumClient) *Xeth {
  33. return &Xeth{
  34. client: client,
  35. }
  36. }
  37. // Call invokes a method with the given parameters are the remote node.
  38. func (self *Xeth) Call(method string, params []interface{}) (map[string]interface{}, error) {
  39. // Assemble the json RPC request
  40. data, err := json.Marshal(params)
  41. if err != nil {
  42. return nil, err
  43. }
  44. req := &shared.Request{
  45. Id: atomic.AddUint32(&self.reqId, 1),
  46. Jsonrpc: "2.0",
  47. Method: method,
  48. Params: data,
  49. }
  50. // Send the request over and retrieve the response
  51. if err := self.client.Send(req); err != nil {
  52. return nil, err
  53. }
  54. res, err := self.client.Recv()
  55. if err != nil {
  56. return nil, err
  57. }
  58. // Ensure the response is valid, and extract the results
  59. success, isSuccessResponse := res.(*shared.SuccessResponse)
  60. failure, isFailureResponse := res.(*shared.ErrorResponse)
  61. switch {
  62. case isFailureResponse:
  63. return nil, fmt.Errorf("Method invocation failed: %v", failure.Error)
  64. case isSuccessResponse:
  65. return success.Result.(map[string]interface{}), nil
  66. default:
  67. return nil, fmt.Errorf("Invalid response type: %v", reflect.TypeOf(res))
  68. }
  69. }