net.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api
  2. import (
  3. "github.com/ethereum/go-ethereum/eth"
  4. "github.com/ethereum/go-ethereum/rpc/codec"
  5. "github.com/ethereum/go-ethereum/rpc/shared"
  6. "github.com/ethereum/go-ethereum/xeth"
  7. )
  8. const (
  9. NetApiVersion = "1.0"
  10. )
  11. var (
  12. // mapping between methods and handlers
  13. netMapping = map[string]nethandler{
  14. "net_version": (*netApi).Version,
  15. "net_peerCount": (*netApi).PeerCount,
  16. "net_listening": (*netApi).IsListening,
  17. "net_peers": (*netApi).Peers,
  18. }
  19. )
  20. // net callback handler
  21. type nethandler func(*netApi, *shared.Request) (interface{}, error)
  22. // net api provider
  23. type netApi struct {
  24. xeth *xeth.XEth
  25. ethereum *eth.Ethereum
  26. methods map[string]nethandler
  27. codec codec.ApiCoder
  28. }
  29. // create a new net api instance
  30. func NewNetApi(xeth *xeth.XEth, eth *eth.Ethereum, coder codec.Codec) *netApi {
  31. return &netApi{
  32. xeth: xeth,
  33. ethereum: eth,
  34. methods: netMapping,
  35. codec: coder.New(nil),
  36. }
  37. }
  38. // collection with supported methods
  39. func (self *netApi) Methods() []string {
  40. methods := make([]string, len(self.methods))
  41. i := 0
  42. for k := range self.methods {
  43. methods[i] = k
  44. i++
  45. }
  46. return methods
  47. }
  48. // Execute given request
  49. func (self *netApi) Execute(req *shared.Request) (interface{}, error) {
  50. if callback, ok := self.methods[req.Method]; ok {
  51. return callback(self, req)
  52. }
  53. return nil, shared.NewNotImplementedError(req.Method)
  54. }
  55. func (self *netApi) Name() string {
  56. return NetApiName
  57. }
  58. func (self *netApi) ApiVersion() string {
  59. return NetApiVersion
  60. }
  61. // Network version
  62. func (self *netApi) Version(req *shared.Request) (interface{}, error) {
  63. return self.xeth.NetworkVersion(), nil
  64. }
  65. // Number of connected peers
  66. func (self *netApi) PeerCount(req *shared.Request) (interface{}, error) {
  67. return self.xeth.PeerCount(), nil
  68. }
  69. func (self *netApi) IsListening(req *shared.Request) (interface{}, error) {
  70. return self.xeth.IsListening(), nil
  71. }
  72. func (self *netApi) Peers(req *shared.Request) (interface{}, error) {
  73. return self.ethereum.PeersInfo(), nil
  74. }