From 90d78d310e264f79f7213eec3562ae3a9742f755 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Mon, 11 Mar 2024 17:24:21 -0400 Subject: [PATCH] feat: add /s5/p2p/peers endpoint --- service/default/http.go | 45 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/service/default/http.go b/service/default/http.go index b09e70c..0a0e7b7 100644 --- a/service/default/http.go +++ b/service/default/http.go @@ -40,6 +40,7 @@ func (h *HTTPServiceDefault) GetHttpRouter(inject map[string]jape.Handler) *http "GET /s5/version": h.versionHandler, "GET /s5/p2p": h.p2pHandler, "GET /s5/p2p/nodes": h.p2pNodesHandler, + "GET /s5/p2p/peers": h.p2pPeersHandler, } for k, v := range inject { @@ -115,10 +116,6 @@ func (h *HTTPServiceDefault) p2pHandler(ctx jape.Context) { } } - if clientIP != nil { - peer.SetIP(&net.IPAddr{IP: clientIP}) - } - if blockConnection(peer.GetIP()) { err := peer.End() if err != nil { @@ -127,6 +124,10 @@ func (h *HTTPServiceDefault) p2pHandler(ctx jape.Context) { return } + if clientIP != nil { + peer.SetIP(&net.IPAddr{IP: clientIP}) + } + h.Services().P2P().ConnectionTracker().Add(1) go func() { @@ -160,3 +161,39 @@ func (h *HTTPServiceDefault) p2pNodesHandler(ctx jape.Context) { Nodes: nodeList, }) } +func (h *HTTPServiceDefault) p2pPeersHandler(ctx jape.Context) { + peers := h.Services().P2P().Peers().Values() + peerList := make([]P2PNodeResponse, 0) + + for _, p := range peers { + peer, ok := p.(s5net.Peer) + if !ok { + continue + } + + id, err := peer.Id().ToString() + if err != nil { + h.Logger().Error("error getting peer id", zap.Error(err)) + continue + } + + if len(peer.ConnectionURIs()) == 0 { + continue + } + + uris := make([]string, len(peer.ConnectionURIs())) + + for i, uri := range peer.ConnectionURIs() { + uris[i] = uri.String() + } + + peerList = append(peerList, P2PNodeResponse{ + Id: id, + Uris: uris, + }) + } + + ctx.Encode(P2PNodesResponse{ + Nodes: peerList, + }) +}