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:
2026-11-19 10:31:19 +01:00
co-authored by Claude Sonnet 5.5
parent d94c7b5b86
commit f83a305ee5
9 changed files with 246 additions and 3 deletions
+5
View File
@@ -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/<addr>/tcp/<port>/p2p/<peer id>`
(or `/dnsaddr/<name>`), 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 <your address>`).
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:
+1 -1
View File
@@ -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) |
+79
View File
@@ -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
}
+61
View File
@@ -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")
}
}
+3
View File
@@ -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":
+7
View File
@@ -545,8 +545,15 @@ allmende init # create identity, show the 12-w
allmende run --region u1x [--bootstrap <addr>] # 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 <address>`. 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.
+2
View File
@@ -200,6 +200,8 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"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(),
+47
View File
@@ -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 <address>`): 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
}
+39
View File
@@ -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)
}
}