net.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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_peerCount": (*netApi).PeerCount,
  15. "net_listening": (*netApi).IsListening,
  16. }
  17. )
  18. // net callback handler
  19. type nethandler func(*netApi, *shared.Request) (interface{}, error)
  20. // net api provider
  21. type netApi struct {
  22. xeth *xeth.XEth
  23. ethereum *eth.Ethereum
  24. methods map[string]nethandler
  25. codec codec.ApiCoder
  26. }
  27. // create a new net api instance
  28. func NewNetApi(xeth *xeth.XEth, eth *eth.Ethereum, coder codec.Codec) *netApi {
  29. return &netApi{
  30. xeth: xeth,
  31. ethereum: eth,
  32. methods: netMapping,
  33. codec: coder.New(nil),
  34. }
  35. }
  36. // collection with supported methods
  37. func (self *netApi) Methods() []string {
  38. methods := make([]string, len(self.methods))
  39. i := 0
  40. for k := range self.methods {
  41. methods[i] = k
  42. i++
  43. }
  44. return methods
  45. }
  46. // Execute given request
  47. func (self *netApi) Execute(req *shared.Request) (interface{}, error) {
  48. if callback, ok := self.methods[req.Method]; ok {
  49. return callback(self, req)
  50. }
  51. return nil, shared.NewNotImplementedError(req.Method)
  52. }
  53. func (self *netApi) Name() string {
  54. return shared.NetApiName
  55. }
  56. func (self *netApi) ApiVersion() string {
  57. return NetApiVersion
  58. }
  59. // Number of connected peers
  60. func (self *netApi) PeerCount(req *shared.Request) (interface{}, error) {
  61. return newHexNum(self.xeth.PeerCount()), nil
  62. }
  63. func (self *netApi) IsListening(req *shared.Request) (interface{}, error) {
  64. return self.xeth.IsListening(), nil
  65. }