xeth.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package rpc
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "reflect"
  21. "sync/atomic"
  22. "github.com/ethereum/go-ethereum/rpc/comms"
  23. "github.com/ethereum/go-ethereum/rpc/shared"
  24. )
  25. // Xeth is a native API interface to a remote node.
  26. type Xeth struct {
  27. client comms.EthereumClient
  28. reqId uint32
  29. }
  30. // NewXeth constructs a new native API interface to a remote node.
  31. func NewXeth(client comms.EthereumClient) *Xeth {
  32. return &Xeth{
  33. client: client,
  34. }
  35. }
  36. // Call invokes a method with the given parameters are the remote node.
  37. func (self *Xeth) Call(method string, params []interface{}) (map[string]interface{}, error) {
  38. // Assemble the json RPC request
  39. data, err := json.Marshal(params)
  40. if err != nil {
  41. return nil, err
  42. }
  43. req := &shared.Request{
  44. Id: atomic.AddUint32(&self.reqId, 1),
  45. Jsonrpc: "2.0",
  46. Method: method,
  47. Params: data,
  48. }
  49. // Send the request over and process the response
  50. if err := self.client.Send(req); err != nil {
  51. return nil, err
  52. }
  53. res, err := self.client.Recv()
  54. if err != nil {
  55. return nil, err
  56. }
  57. value, ok := res.(map[string]interface{})
  58. if !ok {
  59. return nil, fmt.Errorf("Invalid response type: have %v, want %v", reflect.TypeOf(res), reflect.TypeOf(make(map[string]interface{})))
  60. }
  61. return value, nil
  62. }