From f83a305ee54f11adea48e2e6df88ee4a9375d745 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Thu, 19 Nov 2026 10:31:19 +0100 Subject: [PATCH] allmende address: how others can join through a running node (status field 'share') Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- README.md | 5 +++ SPECS.md | 2 +- cmd/allmende/address.go | 79 ++++++++++++++++++++++++++++++++++++ cmd/allmende/address_test.go | 61 ++++++++++++++++++++++++++++ cmd/allmende/main.go | 3 ++ docs/PROTOCOL.md | 7 ++++ internal/api/api.go | 6 ++- internal/p2p/share.go | 47 +++++++++++++++++++++ internal/p2p/share_test.go | 39 ++++++++++++++++++ 9 files changed, 246 insertions(+), 3 deletions(-) create mode 100644 cmd/allmende/address.go create mode 100644 cmd/allmende/address_test.go create mode 100644 internal/p2p/share.go create mode 100644 internal/p2p/share_test.go diff --git a/README.md b/README.md index bfaea2e..f1ab1c5 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,11 @@ the peers they met last time, a DHT per region, and mDNS on the local network. Add your own bootstrap peers with `--bootstrap /ip4//tcp//p2p/` (or `/dnsaddr/`), or turn the built-in one off with `--no-default-bootstrap`. +**Letting a friend join through your node:** with your node running, `allmende +address` prints the command for them (`allmende run --bootstrap `). +It lists only addresses reachable from the internet, a direct one before one +through a relay; behind a router it can take a minute until there is one. + **Running a bootstrap node** helps everyone else connect, and nodes behind a home router use it as a relay. It needs a public address: diff --git a/SPECS.md b/SPECS.md index 6b9bc20..e90f053 100644 --- a/SPECS.md +++ b/SPECS.md @@ -248,7 +248,7 @@ make image # build and push the container image (clean tree only) | Path | What | |---|---| -| `cmd/allmende` | CLI: `init`, `run`, `recover`, `version`; flags; terminal notices; shutdown | +| `cmd/allmende` | CLI: `init`, `run`, `recover`, `address` (the address others can join through), `version`; flags; terminal notices; shutdown | | `internal/identity` | phrase → root key, certificates, device keys, revocations | | `internal/listing` | the listing record: seal, check, regions, geohash | | `internal/message` | encrypted envelopes, plaintext rules, sealing (mirrored in `web/src/message.ts`, checked against a golden fixture) | diff --git a/cmd/allmende/address.go b/cmd/allmende/address.go new file mode 100644 index 0000000..0100f06 --- /dev/null +++ b/cmd/allmende/address.go @@ -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 +} diff --git a/cmd/allmende/address_test.go b/cmd/allmende/address_test.go new file mode 100644 index 0000000..e29d58f --- /dev/null +++ b/cmd/allmende/address_test.go @@ -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") + } +} diff --git a/cmd/allmende/main.go b/cmd/allmende/main.go index f60445b..bd38cda 100644 --- a/cmd/allmende/main.go +++ b/cmd/allmende/main.go @@ -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 -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": diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index f4e6652..4285a99 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -545,8 +545,15 @@ allmende init # create identity, show the 12-w allmende run --region u1x [--bootstrap ] # replicate a region, serve the API on 127.0.0.1:8080 allmende run --public [--listen …] # a bootstrap node: DHT server and relay allmende recover # restore from the phrase; also yearly cert renewal +allmende address # how others can join through this running node ``` +`address` asks the node on `--http` (default 127.0.0.1:8080) for the `share` +field of `/api/v1/status`: its addresses reachable from the internet (direct +first, then through a relay; none for loopback and private ones) and prints +`allmende run --bootstrap
`. It lets a person join through any node +when the built-in bootstrap name is down. + `run` also takes `--no-default-bootstrap`, `--no-dht` and `--no-mdns`, and keeps the peers it has met in `peers.json` next to its keys. diff --git a/internal/api/api.go b/internal/api/api.go index 9a10529..f1f778a 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -198,8 +198,10 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) { return } writeJSON(w, http.StatusOK, map[string]any{ - "peer_id": s.Node.ID().String(), - "addrs": s.Node.Addrs(), + "peer_id": s.Node.ID().String(), + "addrs": s.Node.Addrs(), + // What someone else can pass to --bootstrap to join through this node. + "share": s.Node.ShareAddrs(), "author": s.Device.Cert.Author, "device": s.Device.Cert.Device, "regions": s.regions(), diff --git a/internal/p2p/share.go b/internal/p2p/share.go new file mode 100644 index 0000000..b4a70dc --- /dev/null +++ b/internal/p2p/share.go @@ -0,0 +1,47 @@ +package p2p + +import ( + "slices" + + ma "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr/net" +) + +// ShareAddrs returns the addresses another person could use to join the +// network through this node (`allmende run --bootstrap
`): the ones +// reachable from the internet, with a direct address before one through a +// relay. Local and private addresses are left out, as nobody else can dial +// them. A node behind a router has none until it knows its public address or +// has taken a relay reservation, which takes a few seconds after the start. +func (n *Node) ShareAddrs() []string { return shareable(n.Addrs()) } + +func shareable(addrs []string) []string { + var direct, relayed []string + for _, a := range addrs { + m, err := ma.NewMultiaddr(a) + if err != nil || !manet.IsPublicAddr(m) { + continue + } + if isCircuit(m) { + relayed = append(relayed, a) + } else { + direct = append(direct, a) + } + } + slices.Sort(direct) + slices.Sort(relayed) + return append(direct, relayed...) +} + +// isCircuit reports whether m goes through a relay (contains /p2p-circuit). +func isCircuit(m ma.Multiaddr) bool { + found := false + ma.ForEach(m, func(c ma.Component) bool { + if c.Protocol().Code == ma.P_CIRCUIT { + found = true + return false + } + return true + }) + return found +} diff --git a/internal/p2p/share_test.go b/internal/p2p/share_test.go new file mode 100644 index 0000000..f1b9f60 --- /dev/null +++ b/internal/p2p/share_test.go @@ -0,0 +1,39 @@ +package p2p + +import ( + "slices" + "testing" +) + +const ( + idA = "12D3KooWQsiJgoN2o9KzvSFdvB5RZPursnQUqSD3v5i9sXrZZciw" + idB = "12D3KooWPA8Gigzxf2cBVkBKytSh8HUPpcufsFdVmiin8RQ8tFnx" +) + +func TestOnlyAddressesFromTheInternetAreShared(t *testing.T) { + got := shareable([]string{ + "/ip4/127.0.0.1/tcp/4001/p2p/" + idB, + "/ip4/192.168.1.20/tcp/4001/p2p/" + idB, + "/ip6/::1/tcp/4001/p2p/" + idB, + "/ip4/10.1.2.3/udp/4001/quic-v1/p2p/" + idB, + "/ip4/1.1.1.1/tcp/4001/p2p/" + idA + "/p2p-circuit/p2p/" + idB, // through a relay + "/ip4/8.8.8.8/tcp/4001/p2p/" + idB, // direct + "/dns4/node.example.org/tcp/4001/p2p/" + idB, + "not an address", + }) + want := []string{ + "/dns4/node.example.org/tcp/4001/p2p/" + idB, + "/ip4/8.8.8.8/tcp/4001/p2p/" + idB, + "/ip4/1.1.1.1/tcp/4001/p2p/" + idA + "/p2p-circuit/p2p/" + idB, // relayed last + } + if !slices.Equal(got, want) { + t.Fatalf("got\n %v\nwant\n %v", got, want) + } +} + +func TestANodeWithOnlyLocalAddressesSharesNothing(t *testing.T) { + a := startNode(t, nil, "u1x") // listens on 127.0.0.1 only + if got := a.ShareAddrs(); len(got) != 0 { + t.Fatalf("shared %v", got) + } +}