xeth.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package rpc
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "reflect"
  6. "sync/atomic"
  7. "github.com/ethereum/go-ethereum/rpc/comms"
  8. "github.com/ethereum/go-ethereum/rpc/shared"
  9. )
  10. // Xeth is a native API interface to a remote node.
  11. type Xeth struct {
  12. client comms.EthereumClient
  13. reqId uint32
  14. }
  15. // NewXeth constructs a new native API interface to a remote node.
  16. func NewXeth(client comms.EthereumClient) *Xeth {
  17. return &Xeth{
  18. client: client,
  19. }
  20. }
  21. // Call invokes a method with the given parameters are the remote node.
  22. func (self *Xeth) Call(method string, params []interface{}) (map[string]interface{}, error) {
  23. // Assemble the json RPC request
  24. data, err := json.Marshal(params)
  25. if err != nil {
  26. return nil, err
  27. }
  28. req := &shared.Request{
  29. Id: atomic.AddUint32(&self.reqId, 1),
  30. Jsonrpc: "2.0",
  31. Method: method,
  32. Params: data,
  33. }
  34. // Send the request over and process the response
  35. if err := self.client.Send(req); err != nil {
  36. return nil, err
  37. }
  38. res, err := self.client.Recv()
  39. if err != nil {
  40. return nil, err
  41. }
  42. value, ok := res.(map[string]interface{})
  43. if !ok {
  44. return nil, fmt.Errorf("Invalid response type: have %v, want %v", reflect.TypeOf(res), reflect.TypeOf(make(map[string]interface{})))
  45. }
  46. return value, nil
  47. }