rpc: implement net_listening and net_peerCount JSON-RPC endpoints (#252)

* Add net_listening net_peerCount endpoint

* Add test cases

* Use RPC client from context

* Fix lint issue

* Revert unnecessary changes

* Update JSON RPC documentation
This commit is contained in:
Calvin Lau
2021-07-12 08:26:33 -04:00
committed by GitHub
parent 8f73d556c6
commit 8bfb6b0a67
4 changed files with 86 additions and 5 deletions
+25 -2
View File
@@ -1,16 +1,18 @@
package net
import (
"context"
"fmt"
ethermint "github.com/tharsis/ethermint/types"
"github.com/cosmos/cosmos-sdk/client"
rpcclient "github.com/tendermint/tendermint/rpc/client"
ethermint "github.com/tharsis/ethermint/types"
)
// PublicAPI is the eth_ prefixed set of APIs in the Web3 JSON-RPC spec.
type PublicAPI struct {
networkVersion uint64
tmClient rpcclient.Client
}
// NewPublicAPI creates an instance of the public Net Web3 API.
@@ -23,6 +25,7 @@ func NewPublicAPI(clientCtx client.Context) *PublicAPI {
return &PublicAPI{
networkVersion: chainIDEpoch.Uint64(),
tmClient: clientCtx.Client,
}
}
@@ -30,3 +33,23 @@ func NewPublicAPI(clientCtx client.Context) *PublicAPI {
func (s *PublicAPI) Version() string {
return fmt.Sprintf("%d", s.networkVersion)
}
// Listening returns if client is actively listening for network connections.
func (s *PublicAPI) Listening() bool {
ctx := context.Background()
netInfo, err := s.tmClient.NetInfo(ctx)
if err != nil {
return false
}
return netInfo.Listening
}
// PeerCount returns the number of peers currently connected to the client.
func (s *PublicAPI) PeerCount() int {
ctx := context.Background()
netInfo, err := s.tmClient.NetInfo(ctx)
if err != nil {
return 0
}
return len(netInfo.Peers)
}