Skip to content

Commit

Permalink
Add old modes as stanalone binaries
Browse files Browse the repository at this point in the history
  • Loading branch information
bahner committed Mar 17, 2024
1 parent 0f25ba0 commit 41c895b
Show file tree
Hide file tree
Showing 13 changed files with 338 additions and 28 deletions.
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}"
},
{
"name": "Launch allowAll",
"type": "go",
Expand Down
9 changes: 9 additions & 0 deletions cmd/actor/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,13 @@ func initConfig() {
config.Generate(actorConfig)
os.Exit(0)
}

config.InitActor()

// This flag is dependent on the actor to be initialized to make sense.
if config.ShowConfigFlag() {
config.Print()
os.Exit(0)
}

}
12 changes: 11 additions & 1 deletion cmd/pong/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,13 @@ func pongReply() string {
return viper.GetString("mode.pong.reply")
}

func initConfig() {
func initConfig(profile string) {

// Always parse the flags first
config.InitCommonFlags()
config.InitActorFlags()
pflag.Parse()
config.SetProfile(profile)
config.Init()

if config.GenerateFlag() {
Expand All @@ -58,4 +59,13 @@ func initConfig() {
config.Generate(actorConfig)
os.Exit(0)
}

config.InitActor()

// This flag is dependent on the actor to be initialized to make sense.
if config.ShowConfigFlag() {
config.Print()
os.Exit(0)
}

}
4 changes: 1 addition & 3 deletions cmd/pong/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
func main() {

ctx := context.Background()
initConfig()
initConfig(pong)

a := initActorOrPanic()

Expand All @@ -21,8 +21,6 @@ func main() {
return
}

initConfig()

fmt.Printf("Starting pong mode as %s\n", a.Entity.DID.Id)
go p.StartDiscoveryLoop(ctx)
fmt.Println("Discovery loop started.")
Expand Down
31 changes: 31 additions & 0 deletions cmd/relay/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"os"

"github.com/bahner/go-ma-actor/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
)

func initConfig(profile string) {

// Always parse the flags first
config.InitCommonFlags()
pflag.Parse()
config.SetProfile(profile)
config.Init()

if config.GenerateFlag() {
// Reinit logging to STDOUT
log.SetOutput(os.Stdout)
log.Info("Generating new actor and node identity")
node, err := config.GenerateNodeIdentity()
if err != nil {
log.Fatalf("Failed to generate node identity: %v", err)
}
relayConfig := configTemplate(node)
config.Generate(relayConfig)
os.Exit(0)
}
}
38 changes: 38 additions & 0 deletions cmd/relay/dht.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"fmt"

"github.com/bahner/go-ma-actor/config"
"github.com/bahner/go-ma-actor/p2p"
"github.com/bahner/go-ma-actor/p2p/connmgr"
"github.com/bahner/go-ma-actor/p2p/node"
"github.com/libp2p/go-libp2p"
p2pDHT "github.com/libp2p/go-libp2p-kad-dht"
)

func DHT(cg *connmgr.ConnectionGater) (*p2p.DHT, error) {

// THese are the relay specific parts.
p2pOpts := []libp2p.Option{
libp2p.ConnectionGater(cg),
libp2p.EnableRelay(),
libp2p.EnableRelayService(),
}

dhtOpts := []p2pDHT.Option{
p2pDHT.Mode(p2pDHT.ModeServer),
}

n, err := node.New(config.NodeIdentity(), p2pOpts...)
if err != nil {
return nil, fmt.Errorf("pong: failed to create libp2p node: %w", err)
}

d, err := p2p.NewDHT(n, cg, dhtOpts...)
if err != nil {
return nil, fmt.Errorf("pong: failed to create DHT: %w", err)
}

return d, nil
}
43 changes: 43 additions & 0 deletions cmd/relay/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"context"
"fmt"
"net/http"

"github.com/bahner/go-ma-actor/config"
log "github.com/sirupsen/logrus"
)

const relay = "relay"

// Run the pong actor. Cancel it from outside to stop it.
func main() {

ctx := context.Background()
initConfig(relay)

p, err := initP2P()
if err != nil {
fmt.Printf("Failed to initialize p2p: %v\n", err)
return
}

go p.StartDiscoveryLoop(ctx)
fmt.Println("Discovery loop started.")

// Start a simple web server to handle incoming requests.
// This is defined in web.go. It makes it possible to add extra parameters to the handler.
mux := http.NewServeMux()
h := &WebHandlerData{
P2P: p,
}
mux.HandleFunc("/", h.WebHandler)

log.Infof("Listening on %s", config.HttpSocket())

// IN relay mode we want to stop here.
fmt.Println("Web server starting on http://" + config.HttpSocket() + "/")
http.ListenAndServe(config.HttpSocket(), mux)

}
26 changes: 26 additions & 0 deletions cmd/relay/p2p.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"fmt"

"github.com/bahner/go-ma-actor/p2p"
"github.com/bahner/go-ma-actor/p2p/connmgr"
)

func initP2P() (P2P *p2p.P2P, err error) {
fmt.Println("Initialising libp2p...")

// Everyone needs a connection manager.
cm, err := connmgr.Init()
if err != nil {
panic(fmt.Errorf("pong: failed to create connection manager: %w", err))
}
cg := connmgr.NewConnectionGater(cm)

d, err := DHT(cg)
if err != nil {
panic(fmt.Sprintf("failed to initialize dht: %v", err))
}

return p2p.Init(d)
}
38 changes: 38 additions & 0 deletions cmd/relay/peers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"sort"

"github.com/bahner/go-ma-actor/p2p/peer"
p2peer "github.com/libp2p/go-libp2p/core/peer"
)

func UnorderedListFromPeerIDSlice(peers p2peer.IDSlice) string {
peersMap := make(map[string]string)
for _, p := range peers {
id := p.String()
nick, err := peer.LookupNick(id)
if err != nil {
peersMap[id] = id
} else {
peersMap[id] = nick
}
}

var keys []string
for _, p := range peers {
keys = append(keys, p.String())
}
sort.Strings(keys)

list := "<table>\n"
for _, v := range keys {
if peersMap[v] == v {
list += "<tr><td span=2>" + v + "</td></tr>\n"
} else {
list += "<tr><td>" + v + "</td><td>" + peersMap[v] + "</td></tr>\n"
}
}
list += "</table>\n"
return list
}
42 changes: 42 additions & 0 deletions cmd/relay/template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"github.com/bahner/go-ma-actor/config"
)

func configTemplate(node string) map[string]interface{} {

// Get the default settings as a map
// Note: Viper does not have a built-in way to directly extract only the config
// so we manually recreate the structure based on the config we have set.
return map[string]interface{}{
"db": map[string]interface{}{
"file": config.DefaultDbFile,
},
"log": map[string]interface{}{
"level": config.LogLevel(),
"file": config.LogFile(),
},
"http": map[string]interface{}{
"socket": config.HttpSocket(),
"refresh": config.HttpRefresh(),
},
"p2p": map[string]interface{}{
"identity": node,
"port": config.P2PPort(),
"connmgr": map[string]interface{}{
"low-watermark": config.P2PConnmgrLowWatermark(),
"high-watermark": config.P2PConnmgrHighWatermark(),
"grace-period": config.P2PConnMgrGracePeriod(),
},
"discovery": map[string]interface{}{
"advertise-ttl": config.P2PDiscoveryAdvertiseTTL(),
"advertise-limit": config.P2PDiscoveryAdvertiseLimit(),
"advertise-interval": config.P2PDiscoveryAdvertiseInterval(),
"dht": config.P2PDiscoveryDHT(),
"mdns": config.P2PDiscoveryMDNS(),
},
},
}

}
91 changes: 91 additions & 0 deletions cmd/relay/web_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package main

import (
"fmt"
"net/http"

"github.com/bahner/go-ma"
"github.com/bahner/go-ma-actor/config"
"github.com/bahner/go-ma-actor/p2p"
p2peer "github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
)

// Assuming you have initialized variables like `h` and `rendezvous` somewhere in your main function or globally

type WebHandlerData struct {
P2P *p2p.P2P
}

type WebHandlerDocument struct {
Title string
H1 string
Addrs []multiaddr.Multiaddr
ProtectedPeers p2peer.IDSlice
UnprotectedPeers p2peer.IDSlice
}

func NewWebHandlerDocument() *WebHandlerDocument {
return &WebHandlerDocument{}
}

func (data *WebHandlerData) WebHandler(w http.ResponseWriter, r *http.Request) {
webHandler(w, r, data.P2P)
}

func webHandler(w http.ResponseWriter, _ *http.Request, p *p2p.P2P) {

doc := NewWebHandlerDocument()

doc.Title = fmt.Sprintf("Bootstrap peer for rendezvous %s.", ma.RENDEZVOUS)
doc.H1 = fmt.Sprintf("%s@%s", ma.RENDEZVOUS, (p.Host.ID().String()))
doc.H1 += fmt.Sprintf("<br>Found %d peers with rendezvous %s", len(p.ConnectedProtectedPeers()), ma.RENDEZVOUS)
doc.Addrs = p.Host.Addrs()
doc.ProtectedPeers = p.ConnectedProtectedPeers()
doc.UnprotectedPeers = p.ConnectedUnprotectedPeers()
// doc.AllConnectedPeers = p.GetAllConnectedPeers()

fmt.Fprint(w, doc.String())
}

func (d *WebHandlerDocument) String() string {

html := "<!DOCTYPE html>\n<html>\n<head>\n"
html += "<style>table, th, td {border: 1px solid black;}</style>"

if d.Title != "" {
html += "<title>" + d.Title + "</title>\n"
}
html += fmt.Sprintf(`<meta http-equiv="refresh" content="%d">`, config.HttpRefresh())
html += "</head>\n<body>\n"
if d.H1 != "" {
html += "<h1>" + d.H1 + "</h1>\n"
}
html += "<hr>"

// Info leak? Not really important anyways.
// // Addresses
if len(d.Addrs) > 0 {
html += "<h2>Addresses</h2>\n"
html += "<table>\n"
for _, addr := range d.Addrs {
html += "<tr><td>" + addr.String() + "</td></tr>"
}
html += "</table>"
}

// Peers with Same Rendezvous
if len(d.ProtectedPeers) > 0 {
html += fmt.Sprintf("<h2>Discovered peers (%d):</h2>\n", len(d.ProtectedPeers))
html += UnorderedListFromPeerIDSlice(d.ProtectedPeers)
}
// All Connected Peers
if len(d.UnprotectedPeers) > 0 {
html += fmt.Sprintf("<h2>libp2p Network Peers (%d):</h2>\n", len(d.UnprotectedPeers))

html += UnorderedListFromPeerIDSlice(d.UnprotectedPeers)
}

html += "</body>\n</html>"
return html
}
Loading

0 comments on commit 41c895b

Please sign in to comment.