From 3942aaa7dcfa8cfd2fe110cf2bda66b34ead6539 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 25 Sep 2022 01:29:25 +0200 Subject: [PATCH] Grab bootstrap peers from IPFS API --- p2p/node.go | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/p2p/node.go b/p2p/node.go index 0c9a250..f5d5292 100644 --- a/p2p/node.go +++ b/p2p/node.go @@ -2,8 +2,12 @@ package p2p import ( "context" + "encoding/json" "errors" "fmt" + "io/ioutil" + "net/http" + "net/url" "os" "sync" @@ -22,6 +26,35 @@ import ( // Protocol is a descriptor for the Hyprspace P2P Protocol. const Protocol = "/hyprspace/0.0.1" +func getExtraBootstrapNodes(addr ma.Multiaddr) (nodesList []string) { + nodesList = []string{} + ip4, err := addr.ValueForProtocol(ma.P_IP4) + if err != nil { + return + } + port, err := addr.ValueForProtocol(ma.P_TCP) + if err != nil { + return + } + resp, err := http.PostForm("http://"+ip4+":"+port+"/api/v0/swarm/addrs", url.Values{}) + + defer resp.Body.Close() + + apiResponse, err := ioutil.ReadAll(resp.Body) + + if err != nil { + return + } + var obj = map[string]map[string][]string{} + json.Unmarshal([]byte(apiResponse), &obj) + for k, v := range obj["Addrs"] { + for _, addr := range v { + nodesList = append(nodesList, (addr + "/p2p/" + k)) + } + } + return +} + // CreateNode creates an internal Libp2p nodes and returns it and it's DHT Discovery service. func CreateNode(ctx context.Context, inputKey string, port int, handler network.StreamHandler) (node host.Host, dhtOut *dht.IpfsDHT, err error) { // Unmarshal Private Key @@ -34,6 +67,15 @@ func CreateNode(ctx context.Context, inputKey string, port int, handler network. if err != nil { return } + extraBootstrapNodes := []string{} + ipfsApiStr, ok := os.LookupEnv("HYPRSPACE_IPFS_API") + if ok { + ipfsApiAddr, err := ma.NewMultiaddr(ipfsApiStr) + if err == nil { + fmt.Println("[+] Getting additional peers from IPFS API") + extraBootstrapNodes = getExtraBootstrapNodes(ipfsApiAddr) + } + } ip6tcp := fmt.Sprintf("/ip6/::/tcp/%d", port) ip4tcp := fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port) @@ -74,7 +116,7 @@ func CreateNode(ctx context.Context, inputKey string, port int, handler network. // Convert Bootstap Nodes into usable addresses. BootstrapPeers := make(map[peer.ID]*peer.AddrInfo, len(peers)) - for _, addrStr := range peers { + for _, addrStr := range append(peers, extraBootstrapNodes...) { addr, err := ma.NewMultiaddr(addrStr) if err != nil { return node, dhtOut, err -- 2.37.2