From e7bec4fb63d2a1ed47026bb0ea5cfbacf5e30374 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Tue, 17 Nov 2026 22:14:34 +0100 Subject: [PATCH] Add bootstrap nodes, DNS-based discovery, a DHT per region and NAT traversal - Bootstrap: built-in /dnsaddr/allmende.stinnesbeck.com (TXT records at _dnsaddr.), resolved at every redial with the last good answer kept; --bootstrap takes /p2p/ or /dnsaddr/ entries, --no-default-bootstrap drops the built-in one. Stopping never waits for a stuck resolver. - Remembered peers in peers.json (saved every 5 min and on shutdown, redialled at the next start) - Private Kademlia DHT (/allmende prefix), advertised and looked up per region with quick first attempts and a backoff; --no-dht turns it off - NAT traversal: port mapping, hole punching, AutoRelay through bootstrap nodes - --public: DHT server and relay for a bootstrap node; prints the TXT records - Docker, NixOS module (public, defaultBootstrap, QUIC/UDP) and docs updated - e2e: bootstrap node scenario, seed cache restart, and polling that really polls Co-Authored-By: Claude Sonnet 5.5 --- Dockerfile | 13 +- README.md | 21 ++- cmd/allmende/bootstrap.go | 21 +++ cmd/allmende/bootstrap_test.go | 29 ++++ cmd/allmende/main.go | 1 + cmd/allmende/run.go | 31 +++- docs/PROTOCOL.md | 55 +++++- go.mod | 30 +++- go.sum | 93 +++++++++- internal/p2p/bootstrap.go | 185 ++++++++++++++++++++ internal/p2p/bootstrap_test.go | 309 +++++++++++++++++++++++++++++++++ internal/p2p/discovery.go | 163 +++++++++++++++++ internal/p2p/node.go | 123 ++++++++++--- internal/p2p/peercache.go | 178 +++++++++++++++++++ nix/module.nix | 35 +++- nix/package.nix | 2 +- nix/test.nix | 6 +- scripts/e2e.sh | 55 +++++- 18 files changed, 1281 insertions(+), 69 deletions(-) create mode 100644 cmd/allmende/bootstrap.go create mode 100644 cmd/allmende/bootstrap_test.go create mode 100644 internal/p2p/bootstrap.go create mode 100644 internal/p2p/bootstrap_test.go create mode 100644 internal/p2p/discovery.go create mode 100644 internal/p2p/peercache.go diff --git a/Dockerfile b/Dockerfile index 508e21c..65e49f9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,11 +4,12 @@ # docker build -t allmende . # docker run --rm -it -v allmende-data:/data allmende init # once; shows the recovery phrase # docker run -d --name allmende -v allmende-data:/data \ -# -p 127.0.0.1:8080:8080 -p 4001:4001 allmende # run (Bonn by default) +# -p 127.0.0.1:8080:8080 -p 4001:4001 -p 4001:4001/udp allmende # run (Bonn by default) # # The HTTP port also serves the owner API, which the admin token protects, so # publish it on 127.0.0.1 only and put a TLS proxy in front for public use. -# Port 4001 is the libp2p port other nodes connect to. +# Port 4001 (TCP and UDP/QUIC) is the libp2p port other nodes connect to. +# The node remembers its peers in /data/peers.json, so keep the volume. ARG GO_VERSION=1.27 @@ -25,11 +26,13 @@ COPY --from=build /out/allmende /usr/local/bin/allmende USER allmende ENV ALLMENDE_DATA=/data VOLUME /data -EXPOSE 8080 4001 +EXPOSE 8080 4001/tcp 4001/udp HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ CMD wget -qO- http://127.0.0.1:8080/api/v1/status >/dev/null || exit 1 ENTRYPOINT ["allmende"] # Override the whole command to change regions or add peers, e.g. -# docker run ... allmende run --http 0.0.0.0:8080 --listen /ip4/0.0.0.0/tcp/4001 \ +# docker run ... allmende run --http 0.0.0.0:8080 \ +# --listen /ip4/0.0.0.0/tcp/4001 --listen /ip4/0.0.0.0/udp/4001/quic-v1 \ # --region u1j --region u1h --bootstrap /ip4/203.0.113.5/tcp/4001/p2p/ -CMD ["run", "--http", "0.0.0.0:8080", "--listen", "/ip4/0.0.0.0/tcp/4001", "--region", "u1j"] +# A bootstrap node adds --public (and needs a public address). +CMD ["run", "--http", "0.0.0.0:8080", "--listen", "/ip4/0.0.0.0/tcp/4001", "--listen", "/ip4/0.0.0.0/udp/4001/quic-v1", "--region", "u1j"] diff --git a/README.md b/README.md index 77f97a8..a0e67ab 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,23 @@ Owners publish from the same screen: "New listing" takes a title, price and pasted coordinates (only a ~1 km area is published, never the address), and listings can be edited, renewed (30 days, manually) or deleted there. -A second node on the same network finds this one automatically (mDNS); across -networks, pass `--bootstrap /ip4//tcp//p2p/`. +Nodes find each other through a bootstrap list in DNS (`allmende.stinnesbeck.com`), +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`. + +**Running a bootstrap node** helps everyone else connect, and nodes behind a home +router use it as a relay. It needs a public address: + +``` +allmende run --public --listen /ip4/0.0.0.0/tcp/4001 --listen /ip4/0.0.0.0/udp/4001/quic-v1 +``` + +It prints the DNS TXT records to publish at `_dnsaddr.allmende.stinnesbeck.com` +(`dnsaddr=/ip4//tcp/4001/p2p/`, one per address). With a few such +nodes on different networks, the network no longer depends on any one of them. +In Docker replace the command (see the end of the `Dockerfile`) and add `--public`; +the NixOS module has `services.allmende.public = true`. ## Running a node for real @@ -42,7 +57,7 @@ targets: `make build run test check e2e docker` (`make help` lists them). docker build -t allmende . # or: make docker docker run --rm -it -v allmende-data:/data allmende init # once; write down the phrase docker run -d --name allmende -v allmende-data:/data \ - -p 127.0.0.1:8080:8080 -p 4001:4001 allmende # Bonn (u1j) by default + -p 127.0.0.1:8080:8080 -p 4001:4001 -p 4001:4001/udp allmende # Bonn (u1j) by default docker logs allmende | grep -A1 'Owner login' # the sign-in link ``` diff --git a/cmd/allmende/bootstrap.go b/cmd/allmende/bootstrap.go new file mode 100644 index 0000000..c503be1 --- /dev/null +++ b/cmd/allmende/bootstrap.go @@ -0,0 +1,21 @@ +package main + +import ( + ma "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr/net" +) + +// bootstrapRecords turns a node's addresses into the DNS TXT values that make +// it a bootstrap node, one per publicly routable address. Loopback and private +// addresses are left out: nobody else could use them. +func bootstrapRecords(addrs []string) []string { + var out []string + for _, a := range addrs { + m, err := ma.NewMultiaddr(a) + if err != nil || !manet.IsPublicAddr(m) { + continue + } + out = append(out, "dnsaddr="+a) + } + return out +} diff --git a/cmd/allmende/bootstrap_test.go b/cmd/allmende/bootstrap_test.go new file mode 100644 index 0000000..9844ed3 --- /dev/null +++ b/cmd/allmende/bootstrap_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestBootstrapRecordsKeepOnlyPublicAddresses(t *testing.T) { + const id = "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo" + got := bootstrapRecords([]string{ + "/ip4/127.0.0.1/tcp/4001/p2p/" + id, // loopback + "/ip4/192.168.1.20/tcp/4001/p2p/" + id, // private + "/ip4/10.0.0.5/udp/4001/quic-v1/p2p/" + id, // private + "/ip4/93.184.216.34/tcp/4001/p2p/" + id, // public + "/ip4/93.184.216.34/udp/4001/quic-v1/p2p/" + id, // public + "/ip6/::1/tcp/4001/p2p/" + id, // loopback + "/ip6/2606:4700:4700::1111/tcp/4001/p2p/" + id, // public + "/ip4/203.0.113.5/tcp/4001/p2p/" + id, // a documentation range, never routable + "not an address", + }) + want := []string{ + "dnsaddr=/ip4/93.184.216.34/tcp/4001/p2p/" + id, + "dnsaddr=/ip4/93.184.216.34/udp/4001/quic-v1/p2p/" + id, + "dnsaddr=/ip6/2606:4700:4700::1111/tcp/4001/p2p/" + id, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %v\nwant %v", got, want) + } +} diff --git a/cmd/allmende/main.go b/cmd/allmende/main.go index d1a1091..f931b15 100644 --- a/cmd/allmende/main.go +++ b/cmd/allmende/main.go @@ -21,6 +21,7 @@ const ( dbFile = "allmende.db" tokenFile = "admin.token" + peersFile = "peers.json" // peers met on earlier runs ) const usage = `Allmende: a free, distributed marketplace for homes. diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index 6b4c076..3347c63 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -11,6 +11,7 @@ import ( "os" "os/signal" "path/filepath" + "strings" "syscall" "time" @@ -34,7 +35,12 @@ func cmdRun(args []string) error { data := dataFlag(fs) var regions, bootstrap, listen listFlag fs.Var(®ions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable") - fs.Var(&bootstrap, "bootstrap", "multiaddr of a known peer (…/p2p/); repeatable") + fs.Var(&bootstrap, "bootstrap", "extra bootstrap peer: …/p2p/ or /dnsaddr/; repeatable") + noDefaultBootstrap := fs.Bool("no-default-bootstrap", false, + "do not use the built-in bootstrap name "+p2p.DefaultBootstrap) + noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT") + public := fs.Bool("public", false, + "this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)") fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)") httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API") noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network") @@ -46,9 +52,13 @@ func cmdRun(args []string) error { "how many new conversations each of your listings can start per day") fs.Parse(args) - if len(regions) == 0 { + // A bootstrap node may follow no region: it then only helps others connect. + if len(regions) == 0 && !*public { return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)") } + if !*noDefaultBootstrap { + bootstrap = append(bootstrap, p2p.DefaultBootstrap) + } dev, err := identity.LoadDevice(*data) if err != nil { @@ -85,6 +95,9 @@ func cmdRun(args []string) error { Bootstrap: bootstrap, Regions: regions, MDNS: !*noMDNS, + DHT: !*noDHT, + Public: *public, + PeerCache: filepath.Join(*data, peersFile), Difficulty: *difficulty, Logger: log, @@ -139,6 +152,20 @@ func cmdRun(args []string) error { log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public") } + if *public { + name := strings.TrimPrefix(p2p.DefaultBootstrap, "/dnsaddr/") + if recs := bootstrapRecords(node.Addrs()); len(recs) > 0 { + fmt.Fprintf(os.Stderr, "\nBootstrap node. For fresh nodes to find it, publish these TXT records at _dnsaddr.%s:\n", name) + for _, r := range recs { + fmt.Fprintf(os.Stderr, " %s\n", r) + } + fmt.Fprintln(os.Stderr) + } else { + log.Warn("--public, but this node has no public address; a bootstrap node needs one (a server, or a forwarded port): publish dnsaddr=/ip4//tcp//p2p/", + "peer_id", node.ID().String()) + } + } + if token != "" { // Printed to the terminal, not logged: the token must not end up in a // log file. It sits in the URL fragment, which a browser never sends to diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 394bb1a..c1ca103 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -14,9 +14,9 @@ running a node; searching is browser-only through any node's HTTP gateway. `/allmende/1/listings/`. Nodes subscribe to the regions they care about, replicate them, and index them locally. Fine-grained filtering (precision, kind, category, price) happens in local search. -- **Discovery**: configured bootstrap peers plus mDNS on the local network; - gossipsub peer exchange spreads the mesh. A Kademlia DHT can be added later - without protocol changes. +- **Discovery**: a DNS-based bootstrap list, remembered peers, a Kademlia DHT per + region and mDNS on the local network (see "Finding peers"); NAT traversal + through hole punching and relaying bootstrap nodes. - **License**: AGPL-3.0, so modified nodes and gateways must publish their source. - **Launch scope**: one German state or metro area. @@ -131,6 +131,48 @@ within 30 days. revocations every 30 minutes, so newcomers hear about them without waiting for a sync. +## Finding peers + +Four sources, tried together; none is required once a node has met the network. + +1. **Bootstrap.** A fresh node resolves the built-in name + `/dnsaddr/allmende.stinnesbeck.com` (`p2p.DefaultBootstrap`): libp2p reads the + TXT records of `_dnsaddr.allmende.stinnesbeck.com`, each + `dnsaddr=/ip4//tcp/4001/p2p/` (also `udp/…/quic-v1` and `ip6`). + The list of bootstrap nodes therefore changes in DNS, without a new release. + `--bootstrap` adds `/p2p/` addresses or other `/dnsaddr/` names; + `--no-default-bootstrap` drops the built-in one. A name is resolved at every + redial; the last good answer is kept if DNS is briefly unreachable, and a + failure is logged once, not every 20 s. A node never dials itself. +2. **Remembered peers.** The node saves the peers it is connected to in + `peers.json` in its data directory (every 5 minutes and on shutdown: at most + 100, none older than 30 days, relayed addresses left out) and redials the 10 + most recent at the next start. After one successful run it no longer needs + a bootstrap node. +3. **DHT.** A Kademlia DHT with its own protocol prefix (`/allmende/kad/1.0.0`, + so it never mixes with the IPFS DHT). For every region it follows, a node + advertises itself under `allmende/region/` and looks up the others, + connecting to up to 20 until its region topic has 8 peers. Lookups start + within seconds and back off to once a minute. Bootstrap nodes only seed the + routing table. `--no-dht` turns it off. +4. **mDNS** on the local network (`--no-mdns` turns it off). + +**Behind a NAT.** Most nodes run behind a home router. Each node asks the router +for a port mapping (UPnP/NAT-PMP), asks other nodes whether it is reachable +(AutoNAT), and when it is not, takes a reservation on a bootstrap node (a +circuit-relay v2 slot) so others can reach it; the two then try a direct +connection by hole punching (DCUtR). Relayed connections are limited by libp2p +(2 minutes, 128 KB) and only carry that hand-over. If hole punching fails, a +node still takes part: it dials out, and gossip reaches it through the nodes it +is connected to. + +**Running a bootstrap node.** `allmende run --public --listen +/ip4/0.0.0.0/tcp/4001 --listen /ip4/0.0.0.0/udp/4001/quic-v1` on a machine with +a public address (or forwarded ports). `--public` makes it a DHT server and a +relay for nodes behind NATs, and it may follow no region at all. It prints the +TXT records to publish at `_dnsaddr.`; add one record set per bootstrap +node, so several can coexist. Run at least two, on different networks. + ## Messaging Implemented in `internal/message` (wire format), `internal/inbox` (owner side) @@ -418,9 +460,13 @@ needed to change the UI (`cd web && npm ci && npm run build`). ``` allmende init # create identity, show the 12-word phrase (once) 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 ``` +`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. + ## Spam Proof-of-work per listing and per revocation, plus subscribable blocklists @@ -430,6 +476,7 @@ Proof-of-work per listing and per revocation, plus subscribable blocklists Abuse reporting for messages, reciprocity rules, anti- discrimination (AGG) content rules, blocklists, peer scoring and rate limits, -incremental sync and anti-entropy, DHT discovery, image hosting, +incremental sync and anti-entropy, a fallback bootstrap list inside the binary +for networks that block DNS, image hosting, recovering listings onto a fresh machine with an empty database, a helper to turn a place name into a region. diff --git a/go.mod b/go.mod index e883c47..e4c43cb 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,10 @@ go 1.27.3 require ( filippo.io/edwards25519 v1.2.0 github.com/libp2p/go-libp2p v0.52.0 + github.com/libp2p/go-libp2p-kad-dht v0.43.0 github.com/libp2p/go-libp2p-pubsub v0.19.0 + github.com/multiformats/go-multiaddr v0.16.1 + github.com/multiformats/go-multiaddr-dns v0.6.0 github.com/tyler-smith/go-bip39 v1.1.0 golang.org/x/crypto v0.59.0 golang.org/x/term v0.48.0 @@ -24,18 +27,30 @@ require ( github.com/dustin/go-humanize v1.1.0 // indirect github.com/filecoin-project/go-clock v0.1.0 // indirect github.com/flynn/noise v1.1.0 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/gopacket v1.1.19 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect + github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/huin/goupnp v1.3.1 // indirect + github.com/ipfs/boxo v0.43.0 // indirect github.com/ipfs/go-cid v0.6.2 // indirect + github.com/ipfs/go-datastore v0.9.2 // indirect + github.com/ipfs/go-log/v2 v2.9.2 // indirect + github.com/ipld/go-ipld-prime v0.24.0 // indirect github.com/jackpal/go-nat-pmp v1.1.0 // indirect github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect github.com/klauspost/cpuid/v2 v2.4.2 // indirect github.com/koron/go-ssdp v0.9.2 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect + github.com/libp2p/go-cidranger v1.1.0 // indirect github.com/libp2p/go-flow-metrics v0.3.0 // indirect github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect + github.com/libp2p/go-libp2p-kbucket v0.9.0 // indirect + github.com/libp2p/go-libp2p-record v0.3.1 // indirect + github.com/libp2p/go-libp2p-routing-helpers v0.7.5 // indirect github.com/libp2p/go-msgio v0.3.0 // indirect github.com/libp2p/go-netroute v0.4.0 // indirect github.com/libp2p/go-reuseport v0.4.0 // indirect @@ -50,8 +65,6 @@ require ( github.com/mr-tron/base58 v1.3.0 // indirect github.com/multiformats/go-base32 v0.1.0 // indirect github.com/multiformats/go-base36 v0.2.0 // indirect - github.com/multiformats/go-multiaddr v0.16.1 // indirect - github.com/multiformats/go-multiaddr-dns v0.6.0 // indirect github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect github.com/multiformats/go-multibase v0.3.0 // indirect github.com/multiformats/go-multicodec v0.10.0 // indirect @@ -63,7 +76,7 @@ require ( github.com/pandatix/go-abnf v0.5.5 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pion/datachannel v1.5.10 // indirect - github.com/pion/dtls/v3 v3.1.2 // indirect + github.com/pion/dtls/v3 v3.1.4 // indirect github.com/pion/ice/v4 v4.0.10 // indirect github.com/pion/interceptor v0.1.40 // indirect github.com/pion/logging v0.2.4 // indirect @@ -74,11 +87,12 @@ require ( github.com/pion/sctp v1.8.39 // indirect github.com/pion/sdp/v3 v3.0.18 // indirect github.com/pion/srtp/v3 v3.0.6 // indirect - github.com/pion/stun/v3 v3.1.1 // indirect + github.com/pion/stun/v3 v3.1.5 // indirect github.com/pion/transport/v3 v3.0.7 // indirect - github.com/pion/transport/v4 v4.0.1 // indirect + github.com/pion/transport/v4 v4.0.2 // indirect github.com/pion/turn/v4 v4.0.2 // indirect github.com/pion/webrtc/v4 v4.1.2 // indirect + github.com/polydawn/refmt v0.90.0 // indirect github.com/prometheus/client_golang v1.25.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.74.0 // indirect @@ -88,7 +102,12 @@ require ( github.com/quic-go/webtransport-go v0.13.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect + github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirect github.com/wlynxg/anet v0.0.5 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel v1.46.0 // indirect + go.opentelemetry.io/otel/metric v1.46.0 // indirect + go.opentelemetry.io/otel/trace v1.46.0 // indirect go.uber.org/dig v1.19.0 // indirect go.uber.org/fx v1.24.0 // indirect go.uber.org/mock v0.6.0 // indirect @@ -103,6 +122,7 @@ require ( golang.org/x/text v0.44.0 // indirect golang.org/x/time v0.16.0 // indirect golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect + gonum.org/v1/gonum v0.17.0 // indirect google.golang.org/protobuf v1.36.12 // indirect lukechampine.com/blake3 v1.4.1 // indirect modernc.org/libc v1.80.1 // indirect diff --git a/go.sum b/go.sum index bd2593c..6bccf7e 100644 --- a/go.sum +++ b/go.sum @@ -12,6 +12,7 @@ github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 h1:oe6 github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3/go.mod h1:qdP0gaj0QtgX2RUZhnlVrceJ+Qln8aSlDyJwelLLFeM= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c h1:pFUpOrbxDR6AkioZ1ySsx5yxlDQZ8stG2b88gTPxgJU= github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c/go.mod h1:6UhI8N9EjYm1c2odKpFpAYeR8dsBeM7PtzQhRgxRr9U= github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8= @@ -26,44 +27,84 @@ github.com/filecoin-project/go-clock v0.1.0 h1:SFbYIM75M8NnFm1yMHhN9Ahy3W5bEZV9g github.com/filecoin-project/go-clock v0.1.0/go.mod h1:4uB/O4PvOjlx1VCMdZ9MyDZXRm//gkj1ELEbxfI1AZs= github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg= github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8= +github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= +github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= +github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/huin/goupnp v1.3.1 h1:n8259zVoE4BU7dBCQEUlwZK1h0Z3pxZ58ov0xbJuIQU= github.com/huin/goupnp v1.3.1/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= +github.com/ipfs/boxo v0.43.0 h1:nhIbfBBxgLoAxUi8upOIO5RATy++2WigMVWniRJFjnw= +github.com/ipfs/boxo v0.43.0/go.mod h1:n9HNLPLfAGexg2DGoQ5B4BMVlmj9g4+5dIcuo7w95iI= +github.com/ipfs/go-block-format v0.2.4 h1:pgsT9i8zB4YQkBIQRrBwqbQiXPogRCiQnfxd2bC4koI= +github.com/ipfs/go-block-format v0.2.4/go.mod h1:YpXrOge8ARskfuJuqjvJTYr4v6o9IZWgK2EEIMAhpcU= github.com/ipfs/go-cid v0.6.2 h1:VuGwJd+KJTaMJ4S4d5EEf9SXc17YUblS5axCbocn9YE= github.com/ipfs/go-cid v0.6.2/go.mod h1:Xhwg8NzHeK9xPCEZkCw4idzPiuNMpX3fARuI5Iwj1Lo= +github.com/ipfs/go-datastore v0.9.2 h1:HJOgAmvWPRMHiwD8JHBzGZQNTKhuFGYfp8bNPwye28g= +github.com/ipfs/go-datastore v0.9.2/go.mod h1:VIjDxnINIcCqBMaB8LGggHfYY7PalKWfPtRMFeOU4q4= +github.com/ipfs/go-detect-race v0.0.1 h1:qX/xay2W3E4Q1U7d9lNs1sU9nvguX0a7319XbyQ6cOk= +github.com/ipfs/go-detect-race v0.0.1/go.mod h1:8BNT7shDZPo99Q74BpGMK+4D8Mn4j46UU0LZ723meps= +github.com/ipfs/go-log/v2 v2.9.2 h1:O/5BB0elpkRILvT24rCJ5976wWd7u0nJ436T3rdYdc4= +github.com/ipfs/go-log/v2 v2.9.2/go.mod h1:RziRwwXWhndlk8L75RnEe0zeAYaq2heKtEMc3jqUov0= +github.com/ipfs/go-test v0.4.1 h1:n6uNSakIgpTQIRorqNg2O02aMIFDLQk2z4rBfrlD3Uw= +github.com/ipfs/go-test v0.4.1/go.mod h1:QmvVBf9kClNtRuFow4DASq03eFvjKla4Fy/UAkeeLO8= +github.com/ipld/go-ipld-prime v0.24.0 h1:6th8Z6Peh5bCWuRAVZcDO1sHzZdVF6F2cCCDG3681tg= +github.com/ipld/go-ipld-prime v0.24.0/go.mod h1:DYZxr/5caLNFbcuU6zLOgwSW7CgUEoC4wJiZMEU8Zhs= github.com/jackpal/go-nat-pmp v1.1.0 h1:UInMLPV1VQdP860ggNiz0YxGvJH/bWzxL099y+1EdCs= github.com/jackpal/go-nat-pmp v1.1.0/go.mod h1:m9o4DK1wHA4h2pPpErD5vwzWLf91tJcfNQ3QyUIbh5A= github.com/jbenet/go-temp-err-catcher v0.1.0 h1:zpb3ZH6wIE8Shj2sKS+khgRvf7T7RABoLk/+KKHggpk= github.com/jbenet/go-temp-err-catcher v0.1.0/go.mod h1:0kJRvmDZXNMIiJirNPEYfhpPwbGVtZVWC34vc5WLsDk= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ= github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/koron/go-ssdp v0.9.2 h1:s7YOSyV2Sch54U4+JGtiT+qgyUUKqbHbelgAV5PBCu0= github.com/koron/go-ssdp v0.9.2/go.mod h1:AfRmwB0yUX/pCcB5dI7Z3947zo+sC3lXmqQOW8VO/TA= -github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= +github.com/libp2p/go-cidranger v1.1.0 h1:ewPN8EZ0dd1LSnrtuwd4709PXVcITVeuwbag38yPW7c= +github.com/libp2p/go-cidranger v1.1.0/go.mod h1:KWZTfSr+r9qEo9OkI9/SIEeAtw+NNoU0dXIXt15Okic= github.com/libp2p/go-flow-metrics v0.3.0 h1:q31zcHUvHnwDO0SHaukewPYgwOBSxtt830uJtUx6784= github.com/libp2p/go-flow-metrics v0.3.0/go.mod h1:nuhlreIwEguM1IvHAew3ij7A8BMlyHQJ279ao24eZZo= github.com/libp2p/go-libp2p v0.52.0 h1:jMnbVokEwR/XYnu7J9VCPClbtvlkWPvv4kFGO6r5aKY= github.com/libp2p/go-libp2p v0.52.0/go.mod h1:USTtm7OAlCwOlDlwGVgEGzKw4iizPcAFuZERQ+RWvtE= github.com/libp2p/go-libp2p-asn-util v0.4.1 h1:xqL7++IKD9TBFMgnLPZR6/6iYhawHKHl950SO9L6n94= github.com/libp2p/go-libp2p-asn-util v0.4.1/go.mod h1:d/NI6XZ9qxw67b4e+NgpQexCIiFYJjErASrYW4PFDN8= +github.com/libp2p/go-libp2p-kad-dht v0.43.0 h1:PTa4Qea87dAd+ecAIPIrRIHByFsErjKFkFuYO0rgENU= +github.com/libp2p/go-libp2p-kad-dht v0.43.0/go.mod h1:H5knPH7Fc8Qp1va9h5C7Dp09MeVB5V30fnKTX847rPs= +github.com/libp2p/go-libp2p-kbucket v0.9.0 h1:9kTf74R8CHGIk3QK+gwEOnJ/t+JzuxqQSfAAASl1VhM= +github.com/libp2p/go-libp2p-kbucket v0.9.0/go.mod h1:lKhHVjRq1z/Cl/bFzB2vPzYY0KCdmON6HlBwEAanqjk= github.com/libp2p/go-libp2p-pubsub v0.19.0 h1:9eyitBeXjW09XyDQF+EYL6RGRJ50Df1G9aTjB3XOMQQ= github.com/libp2p/go-libp2p-pubsub v0.19.0/go.mod h1:BfhG/m4TM39nKlcW6myqsoUjsJhOPpSLBCo4OtHLweI= +github.com/libp2p/go-libp2p-record v0.3.1 h1:cly48Xi5GjNw5Wq+7gmjfBiG9HCzQVkiZOUZ8kUl+Fg= +github.com/libp2p/go-libp2p-record v0.3.1/go.mod h1:T8itUkLcWQLCYMqtX7Th6r7SexyUJpIyPgks757td/E= +github.com/libp2p/go-libp2p-routing-helpers v0.7.5 h1:HdwZj9NKovMx0vqq6YNPTh6aaNzey5zHD7HeLJtq6fI= +github.com/libp2p/go-libp2p-routing-helpers v0.7.5/go.mod h1:3YaxrwP0OBPDD7my3D0KxfR89FlcX/IEbxDEDfAmj98= github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA= github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg= github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0= @@ -130,8 +171,8 @@ github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2D github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y= github.com/pion/datachannel v1.5.10 h1:ly0Q26K1i6ZkGf42W7D4hQYR90pZwzFOjTq5AuCKk4o= github.com/pion/datachannel v1.5.10/go.mod h1:p/jJfC9arb29W7WrxyKbepTU20CFgyx5oLo8Rs4Py/M= -github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc= -github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo= +github.com/pion/dtls/v3 v3.1.4 h1:QhvtMflMfu9Kf0RcDC5BJBle4caPskByrKQR6uuYqpY= +github.com/pion/dtls/v3 v3.1.4/go.mod h1:cr/qotLISUw/9C1m83ZPNZtj9WnXkYLpfCptPqbkInc= github.com/pion/ice/v4 v4.0.10 h1:P59w1iauC/wPk9PdY8Vjl4fOFL5B+USq1+xbDcN6gT4= github.com/pion/ice/v4 v4.0.10/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw= github.com/pion/interceptor v0.1.40 h1:e0BjnPcGpr2CFQgKhrQisBU7V3GXK6wrfYrGYaU6Jq4= @@ -152,16 +193,19 @@ github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI= github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8= github.com/pion/srtp/v3 v3.0.6 h1:E2gyj1f5X10sB/qILUGIkL4C2CqK269Xq167PbGCc/4= github.com/pion/srtp/v3 v3.0.6/go.mod h1:BxvziG3v/armJHAaJ87euvkhHqWe9I7iiOy50K2QkhY= -github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw= -github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM= +github.com/pion/stun/v3 v3.1.5 h1:Y1FHlhaI6+4UoC5i/zQf4F7JvdZtB24/05oyy/GF1x8= +github.com/pion/stun/v3 v3.1.5/go.mod h1:zRUghXSQU32Lx5orJsz3uYMkIihweXb3mu5gIns02fs= github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0= github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo= -github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o= -github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM= +github.com/pion/transport/v4 v4.0.2 h1:ifYlPqNwsy6aKQ9y8yzxXlHae5431ZrH2avkD/Rn6Tk= +github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM= github.com/pion/turn/v4 v4.0.2 h1:ZqgQ3+MjP32ug30xAbD6Mn+/K4Sxi3SdNOTFf+7mpps= github.com/pion/turn/v4 v4.0.2/go.mod h1:pMMKP/ieNAG/fN5cZiN4SDuyKsXtNTr0ccN7IToA1zs= github.com/pion/webrtc/v4 v4.1.2 h1:mpuUo/EJ1zMNKGE79fAdYNFZBX790KE7kQQpLMjjR54= github.com/pion/webrtc/v4 v4.1.2/go.mod h1:xsCXiNAmMEjIdFxAYU0MbB3RwRieJsegSB2JZsGN+8U= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/polydawn/refmt v0.90.0 h1:58BfEsP+G4uIRD9ApJTFsag+Mw+QQlZuH9uI/lPmjfY= +github.com/polydawn/refmt v0.90.0/go.mod h1:XAlDMOunevTYDsZtOKQd8itHXFMsX/QtDkPHaj6ZLxk= github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= @@ -180,14 +224,32 @@ github.com/quic-go/webtransport-go v0.13.0 h1:RJLrTUHlTj8jJaQlQJUy0z0Mf7u1fVM0I6 github.com/quic-go/webtransport-go v0.13.0/go.mod h1:K83X9YHbAqgSLO6ikS6BXCMdWOvqh9JTHALulvb2JVk= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY= +github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec= +github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= +github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= +github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 h1:EKhdznlJHPMoKr0XTrX+IlJs1LH3lyx2nfr1dOlZ79k= +github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1/go.mod h1:8UvriyWtv5Q5EOgjHaSseUEdkQfvwFv1I/In/O2M9gc= github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= +go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= +go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= +go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= +go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4= go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE= go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg= @@ -206,6 +268,7 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200602180216-279210d13fed/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= @@ -213,14 +276,18 @@ golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4 h1:lfvjMWyv5q5oJgIhGfBDf7Szvu8POtgSpMy2XbXlEFs= golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210423184538-5f58ad60dda6/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= @@ -246,14 +313,22 @@ golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640= golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg= lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo= modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= diff --git a/internal/p2p/bootstrap.go b/internal/p2p/bootstrap.go new file mode 100644 index 0000000..766a243 --- /dev/null +++ b/internal/p2p/bootstrap.go @@ -0,0 +1,185 @@ +package p2p + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sync" + "time" + + "github.com/libp2p/go-libp2p/core/peer" + ma "github.com/multiformats/go-multiaddr" + madns "github.com/multiformats/go-multiaddr-dns" +) + +// DefaultBootstrap is where a fresh node finds its first peers. libp2p reads +// the TXT records of _dnsaddr., each of the form +// +// dnsaddr=/ip4/203.0.113.5/tcp/4001/p2p/12D3KooW... +// +// so the list of bootstrap nodes can change without a new release. +const DefaultBootstrap = "/dnsaddr/allmende.stinnesbeck.com" + +const resolveTimeout = 10 * time.Second + +// bootstrapper turns the configured bootstrap addresses into peers. An entry is +// either a full /p2p/ address or a /dnsaddr/ name; names are resolved every +// time (so new servers are picked up), and the last good answer is kept in case +// DNS is briefly unreachable. +type bootstrapper struct { + entries []ma.Multiaddr + resolver *madns.Resolver + self peer.ID + log *slog.Logger + + mu sync.Mutex + cache map[string][]peer.AddrInfo // last good resolution per entry + failed map[string]bool // entries that failed last time, so it is said once +} + +func newBootstrapper(addrs []string, r *madns.Resolver, self peer.ID, log *slog.Logger) (*bootstrapper, error) { + if r == nil { + r = madns.DefaultResolver + } + b := &bootstrapper{ + resolver: r, self: self, log: log, + cache: map[string][]peer.AddrInfo{}, failed: map[string]bool{}, + } + for _, a := range addrs { + m, err := ma.NewMultiaddr(a) + if err != nil { + return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w", a, err) + } + if !isDNSAddr(m) { + if _, err := peer.AddrInfoFromP2pAddr(m); err != nil { + return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w (want /p2p/ or /dnsaddr/)", a, err) + } + } + b.entries = append(b.entries, m) + } + return b, nil +} + +func isDNSAddr(m ma.Multiaddr) bool { + _, err := m.ValueForProtocol(ma.P_DNSADDR) + return err == nil +} + +// empty reports whether nothing was configured. +func (b *bootstrapper) empty() bool { return len(b.entries) == 0 } + +// peers returns the current bootstrap peers, without this node itself. +func (b *bootstrapper) peers(ctx context.Context) []peer.AddrInfo { + var out []peer.AddrInfo + for _, e := range b.entries { + key := e.String() + var got []peer.AddrInfo + if isDNSAddr(e) { + got = b.resolve(ctx, key, e) + } else if ai, err := peer.AddrInfoFromP2pAddr(e); err == nil { + got = []peer.AddrInfo{*ai} + } + out = mergePeers(out, got) + } + kept := out[:0] + for _, ai := range out { + if ai.ID != b.self { + kept = append(kept, ai) + } + } + return kept +} + +func (b *bootstrapper) resolve(ctx context.Context, key string, e ma.Multiaddr) []peer.AddrInfo { + ctx, cancel := context.WithTimeout(ctx, resolveTimeout) + defer cancel() + + // The resolver can keep going for seconds after its context is cancelled + // (DNS that never answers), and the node must not wait for it to stop. + type answer struct { + addrs []ma.Multiaddr + err error + } + done := make(chan answer, 1) + go func() { + a, err := b.resolver.Resolve(ctx, e) + done <- answer{a, err} + }() + var resolved []ma.Multiaddr + var err error + select { + case a := <-done: + resolved, err = a.addrs, a.err + case <-ctx.Done(): + err = ctx.Err() + } + if ctx.Err() != nil && errors.Is(err, context.Canceled) { + b.mu.Lock() + defer b.mu.Unlock() + return b.cache[key] // stopping, not a DNS failure: say nothing + } + var got []peer.AddrInfo + for _, r := range resolved { + if ai, perr := peer.AddrInfoFromP2pAddr(r); perr == nil { + got = mergePeers(got, []peer.AddrInfo{*ai}) + } + } + if err == nil && len(got) == 0 { + err = fmt.Errorf("no peers in the records of %s", key) + } + + b.mu.Lock() + defer b.mu.Unlock() + if err != nil { + if !b.failed[key] { // say it once, not at every redial + b.log.Warn("could not resolve bootstrap name", "name", key, "err", err, "using", len(b.cache[key])) + } + b.failed[key] = true + return b.cache[key] + } + if b.failed[key] { + b.log.Info("bootstrap name resolves again", "name", key, "peers", len(got)) + } + b.failed[key] = false + b.cache[key] = got + return got +} + +// mergePeers adds more to into, joining the addresses of a peer seen twice. +func mergePeers(into, more []peer.AddrInfo) []peer.AddrInfo { + for _, m := range more { + found := false + for i := range into { + if into[i].ID == m.ID { + into[i].Addrs = append(into[i].Addrs, m.Addrs...) + found = true + break + } + } + if !found { + into = append(into, m) + } + } + return into +} + +// relayCandidates feeds AutoRelay: bootstrap nodes run with --public, so they +// are the relays a node behind a NAT can use to be reached. +func (b *bootstrapper) relayCandidates(ctx context.Context, num int) <-chan peer.AddrInfo { + ch := make(chan peer.AddrInfo, num) + go func() { + defer close(ch) + for i, ai := range b.peers(ctx) { + if i >= num { + return + } + select { + case ch <- ai: + case <-ctx.Done(): + return + } + } + }() + return ch +} diff --git a/internal/p2p/bootstrap_test.go b/internal/p2p/bootstrap_test.go new file mode 100644 index 0000000..a33a494 --- /dev/null +++ b/internal/p2p/bootstrap_test.go @@ -0,0 +1,309 @@ +package p2p + +import ( + "context" + "crypto/rand" + "errors" + "log/slog" + "net" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/libp2p/go-libp2p/core/crypto" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + madns "github.com/multiformats/go-multiaddr-dns" +) + +// fakeDNS answers TXT lookups from a table the test can change. +type fakeDNS struct { + mu sync.Mutex + txt map[string][]string + err error +} + +func (f *fakeDNS) set(name string, records ...string) { + f.mu.Lock() + defer f.mu.Unlock() + if f.txt == nil { + f.txt = map[string][]string{} + } + f.txt[name] = records +} + +func (f *fakeDNS) fail(err error) { + f.mu.Lock() + defer f.mu.Unlock() + f.err = err +} + +func (f *fakeDNS) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) { + return nil, errors.New("no addresses in this fake") +} + +func (f *fakeDNS) LookupTXT(_ context.Context, name string) ([]string, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.err != nil { + return nil, f.err + } + return f.txt[name], nil +} + +func resolverFor(t *testing.T, f *fakeDNS) *madns.Resolver { + t.Helper() + r, err := madns.NewResolver(madns.WithDefaultResolver(f)) + if err != nil { + t.Fatal(err) + } + return r +} + +func connected(a *tnode, b *tnode) bool { + return a.host.Network().Connectedness(b.ID()) == network.Connected +} + +func TestBootstrapNameIsResolvedAndDialled(t *testing.T) { + a := startNode(t, nil, "u1x") + dns := &fakeDNS{} + dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0], "dnsaddr=/ip4/192.0.2.1/tcp/1", "not a record") + b := startNodeWith(t, nil, func(c *Config) { + c.Bootstrap = []string{"/dnsaddr/boot.test"} + c.Resolver = resolverFor(t, dns) + }, "u1x") + eventually(t, "b reaches a through the name", func() bool { return connected(b, a) }) +} + +func TestBootstrapNameKeepsTheLastAnswerWhenDNSFails(t *testing.T) { + a := startNode(t, nil, "u1x") + dns := &fakeDNS{} + dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0]) + b := startNodeWith(t, nil, func(c *Config) { + c.Bootstrap = []string{"/dnsaddr/boot.test"} + c.Resolver = resolverFor(t, dns) + }, "u1x") + eventually(t, "first connection", func() bool { return connected(b, a) }) + + dns.fail(errors.New("servfail")) + b.host.Network().ClosePeer(a.ID()) + eventually(t, "b dials again from its remembered answer", func() bool { return connected(b, a) }) +} + +// stuckDNS never answers and ignores cancellation, like a resolver whose +// server drops packets. +type stuckDNS struct{ release chan struct{} } + +func (s stuckDNS) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) { + <-s.release + return nil, errors.New("released") +} + +func (s stuckDNS) LookupTXT(context.Context, string) ([]string, error) { + <-s.release + return nil, errors.New("released") +} + +func TestStoppingDoesNotWaitForAStuckResolver(t *testing.T) { + dns := stuckDNS{release: make(chan struct{})} + defer close(dns.release) + r, err := madns.NewResolver(madns.WithDefaultResolver(dns)) + if err != nil { + t.Fatal(err) + } + var logged strings.Builder + log := slog.New(slog.NewTextHandler(&logged, nil)) + b, err := newBootstrapper([]string{"/dnsaddr/boot.test"}, r, "", log) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + b.peers(ctx) + close(done) + }() + time.Sleep(50 * time.Millisecond) + cancel() // the node is stopping + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("stopping waited for a resolver that never answers") + } + if logged.Len() != 0 { + t.Errorf("stopping is not a DNS failure, but it was logged: %s", logged.String()) + } +} + +func TestBootstrapEntriesAreCheckedUpFront(t *testing.T) { + id := "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo" + for addr, ok := range map[string]bool{ + "/dnsaddr/allmende.example": true, + "/ip4/203.0.113.5/tcp/4001/p2p/" + id: true, + "/dns4/node.example/tcp/4001/p2p/" + id: true, + "/ip4/203.0.113.5/tcp/4001": false, // no peer ID to verify + "allmende.example": false, + "/dnsaddr/": false, + "": false, + } { + _, err := newBootstrapper([]string{addr}, nil, "", testLogger()) + if (err == nil) != ok { + t.Errorf("%q: error = %v, want ok = %v", addr, err, ok) + } + } +} + +func TestBootstrapNeverDialsItself(t *testing.T) { + a := startNode(t, nil) + dns := &fakeDNS{} + dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0]) + b, err := newBootstrapper([]string{"/dnsaddr/boot.test", a.Addrs()[0]}, resolverFor(t, dns), a.ID(), testLogger()) + if err != nil { + t.Fatal(err) + } + if got := b.peers(context.Background()); len(got) != 0 { + t.Fatalf("a bootstrap node must not dial itself: %v", got) + } + other, _ := newBootstrapper([]string{"/dnsaddr/boot.test"}, resolverFor(t, dns), peer.ID("someone else"), testLogger()) + if got := other.peers(context.Background()); len(got) != 1 || got[0].ID != a.ID() { + t.Fatalf("got %v", got) + } +} + +func TestPeersFromEarlierRunsAreRedialled(t *testing.T) { + a := startNode(t, nil, "u1x") + path := filepath.Join(t.TempDir(), "peers.json") + ai := peer.AddrInfo{ID: a.ID(), Addrs: a.host.Addrs()} + err := writePeerCache(path, []cachedPeer{{ID: a.ID().String(), Addrs: directAddrs(ai.Addrs), Seen: time.Now().Unix()}}) + if err != nil { + t.Fatal(err) + } + // No bootstrap, no mDNS, no DHT: only the remembered address can lead to a. + b := startNodeWith(t, nil, func(c *Config) { c.PeerCache = path }, "u1x") + eventually(t, "b finds a from its cache", func() bool { return connected(b, a) }) +} + +func TestPeersAreRememberedOnTheWayOut(t *testing.T) { + a := startNode(t, nil, "u1x") + path := filepath.Join(t.TempDir(), "peers.json") + b := startNodeWith(t, nil, func(c *Config) { c.PeerCache = path }, "u1x") + connect(t, b, a) + eventually(t, "connected", func() bool { return connected(b, a) }) + b.Close() // saves once more as it stops + + got := readPeerCache(path, time.Now()) + if len(got) != 1 || got[0].ID != a.ID().String() || len(got[0].Addrs) == 0 { + t.Fatalf("cache = %+v, want a's address", got) + } + for _, addr := range got[0].Addrs { + if strings.Contains(addr, "p2p-circuit") { + t.Errorf("a relayed address was remembered: %s", addr) + } + } +} + +func TestPeerCacheIgnoresStaleAndBrokenEntries(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "peers.json") + id := "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo" + now := time.Now() + err := writePeerCache(path, []cachedPeer{ + {ID: id, Addrs: []string{"/ip4/127.0.0.1/tcp/1"}, Seen: now.Unix()}, + {ID: id + "x", Addrs: []string{"/ip4/127.0.0.1/tcp/2"}, Seen: now.Unix()}, // not a peer ID + {ID: id, Addrs: nil, Seen: now.Unix()}, // nothing to dial + {ID: id, Addrs: []string{"/ip4/127.0.0.1/tcp/3"}, Seen: now.Add(-31 * 24 * time.Hour).Unix()}, // too old + }) + if err != nil { + t.Fatal(err) + } + if got := readPeerCache(path, now); len(got) != 1 || got[0].Addrs[0] != "/ip4/127.0.0.1/tcp/1" { + t.Fatalf("got %+v", got) + } + + for name, content := range map[string]string{"garbage": "{not json", "empty": ""} { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + if got := readPeerCache(p, now); got != nil { + t.Errorf("%s: want an empty cache, got %+v", name, got) + } + } + if got := readPeerCache(filepath.Join(dir, "missing"), now); got != nil { + t.Errorf("missing file: %+v", got) + } +} + +func TestPeerCacheKeepsTheNewestEntries(t *testing.T) { + path := filepath.Join(t.TempDir(), "peers.json") + var many []cachedPeer + for i := 0; i < maxCachedPeers+20; i++ { + _, pub, err := crypto.GenerateEd25519Key(rand.Reader) + if err != nil { + t.Fatal(err) + } + id, err := peer.IDFromPublicKey(pub) + if err != nil { + t.Fatal(err) + } + many = append(many, cachedPeer{ID: id.String(), Addrs: []string{"/ip4/127.0.0.1/tcp/1"}, Seen: int64(1000 + i)}) + } + if err := writePeerCache(path, many); err != nil { + t.Fatal(err) + } + got := readPeerCache(path, time.Unix(2000, 0)) + if len(got) != maxCachedPeers || got[0].Seen != int64(1000+maxCachedPeers+19) { + t.Fatalf("kept %d, newest first = %d", len(got), got[0].Seen) + } +} + +// Two nodes that only know a bootstrap node must find each other through the +// DHT, not by being introduced. +func TestDHTFindsPeersOfTheSameRegion(t *testing.T) { + r := startNodeWith(t, nil, func(c *Config) { + c.Public, c.DHT, c.DiscoverInterval = true, true, 200*time.Millisecond + }, "u1x") + seed := func(c *Config) { + c.Bootstrap = []string{r.Addrs()[0]} + c.DHT, c.DiscoverInterval = true, 200*time.Millisecond + } + a := startNodeWith(t, nil, seed, "u1x") + b := startNodeWith(t, nil, seed, "u1x") + other := startNodeWith(t, nil, seed, "u1y") // a different region: not for a or b + + eventually(t, "a and b are connected directly", func() bool { return connected(a, b) && connected(b, a) }) + if connected(a, other) || connected(b, other) { + t.Error("a node of another region was dialled; discovery is per region") + } +} + +// A node that cannot be reached directly takes a reservation on a bootstrap +// node, so that others can still get to it through that relay. (libp2p only +// advertises relay addresses built on public IPs, so on loopback the test +// dials the relayed path itself; that works only if the reservation exists.) +func TestNodeBehindANATIsReachableThroughTheBootstrapNode(t *testing.T) { + r := startNodeWith(t, nil, func(c *Config) { c.Public = true }, "u1x") + a := startNodeWith(t, nil, func(c *Config) { + c.Bootstrap = []string{r.Addrs()[0]} + c.ForcePrivate = true + c.RelayBootDelay = 100 * time.Millisecond + }, "u1x") + b := startNode(t, nil, "u1x") // knows nothing of a + connect(t, b, r) + + via := r.Addrs()[0] + "/p2p-circuit/p2p/" + a.ID().String() + ai, err := peer.AddrInfoFromString(via) + if err != nil { + t.Fatal(err) + } + eventually(t, "b reaches a through r", func() bool { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + ctx = network.WithAllowLimitedConn(ctx, "test") + return b.host.Connect(ctx, *ai) == nil && b.host.Network().Connectedness(a.ID()) != network.NotConnected + }) +} diff --git a/internal/p2p/discovery.go b/internal/p2p/discovery.go new file mode 100644 index 0000000..773b964 --- /dev/null +++ b/internal/p2p/discovery.go @@ -0,0 +1,163 @@ +package p2p + +import ( + "context" + "errors" + "sync" + "time" + + dht "github.com/libp2p/go-libp2p-kad-dht" + "github.com/libp2p/go-libp2p/core/discovery" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing" +) + +const ( + // dhtProtocolPrefix keeps this network's DHT apart from every other one + // (the IPFS DHT included): the protocol is /allmende/kad/1.0.0. + dhtProtocolPrefix = "/allmende" + // regionNamespace is what nodes advertise and look up, one per region. + regionNamespace = "allmende/region/" + + defaultDiscoverInterval = time.Minute + // enoughRegionPeers: with this many peers on a region's topic there is no + // need to look for more. + enoughRegionPeers = 8 + findLimit = 20 +) + +// startDiscovery joins the DHT and, for every region this node follows, +// advertises the node and looks for others. Bootstrap nodes only seed the +// routing table; once a node knows a few peers it no longer depends on them. +func (n *Node) startDiscovery() error { + mode := dht.ModeAuto // a server once AutoNAT finds this node publicly reachable + if n.cfg.Public { + mode = dht.ModeServer + } + d, err := dht.New(n.host, dht.ProtocolPrefix(dhtProtocolPrefix), dht.Mode(mode)) + if err != nil { + return err + } + n.dht = d + rd := drouting.NewRoutingDiscovery(d) + for _, r := range n.cfg.Regions { + ns := regionNamespace + r + n.wg.Add(2) + go n.advertise(rd, ns) + go n.findPeers(rd, r, ns) + } + return nil +} + +func (n *Node) discoverInterval() time.Duration { + if n.cfg.DiscoverInterval > 0 { + return n.cfg.DiscoverInterval + } + return defaultDiscoverInterval +} + +// sleep waits for d or until the node stops; false means it stopped. +func (n *Node) sleep(d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-n.ctx.Done(): + return false + case <-t.C: + return true + } +} + +// advertise keeps this node findable under the region's name. Until the +// routing table has a peer in it there is nowhere to publish, so it retries. +func (n *Node) advertise(rd *drouting.RoutingDiscovery, ns string) { + defer n.wg.Done() + back := n.backoff() + for { + wait := back.next() + ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second) + ttl, err := rd.Advertise(ctx, ns) + cancel() + switch { + case n.ctx.Err() != nil: + return + case err != nil: + n.log.Debug("advertise", "ns", ns, "err", err) // retried soon, then less often + back.bump() + case ttl > 0: + wait = ttl * 3 / 4 // refresh before the record lapses + back.reset() + } + if !n.sleep(wait) { + return + } + } +} + +// backoff paces retries: quick at first, because a fresh node needs its first +// peers now, then settling on the regular interval. +type backoff struct{ cur, max time.Duration } + +func (n *Node) backoff() *backoff { + max := n.discoverInterval() + first := 2 * time.Second + if first > max { + first = max + } + return &backoff{cur: first, max: max} +} + +func (b *backoff) next() time.Duration { return b.cur } + +func (b *backoff) reset() { b.cur = b.max } + +// bump doubles the wait up to the limit. +func (b *backoff) bump() { + if b.cur *= 2; b.cur > b.max { + b.cur = b.max + } +} + +// findPeers connects to other nodes of the region that the DHT knows. +func (n *Node) findPeers(rd *drouting.RoutingDiscovery, region, ns string) { + defer n.wg.Done() + back := n.backoff() + for { + if !n.sleep(back.next()) { + return + } + back.bump() + if len(n.RegionPeers(region)) >= enoughRegionPeers { + continue + } + ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second) + found, err := rd.FindPeers(ctx, ns, discovery.Limit(findLimit)) + if err != nil { + cancel() + if n.ctx.Err() == nil { + n.log.Debug("find peers", "ns", ns, "err", err) + } + continue + } + var wg sync.WaitGroup + for ai := range found { + if ai.ID == n.host.ID() || len(ai.Addrs) == 0 || n.host.Network().Connectedness(ai.ID) == network.Connected { + continue + } + wg.Add(1) + go func(ai peer.AddrInfo) { + defer wg.Done() + cctx, ccancel := context.WithTimeout(ctx, 10*time.Second) + defer ccancel() + if err := n.host.Connect(cctx, ai); err != nil && !errors.Is(err, context.Canceled) { + n.log.Debug("discovered peer unreachable", "peer", ai.ID, "err", err) + } else if err == nil { + n.log.Debug("found a peer through the DHT", "peer", ai.ID, "region", region) + } + }(ai) + } + wg.Wait() + cancel() + } +} diff --git a/internal/p2p/node.go b/internal/p2p/node.go index c3c340e..a0791e0 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -21,12 +21,15 @@ import ( "time" "github.com/libp2p/go-libp2p" + dht "github.com/libp2p/go-libp2p-kad-dht" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/p2p/discovery/mdns" + "github.com/libp2p/go-libp2p/p2p/host/autorelay" + madns "github.com/multiformats/go-multiaddr-dns" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/listing" @@ -52,9 +55,27 @@ type Config struct { Store *store.Store ListenAddrs []string // default: TCP and QUIC on all interfaces, random ports - Bootstrap []string // multiaddrs ending in /p2p/ - Regions []string // geohash precision-3 cells to replicate - MDNS bool // discover peers on the local network + // Bootstrap lists where to find the first peers: multiaddrs ending in + // /p2p/, or /dnsaddr/ (see DefaultBootstrap). + Bootstrap []string + Regions []string // geohash precision-3 cells to replicate + MDNS bool // discover peers on the local network + + // DHT turns on peer discovery through a Kademlia DHT, per region. + DHT bool + // Public says this node is reachable from the internet (it has a public + // address or a forwarded port). It then serves the DHT and acts as a relay + // for nodes behind a NAT, which is what a bootstrap node does. + Public bool + // PeerCache is a file in which the node remembers its peers between runs; + // empty turns that off. + PeerCache string + // Resolver resolves /dnsaddr/ names; the default asks DNS. + Resolver *madns.Resolver + + DiscoverInterval time.Duration // how often to look for region peers (default 1 min) + RelayBootDelay time.Duration // wait before taking a relay when behind a NAT (default 10s) + ForcePrivate bool // treat this node as unreachable; for tests Difficulty int // required proof-of-work bits // MessageDifficulty is the proof-of-work bits required of message @@ -83,7 +104,8 @@ type Node struct { topics map[string]*pubsub.Topic msgTopics map[string]*pubsub.Topic subscribed []string - bootstrap []peer.AddrInfo + boot *bootstrapper + dht *dht.IpfsDHT syncing map[peer.ID]bool revTopic *pubsub.Topic } @@ -107,20 +129,47 @@ func New(ctx context.Context, cfg Config) (*Node, error) { if cfg.RedialInterval <= 0 { cfg.RedialInterval = 20 * time.Second } - var bootstrap []peer.AddrInfo - for _, addr := range cfg.Bootstrap { - ai, err := peer.AddrInfoFromString(addr) - if err != nil { - return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w", addr, err) - } - bootstrap = append(bootstrap, *ai) + if cfg.RelayBootDelay <= 0 { + cfg.RelayBootDelay = 10 * time.Second + } + log := cfg.Logger + if log == nil { + log = slog.Default() } priv, err := crypto.UnmarshalEd25519PrivateKey(cfg.Device.Key.PrivateKey()) if err != nil { return nil, err } - h, err := libp2p.New(libp2p.Identity(priv), libp2p.ListenAddrStrings(cfg.ListenAddrs...)) + self, err := peer.IDFromPrivateKey(priv) + if err != nil { + return nil, err + } + boot, err := newBootstrapper(cfg.Bootstrap, cfg.Resolver, self, log) + if err != nil { + return nil, err + } + + // Reaching nodes behind home routers: map a port on the router when it + // allows it, punch holes with the help of a third node, and otherwise take + // a reservation on a relay (the bootstrap nodes) so others can find a way in. + opts := []libp2p.Option{ + libp2p.Identity(priv), + libp2p.ListenAddrStrings(cfg.ListenAddrs...), + libp2p.NATPortMap(), + libp2p.EnableHolePunching(), + libp2p.EnableAutoRelayWithPeerSource(boot.relayCandidates, + autorelay.WithBootDelay(cfg.RelayBootDelay), + autorelay.WithMinCandidates(1), + autorelay.WithNumRelays(2)), + } + if cfg.Public { + opts = append(opts, libp2p.ForceReachabilityPublic(), libp2p.EnableRelayService(), libp2p.EnableNATService()) + } + if cfg.ForcePrivate { + opts = append(opts, libp2p.ForceReachabilityPrivate()) + } + h, err := libp2p.New(opts...) if err != nil { return nil, err } @@ -130,20 +179,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) { cfg: cfg, host: h, clock: cfg.Clock, - log: cfg.Logger, + log: log, ctx: nctx, cancel: cancel, topics: map[string]*pubsub.Topic{}, msgTopics: map[string]*pubsub.Topic{}, syncing: map[peer.ID]bool{}, - bootstrap: bootstrap, + boot: boot, } if n.clock == nil { n.clock = time.Now } - if n.log == nil { - n.log = slog.Default() - } // Flood-publish: the origin sends to every subscribed peer instead of only // its mesh. Regional topics are small, and without it a listing published @@ -171,7 +217,12 @@ func New(ctx context.Context, cfg Config) (*Node, error) { ConnectedF: func(_ network.Network, c network.Conn) { n.syncSoon(c.RemotePeer()) }, }) - n.dialBootstrap() + if cfg.DHT { + if err := n.startDiscovery(); err != nil { + n.Close() + return nil, err + } + } if cfg.MDNS { n.mdns = mdns.NewMdnsService(h, mdnsService, &mdnsNotifee{n: n}) if err := n.mdns.Start(); err != nil { @@ -180,9 +231,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) { } } - n.wg.Add(2) + // Finding the first peers can take a while (DNS, unreachable servers), so it + // does not hold up starting the node. + n.wg.Add(4) + go func() { + defer n.wg.Done() + n.dialBootstrap() + n.dialCached() + }() go n.maintain() go n.redial() + go n.remember() return n, nil } @@ -272,6 +331,9 @@ func (n *Node) Close() error { n.mdns.Close() } n.wg.Wait() + if n.dht != nil { + n.dht.Close() + } return n.host.Close() } @@ -540,15 +602,24 @@ func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) { // dialBootstrap connects to every configured bootstrap peer we are not // already connected to. func (n *Node) dialBootstrap() { - for _, ai := range n.bootstrap { + var wg sync.WaitGroup + for _, ai := range n.boot.peers(n.ctx) { if n.host.Network().Connectedness(ai.ID) == network.Connected { continue } - ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second) - if err := n.host.Connect(ctx, ai); err != nil { - n.log.Warn("bootstrap peer unreachable", "peer", ai.ID, "err", err) - } - cancel() + wg.Add(1) + go func(ai peer.AddrInfo) { + defer wg.Done() + ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second) + defer cancel() + if err := n.host.Connect(ctx, ai); err != nil && n.ctx.Err() == nil { + n.log.Warn("bootstrap peer unreachable", "peer", ai.ID, "err", err) + } + }(ai) + } + wg.Wait() + if n.dht != nil { + n.dht.Bootstrap(n.ctx) // fill the routing table from whoever answered } } @@ -556,7 +627,7 @@ func (n *Node) dialBootstrap() { // network outages on either side. func (n *Node) redial() { defer n.wg.Done() - if len(n.bootstrap) == 0 { + if n.boot.empty() { return } t := time.NewTicker(n.cfg.RedialInterval) diff --git a/internal/p2p/peercache.go b/internal/p2p/peercache.go new file mode 100644 index 0000000..1a343e4 --- /dev/null +++ b/internal/p2p/peercache.go @@ -0,0 +1,178 @@ +package p2p + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + ma "github.com/multiformats/go-multiaddr" +) + +// The peer cache remembers who this node met, so after the first successful +// start it can find the network again without any bootstrap node. +const ( + maxCachedPeers = 100 + cachedPeerTTL = 30 * 24 * time.Hour + dialCachedMax = 10 + rememberEvery = 5 * time.Minute +) + +type cachedPeer struct { + ID string `json:"id"` + Addrs []string `json:"addrs"` + Seen int64 `json:"seen"` // unix seconds +} + +type peerFile struct { + Peers []cachedPeer `json:"peers"` +} + +// readPeerCache returns the usable entries, newest first. A missing, damaged or +// stale file is simply an empty cache: it is a convenience, never a requirement. +func readPeerCache(path string, now time.Time) []cachedPeer { + data, err := os.ReadFile(path) + if err != nil { + return nil + } + var f peerFile + if json.Unmarshal(data, &f) != nil { + return nil + } + var out []cachedPeer + for _, p := range f.Peers { + if _, err := peer.Decode(p.ID); err != nil || len(p.Addrs) == 0 { + continue + } + if now.Sub(time.Unix(p.Seen, 0)) > cachedPeerTTL { + continue + } + out = append(out, p) + } + sort.Slice(out, func(i, j int) bool { return out[i].Seen > out[j].Seen }) + return out +} + +func writePeerCache(path string, peers []cachedPeer) error { + sort.Slice(peers, func(i, j int) bool { return peers[i].Seen > peers[j].Seen }) + if len(peers) > maxCachedPeers { + peers = peers[:maxCachedPeers] + } + data, err := json.MarshalIndent(peerFile{Peers: peers}, "", " ") + if err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), ".peers-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} + +// directAddrs keeps the addresses worth remembering: not relayed, which only +// work while that relay does, and not unspecified. +func directAddrs(addrs []ma.Multiaddr) []string { + var out []string + for _, a := range addrs { + if strings.Contains(a.String(), "/p2p-circuit") { + continue + } + out = append(out, a.String()) + } + return out +} + +// rememberPeers records the currently connected peers in the cache file. +func (n *Node) rememberPeers() { + if n.cfg.PeerCache == "" { + return + } + now := n.clock() + byID := map[string]cachedPeer{} + for _, p := range readPeerCache(n.cfg.PeerCache, now) { + byID[p.ID] = p + } + for _, id := range n.host.Network().Peers() { + addrs := directAddrs(n.host.Peerstore().Addrs(id)) + if len(addrs) == 0 { + continue + } + byID[id.String()] = cachedPeer{ID: id.String(), Addrs: addrs, Seen: now.Unix()} + } + list := make([]cachedPeer, 0, len(byID)) + for _, p := range byID { + list = append(list, p) + } + if err := writePeerCache(n.cfg.PeerCache, list); err != nil { + n.log.Warn("could not save known peers", "err", err) + } +} + +// remember saves the known peers now and then, and once more on the way out. +func (n *Node) remember() { + defer n.wg.Done() + if n.cfg.PeerCache == "" { + return + } + t := time.NewTicker(rememberEvery) + defer t.Stop() + for { + select { + case <-n.ctx.Done(): + n.rememberPeers() + return + case <-t.C: + n.rememberPeers() + } + } +} + +// dialCached reconnects to the peers met on earlier runs. +func (n *Node) dialCached() { + if n.cfg.PeerCache == "" { + return + } + var wg sync.WaitGroup + dialed := 0 + for _, p := range readPeerCache(n.cfg.PeerCache, n.clock()) { + if dialed == dialCachedMax { + break + } + id, err := peer.Decode(p.ID) + if err != nil || id == n.host.ID() || n.host.Network().Connectedness(id) == network.Connected { + continue + } + ai := peer.AddrInfo{ID: id} + for _, a := range p.Addrs { + if m, err := ma.NewMultiaddr(a); err == nil { + ai.Addrs = append(ai.Addrs, m) + } + } + dialed++ + wg.Add(1) + go func() { + defer wg.Done() + ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second) + defer cancel() + if err := n.host.Connect(ctx, ai); err != nil && !errors.Is(err, context.Canceled) { + n.log.Debug("remembered peer unreachable", "peer", ai.ID, "err", err) + } + }() + } + wg.Wait() +} diff --git a/nix/module.nix b/nix/module.nix index 92e7313..a910dcb 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -23,7 +23,11 @@ let cfg.httpAddress "--listen" "/ip4/0.0.0.0/tcp/${toString cfg.p2pPort}" + "--listen" + "/ip4/0.0.0.0/udp/${toString cfg.p2pPort}/quic-v1" ] + ++ lib.optional cfg.public "--public" + ++ lib.optional (!cfg.defaultBootstrap) "--no-default-bootstrap" ++ lib.concatMap (r: [ "--region" r @@ -47,10 +51,12 @@ in regions = lib.mkOption { type = lib.types.listOf lib.types.str; + default = [ ]; example = [ "u1j" ]; description = '' Regions to replicate: 3-character geohashes, each about 150 km wide. - `u1j` is Bonn, `u1h` Cologne, `u1x` Hamburg. + `u1j` is Bonn, `u1h` Cologne, `u1x` Hamburg. May be empty only for a + bootstrap node ({option}`public`). ''; }; @@ -58,7 +64,23 @@ in type = lib.types.listOf lib.types.str; default = [ ]; example = [ "/ip4/203.0.113.5/tcp/4001/p2p/12D3KooW..." ]; - description = "Known peers to connect to, as multiaddrs ending in /p2p/."; + description = "Extra peers to connect to: /p2p/ multiaddrs or /dnsaddr/."; + }; + + defaultBootstrap = lib.mkOption { + type = lib.types.bool; + default = true; + description = "Also use the built-in bootstrap name (allmende.stinnesbeck.com)."; + }; + + public = lib.mkOption { + type = lib.types.bool; + default = false; + description = '' + This machine is reachable from the internet: serve the DHT and relay for + nodes behind a NAT. Turn it on for a bootstrap node, and publish the TXT + records the node prints (see `journalctl -u allmende`) in DNS. + ''; }; httpAddress = lib.mkOption { @@ -74,13 +96,13 @@ in p2pPort = lib.mkOption { type = lib.types.port; default = 4001; - description = "TCP port other nodes connect to."; + description = "Port other nodes connect to, over TCP and over UDP (QUIC)."; }; openFirewall = lib.mkOption { type = lib.types.bool; default = false; - description = "Open the peer-to-peer port ({option}`p2pPort`) in the firewall."; + description = "Open the peer-to-peer port ({option}`p2pPort`, TCP and UDP) in the firewall."; }; dataDir = lib.mkOption { @@ -100,8 +122,8 @@ in config = lib.mkIf cfg.enable { assertions = [ { - assertion = cfg.regions != [ ]; - message = "services.allmende.regions needs at least one region, for example [ \"u1j\" ]."; + assertion = cfg.regions != [ ] || cfg.public; + message = "services.allmende.regions needs at least one region, for example [ \"u1j\" ] (only a public bootstrap node may have none)."; } ]; @@ -154,6 +176,7 @@ in }; networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.p2pPort ]; + networking.firewall.allowedUDPPorts = lib.mkIf cfg.openFirewall [ cfg.p2pPort ]; # QUIC environment.systemPackages = [ admin ]; }; diff --git a/nix/package.nix b/nix/package.nix index 64e873f..0a9ef1f 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -24,7 +24,7 @@ buildGoModule { # Changes whenever go.mod or go.sum do: set it to lib.fakeHash, build, and # copy the hash from the error. - vendorHash = "sha256-vUBmsqyS+/qXo3UDYzZmZQYik7rMhOrX7csy56UJbLU="; + vendorHash = "sha256-cls1bwmv+BbBwGx5mfNcihENUuojR5Pog5tfVzBKPU8="; subPackages = [ "cmd/allmende" ]; env.CGO_ENABLED = "0"; diff --git a/nix/test.nix b/nix/test.nix index b593554..3bb34dd 100644 --- a/nix/test.nix +++ b/nix/test.nix @@ -46,8 +46,10 @@ pkgs.testers.runNixOSTest { machine.succeed("ss -ltn | grep -q '127.0.0.1:8080'") machine.fail("ss -ltn | grep -q '0.0.0.0:8080'") - with subtest("it survives a restart"): - machine.succeed("systemctl restart allmende") + with subtest("it stops promptly even though the VM has no DNS, and restarts"): + # The built-in bootstrap name cannot be resolved here; stopping must not wait for it. + machine.succeed("timeout 3 systemctl stop allmende") + machine.succeed("systemctl start allmende") machine.wait_for_open_port(8080) ''; } diff --git a/scripts/e2e.sh b/scripts/e2e.sh index 9e86f7f..d9638ed 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -25,8 +25,20 @@ wait_for() { # description, timeout, command... for _ in $(seq 1 $((t*10))); do if "$@" >/dev/null 2>&1; then return 0; fi; sleep 0.1; done bad "timed out: $what" } +# check OP WANT COMMAND...: runs COMMAND each time it is polled and compares its output. +# (Writing test "$(command)" = x inside wait_for would run the command only once.) +check() { + local op=$1 want=$2 got; shift 2 + got=$("$@" 2>/dev/null) || return 1 + case $op in + eq) [ "$got" = "$want" ] ;; + ge) [ "$got" -ge "$want" ] 2>/dev/null ;; + esac +} +peers() { curl -s http://127.0.0.1:$1/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["peers"])'; } DIFF=10 -COMMON="--region u1x --no-mdns --difficulty $DIFF" +# --no-default-bootstrap: these nodes must not look up the real bootstrap name in DNS. +COMMON="--region u1x --no-mdns --no-default-bootstrap --difficulty $DIFF" echo "== init" $BIN init --data $A > $W/init-a.txt || bad "init A" @@ -47,7 +59,7 @@ $BIN run --data $B $COMMON --http 127.0.0.1:18102 --listen /ip4/127.0.0.1/tcp/14 --bootstrap /ip4/127.0.0.1/tcp/14101/p2p/$PEER 2> $W/b.log & PIDS+=($!) wait_for "B http" 10 curl -sf http://127.0.0.1:18102/api/v1/status -wait_for "nodes connected" 15 test "$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["peers"])')" -ge 1 +wait_for "nodes connected" 15 check ge 1 peers 18101 ok "nodes connected" echo "== publish on A, read on B" @@ -58,7 +70,7 @@ RESP=$(curl -s -X POST -H "Authorization: Bearer $TOKEN" -d "$DRAFT" http://127. ID=$(echo "$RESP" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])') || bad "create: $RESP" ok "published listing $ID" count_b() { curl -s "http://127.0.0.1:18102/api/v1/listings?geohash=u1x" | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))'; } -wait_for "B receives the listing" 15 test "$(count_b)" = 1 +wait_for "B receives the listing" 15 check eq 1 count_b ok "node B has the listing via gossip" echo "== UI-style edit and renew on A (draft built by the UI's own code)" @@ -71,7 +83,8 @@ echo "$PUTR" | python3 -c 'import json,sys; l=json.load(sys.stdin); assert l["ti RENEWED=$(echo "$PUTR" | node $RENEW "" 30) || bad "renew draft" PUTR=$(curl -s -X PUT -H "Authorization: Bearer $TOKEN" -d "$RENEWED" http://127.0.0.1:18101/api/v1/listings/$ID) echo "$PUTR" | python3 -c 'import json,sys; l=json.load(sys.stdin); assert l["seq"]==3 and l["expires_at"]-l["created_at"]>29*86400, l' && ok "renew accepted: seq 3, fresh 30-day term" || bad "renew refused: $PUTR" -wait_for "B has the renewed version" 15 test "$(curl -s http://127.0.0.1:18102/api/v1/listings/$AUTHOR0/$ID | python3 -c 'import json,sys; print(json.load(sys.stdin)["seq"])')" = 3 +seq_on_b() { curl -s http://127.0.0.1:18102/api/v1/listings/$AUTHOR0/$ID | python3 -c 'import json,sys; print(json.load(sys.stdin)["seq"])'; } +wait_for "B has the renewed version" 15 check eq 3 seq_on_b ok "node B serves the renewed version" MOVED=$(echo "$PUTR" | node $RENEW "" 30 | python3 -c 'import json,sys; d=json.load(sys.stdin); d["geohash"]="u28xyz"; print(json.dumps(d))') curl -s -o /dev/null -w "%{http_code}" -X PUT -H "Authorization: Bearer $TOKEN" -d "$MOVED" http://127.0.0.1:18101/api/v1/listings/$ID | grep -q 400 && ok "moving a listing to another region is refused" || bad "region change was not refused" @@ -89,7 +102,7 @@ grep -q "Ist die Wohnung noch frei" "$W/a.log" && bad "the buyer's text was prin ok "the notice does not show what the buyer wrote" [ "$(grep -c 'msg="new conversation"' "$W/a.log")" = 1 ] || bad "the notice was repeated" inbox_a() { curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))'; } -wait_for "A receives the message" 20 test "$(inbox_a)" = 1 +wait_for "A receives the message" 20 check eq 1 inbox_a ok "owner's node A decrypted it (via gossip through B)" THREAD=$(curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox | python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["thread"])') curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox/$ID/$THREAD | grep -q "Ist die Wohnung noch frei" && ok "owner reads the buyer's text" @@ -131,6 +144,36 @@ dev_on_b() { curl -s "http://127.0.0.1:18102/api/v1/listings?geohash=u1x" | pyth import json,sys l=json.load(sys.stdin) print(l[0]["device"] if len(l)==1 else "none")'; } -wait_for "B switches to the new device's version" 60 test "$(dev_on_b)" = "$NEW_DEVICE" +wait_for "B switches to the new device's version" 60 check eq "$NEW_DEVICE" dev_on_b ok "node B now serves the listing re-signed by the new device (old device revoked network-wide)" + +echo "== bootstrap node: two nodes that only know it find each other" +C=$W/c; X=$W/x; Y=$W/y +for d in $C $X $Y; do $BIN init --data $d >/dev/null || bad "init $d"; done +$BIN run --data $C $COMMON --public --http 127.0.0.1:18103 --listen /ip4/127.0.0.1/tcp/14103 2> $W/c.log & +PIDS+=($!) +wait_for "bootstrap node http" 10 curl -sf http://127.0.0.1:18103/api/v1/status +PEER_C=$(curl -s http://127.0.0.1:18103/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["peer_id"])') +grep -q "no public address" $W/c.log && ok "--public on loopback says it has no public address to publish" || bad "no hint about the missing public address" +$BIN run --data $X $COMMON --http 127.0.0.1:18104 --listen /ip4/127.0.0.1/tcp/14104 \ + --bootstrap /ip4/127.0.0.1/tcp/14103/p2p/$PEER_C 2> $W/x.log & +XPID=$!; PIDS+=($XPID) +$BIN run --data $Y $COMMON --http 127.0.0.1:18105 --listen /ip4/127.0.0.1/tcp/14105 \ + --bootstrap /ip4/127.0.0.1/tcp/14103/p2p/$PEER_C 2> $W/y.log & +PIDS+=($!) +wait_for "X and Y connected to the bootstrap node" 20 check ge 2 peers 18103 +# Each of X and Y has two peers only if they found each other (C is the other one). +wait_for "X finds Y through the DHT" 60 check ge 2 peers 18104 +wait_for "Y finds X through the DHT" 20 check ge 2 peers 18105 +ok "X and Y found each other through the DHT, introduced by nobody" + +echo "== a node remembers its peers: restart X without any bootstrap" +kill $XPID; wait $XPID 2>/dev/null +[ -s $X/peers.json ] && grep -q "$PEER_C" $X/peers.json && ok "peers were saved on shutdown" || bad "peers.json missing or without the bootstrap node" +$BIN run --data $X $COMMON --http 127.0.0.1:18104 --listen /ip4/127.0.0.1/tcp/14104 2> $W/x2.log & +PIDS+=($!) +wait_for "X restarted" 10 curl -sf http://127.0.0.1:18104/api/v1/status +wait_for "X reconnects from its remembered peers" 30 check ge 1 peers 18104 +ok "X rejoined the network with no bootstrap configured" + echo "ALL E2E CHECKS PASSED"