allmende address: how others can join through a running node (status field 'share')
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// cmdAddress asks the running node on this machine for the addresses someone
|
||||
// else can use to join the network through it, and prints them with the
|
||||
// command to use. It is how a friend joins when the usual bootstrap name is
|
||||
// down, or to start a network of one's own.
|
||||
func cmdAddress(args []string) error {
|
||||
fs := flag.NewFlagSet("address", flag.ContinueOnError)
|
||||
httpAddr := fs.String("http", "127.0.0.1:8080", "HTTP address of the running node")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
share, err := fetchShare(context.Background(), *httpAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out, ok := formatShare(share)
|
||||
fmt.Print(out)
|
||||
if !ok {
|
||||
return fmt.Errorf("no address to share yet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchShare(ctx context.Context, httpAddr string) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+httpAddr+"/api/v1/status", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no node answers at %s (is it running? use --http if it listens elsewhere): %w", httpAddr, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("the node at %s answered %s", httpAddr, resp.Status)
|
||||
}
|
||||
var st struct {
|
||||
Share []string `json:"share"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&st); err != nil {
|
||||
return nil, fmt.Errorf("unreadable answer from %s: %w", httpAddr, err)
|
||||
}
|
||||
return st.Share, nil
|
||||
}
|
||||
|
||||
// formatShare words the answer. ok is false when there is nothing to share.
|
||||
func formatShare(share []string) (string, bool) {
|
||||
if len(share) == 0 {
|
||||
return "This node has no address that others can reach yet.\n" +
|
||||
"A node behind a router needs a few seconds to learn its public address or to\n" +
|
||||
"take a relay; try again in a minute. If it stays empty, the node has no\n" +
|
||||
"public address and no relay: run it with --public and --announce, see k8s/README.md.\n", false
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("Someone who wants to join through this node starts theirs with:\n\n")
|
||||
fmt.Fprintf(&b, " allmende run --bootstrap %s\n", share[0])
|
||||
if len(share) > 1 {
|
||||
b.WriteString("\nOther addresses of this node (any one is enough):\n")
|
||||
for _, a := range share[1:] {
|
||||
fmt.Fprintf(&b, " %s\n", a)
|
||||
}
|
||||
}
|
||||
b.WriteString("\nThe address works while this node runs; a node behind a router is reached\nthrough its relay, which can change.\n")
|
||||
return b.String(), true
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatShareGivesTheCommandToRun(t *testing.T) {
|
||||
out, ok := formatShare([]string{"/ip4/8.8.8.8/tcp/4001/p2p/12D3KooWAAA", "/ip4/8.8.4.4/tcp/4001/p2p/12D3KooWAAA"})
|
||||
if !ok {
|
||||
t.Fatal("not ok with addresses")
|
||||
}
|
||||
if !strings.Contains(out, "allmende run --bootstrap /ip4/8.8.8.8/tcp/4001/p2p/12D3KooWAAA\n") {
|
||||
t.Fatalf("the first address is not in the command:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "/ip4/8.8.4.4/tcp/4001/p2p/12D3KooWAAA") {
|
||||
t.Fatalf("the second address is missing:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatShareSaysWhyThereIsNothingToShare(t *testing.T) {
|
||||
out, ok := formatShare(nil)
|
||||
if ok || !strings.Contains(out, "--announce") {
|
||||
t.Fatalf("ok=%v\n%s", ok, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchShareReadsTheNodesStatus(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/status" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"peer_id":"x","share":["/ip4/8.8.8.8/tcp/4001/p2p/12D3KooWAAA"]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
got, err := fetchShare(context.Background(), strings.TrimPrefix(srv.URL, "http://"))
|
||||
if err != nil || len(got) != 1 || got[0] != "/ip4/8.8.8.8/tcp/4001/p2p/12D3KooWAAA" {
|
||||
t.Fatalf("got %v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchShareExplainsAMissingNode(t *testing.T) {
|
||||
_, err := fetchShare(context.Background(), "127.0.0.1:1")
|
||||
if err == nil || !strings.Contains(err.Error(), "is it running") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchShareRefusesAnErrorAnswer(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "no", http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := fetchShare(context.Background(), strings.TrimPrefix(srv.URL, "http://")); err == nil {
|
||||
t.Fatal("an error answer was accepted")
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ Usage:
|
||||
allmende init [--data DIR] [--no-phrase] create your identity (first run)
|
||||
allmende run [--data DIR] --region u1x run the node
|
||||
allmende recover [--data DIR] restore access using your recovery phrase
|
||||
allmende address [--http ADDR] show how others can join through your running node
|
||||
|
||||
Run "allmende <command> -h" for the options of a command.
|
||||
`
|
||||
@@ -53,6 +54,8 @@ func main() {
|
||||
err = cmdRun(os.Args[2:])
|
||||
case "recover":
|
||||
err = cmdRecover(os.Args[2:])
|
||||
case "address":
|
||||
err = cmdAddress(os.Args[2:])
|
||||
case "version", "-v", "--version":
|
||||
fmt.Println("allmende", version)
|
||||
case "help", "-h", "--help":
|
||||
|
||||
Reference in New Issue
Block a user