Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
4906793
Bump go directive to 1.26 and upgrade dependencies
ShivamB25 Sep 22, 2026
d10f740
Modernize CI and add golangci-lint v2 config
ShivamB25 Sep 22, 2026
b9dcf0d
Fix query handler crashes and modernize the codebase
ShivamB25 Sep 22, 2026
671719b
Get starting nodes before starting traversals
ShivamB25 Sep 22, 2026
c940be7
Check errors in tests instead of excluding errcheck
ShivamB25 Sep 22, 2026
1135f58
Wait for bootstrap traversals to stop when cancelled
ShivamB25 Sep 22, 2026
73f0abc
Read bucket-refresh stats only after the traversal stops
ShivamB25 Sep 22, 2026
f00aff8
Copy traversal counters with atomic loads
ShivamB25 Sep 22, 2026
2d2e667
Unblock announce shutdown when Peers is unread
ShivamB25 Sep 22, 2026
1d25d21
Close the announce if the unread-Peers test fails early
ShivamB25 Sep 22, 2026
32e0213
Stop queries on Close and correct closest-node and BEP 44 checks
ShivamB25 Sep 22, 2026
a28a2e2
Correct target-wide node selection and callback shutdown lifetimes
ShivamB25 Sep 23, 2026
6bccb09
Isolate lifecycle tests from the shared send limiter
ShivamB25 Sep 23, 2026
651c25d
Strengthen nearest-node oracle and responder cleanup regressions
ShivamB25 Sep 23, 2026
987041f
Reject malformed DHT endpoints and propagate publication failures
ShivamB25 Sep 23, 2026
1be3da8
Validate mutable keys and include DNS in ping deadlines
ShivamB25 Sep 23, 2026
265bf4a
Deduplicate traversal endpoints and strengthen concurrency regressions
ShivamB25 Sep 23, 2026
fd77e0b
Cancel command DNS lookups and validate compact address marshaling
ShivamB25 Sep 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 32 additions & 11 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,41 @@ name: Go

on: [push, pull_request]

jobs:
permissions:
contents: read

build:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
# The minimum version declared in go.mod, and the latest release.
go-version: ['1.26', stable]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v7

- uses: actions/setup-go@v6
with:
go-version: ${{ matrix.go-version }}

- name: Vet
run: go vet ./...

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.23'
- name: Test
run: go test -race -count 2 ./...

- name: Bench
run: go test -run @ -bench . -benchtime 1x ./...

lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7

- name: Test
run: go test -race -count 2 -bench . ./...
- uses: actions/setup-go@v6
with:
go-version-file: go.mod

- name: Bench
run: go test -run @ -bench . ./...
- uses: golangci/golangci-lint-action@v9
with:
version: v2.13.2
48 changes: 48 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
version: "2"

linters:
default: standard
enable:
- errorlint
- misspell
- modernize
- nolintlint
- unconvert
settings:
errcheck:
exclude-functions:
- (hash.Hash).Write
- (io.Writer).Write
- crypto/rand.Read
- fmt.Fprint
- fmt.Fprintf
- fmt.Fprintln
- io.WriteString
staticcheck:
checks:
- all
# Package names such as k_nearest_nodes and peer_store are part of the public API.
- -ST1003
# Receiver names follow the existing "me" convention in many types.
- -ST1016
# Exported identifiers without doc comments.
- -ST1000
- -ST1020
- -ST1021
- -ST1022
# TransactionTimeout is exported API.
- -ST1012
# Explicit embedded-field selectors such as NodeAndTime.Time read more clearly.
- -QF1008
exclusions:
presets:
- std-error-handling
rules:
# Tests compare raw IP bytes on purpose.
- path: _test\.go
text: SA1021

formatters:
enable:
- gofmt
- goimports
27 changes: 13 additions & 14 deletions announce.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package dht

// get_peers and announce_peers.

import (
"context"
"fmt"
Expand Down Expand Up @@ -45,7 +43,7 @@ func (a *Announce) NumContacted() uint32 {
}

func (a *Announce) TraversalStats() TraversalStats {
return *a.traversal.Stats()
return a.traversal.LoadStats()
}

// Server.Announce option
Expand Down Expand Up @@ -73,10 +71,11 @@ func AnnouncePeer(opts AnnouncePeerOpts) AnnounceOpt {
}
}

// Deprecated: Use Server.AnnounceTraversal.
// Traverses the DHT graph toward nodes that store peers for the infohash, streaming them to the
// caller, and announcing the local node to each responding node if port is non-zero or impliedPort
// is true.
//
// Deprecated: Use Server.AnnounceTraversal with AnnouncePeer.
func (s *Server) Announce(infoHash [20]byte, port int, impliedPort bool, opts ...AnnounceOpt) (_ *Announce, err error) {
if port != 0 || impliedPort {
opts = append([]AnnounceOpt{AnnouncePeer(AnnouncePeerOpts{
Expand All @@ -99,6 +98,10 @@ func (s *Server) AnnounceTraversal(infoHash [20]byte, opts ...AnnounceOpt) (_ *A
for _, opt := range opts {
opt(a)
}
nodes, err := s.TraversalStartingNodes()
if err != nil {
return
}
a.traversal = traversal.Start(traversal.OperationInput{
Target: infoHash,
DoQuery: a.getPeers,
Expand All @@ -108,11 +111,6 @@ func (s *Server) AnnounceTraversal(infoHash [20]byte, opts ...AnnounceOpt) (_ *A
return ok
},
})
nodes, err := s.TraversalStartingNodes()
if err != nil {
a.traversal.Stop()
return
}
a.traversal.AddNodes(nodes)
go func() {
<-a.traversal.Stalled()
Expand All @@ -130,14 +128,12 @@ func (s *Server) AnnounceTraversal(infoHash [20]byte, opts ...AnnounceOpt) (_ *A
func (a *Announce) announceClosest() {
var wg sync.WaitGroup
a.traversal.Closest().Range(func(elem dhtutil.Elem) {
wg.Add(1)
go func() {
wg.Go(func() {
a.logger().Levelf(log.Debug,
"announce_peer to %v: %v",
elem, a.announcePeer(elem),
)
wg.Done()
}()
})
})
wg.Wait()
}
Expand Down Expand Up @@ -174,9 +170,12 @@ func (a *Announce) getPeers(ctx context.Context, addr krpc.NodeAddr) traversal.Q
},
Return: *r,
}
// Stop waits for this query to return before Stopped fires, so waiting on
// Stopped here deadlocks when nobody is receiving from Peers. The query
// context is cancelled when the traversal stops.
select {
case a.Peers <- peersValues:
case <-a.traversal.Stopped():
case <-ctx.Done():
}
}
return res.TraversalQueryResult(addr)
Expand Down
96 changes: 96 additions & 0 deletions announce_port_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package dht

import (
"net"
"testing"
"time"

"github.com/anacrolix/dht/v2/krpc"
peer_store "github.com/anacrolix/dht/v2/peer-store"
"github.com/anacrolix/torrent/bencode"
"golang.org/x/time/rate"
)

type announcedPortStore struct{ added chan krpc.NodeAddr }

func (s announcedPortStore) AddPeer(_ peer_store.InfoHash, addr krpc.NodeAddr) { s.added <- addr }
func (s announcedPortStore) GetPeers(peer_store.InfoHash) []krpc.NodeAddr { return nil }

func TestAnnouncePeerPortValidation(t *testing.T) {
for _, tc := range []struct {
name string
port int
present, implied, valid bool
}{
{name: "missing"},
{name: "zero", present: true},
{name: "negative", port: -1, present: true},
{name: "too large", port: 65536, present: true},
{name: "maximum", port: 65535, present: true, valid: true},
{name: "implied overrides explicit", port: 65536, present: true, implied: true, valid: true},
} {
t.Run(tc.name, func(t *testing.T) {
peer := mustListen("127.0.0.1:0")
t.Cleanup(func() { _ = peer.Close() })
store := announcedPortStore{added: make(chan krpc.NodeAddr, 1)}
s, err := NewServer(&ServerConfig{Conn: mustListen("127.0.0.1:0"), NoSecurity: true, PeerStore: store, SendLimiter: rate.NewLimiter(rate.Inf, 0)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(s.Close)
source := NewAddr(peer.LocalAddr())
s.mu.Lock()
token := s.createToken(source)
s.mu.Unlock()
args := &krpc.MsgArgs{ID: krpc.ID{19: 1}, InfoHash: krpc.ID{1}, Token: token, ImpliedPort: tc.implied}
if tc.present {
args.Port = &tc.port
}
packet, err := bencode.Marshal(krpc.Msg{Y: krpc.YQuery, Q: "announce_peer", T: "test", A: args})
if err != nil {
t.Fatal(err)
}
if _, err = peer.WriteTo(packet, s.Addr()); err != nil {
t.Fatal(err)
}
if err = peer.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil {
t.Fatal(err)
}
var buf [1500]byte
n, _, err := peer.ReadFrom(buf[:])
if err != nil {
t.Fatal(err)
}
var reply krpc.Msg
if err = bencode.Unmarshal(buf[:n], &reply); err != nil {
t.Fatal(err)
}
if !tc.valid {
if reply.E == nil || reply.E.Code != krpc.ErrorCodeProtocolError {
t.Fatalf("invalid port got response %+v, want protocol error", reply)
}
select {
case addr := <-store.added:
t.Fatalf("stored invalid peer %v", addr)
default:
}
return
}
if reply.R == nil || reply.E != nil {
t.Fatalf("valid announce failed: %+v", reply)
}
want := tc.port
if tc.implied {
want = peer.LocalAddr().(*net.UDPAddr).Port
}
select {
case addr := <-store.added:
if addr.Port != want {
t.Fatalf("stored port %d, want %d", addr.Port, want)
}
case <-time.After(2 * time.Second):
t.Fatal("valid announcement was not stored")
}
})
}
}
49 changes: 35 additions & 14 deletions announce_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package dht

import (
"context"
"crypto/rand"
"net"
"regexp"
Expand Down Expand Up @@ -39,21 +38,43 @@ func TestAnnounceStopsNoPending(t *testing.T) {
},
})
qt.Assert(t, qt.IsNil(err))
t.Cleanup(s.Close)
a, err := s.Announce(randomInfohash(), 0, true)
qt.Assert(t, qt.IsNil(err))
defer a.Close()
<-a.Peers
t.Cleanup(a.Close)
select {
case <-a.Finished():
case <-time.After(2 * time.Second):
t.Fatal("empty traversal did not finish")
}
}

// Assert that rate.Limiter won't wake-up waiters once they have determined a
// delay. This means we can't use it to cancel reservations for queries that
// are successful.
func TestRateLimiterInadequate(t *testing.T) {
rl := rate.NewLimiter(rate.Every(time.Hour), 1)
qt.Check(t, qt.IsNil(rl.Wait(context.Background())))
time.AfterFunc(time.Millisecond, func() { rl.AllowN(time.Now(), -1) })
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
time.AfterFunc(2*time.Millisecond, cancel)
qt.Check(t, qt.Equals(rl.Wait(ctx), context.Canceled))
// Stats can be read while a query is still outstanding.
func TestTraversalStatsDuringQuery(t *testing.T) {
silent := mustListen("localhost:0")
defer silent.Close()
s, err := NewServer(&ServerConfig{
Conn: mustListen("localhost:0"),
NoSecurity: true,
SendLimiter: rate.NewLimiter(rate.Inf, 0),
QueryResendDelay: func() time.Duration { return time.Hour },
StartingNodes: addrResolver(silent.LocalAddr().String()),
})
qt.Assert(t, qt.IsNil(err))
defer s.Close()
a, err := s.AnnounceTraversal([20]byte{9})
qt.Assert(t, qt.IsNil(err))
t.Cleanup(a.Close)
qt.Assert(t, qt.IsNil(silent.SetReadDeadline(time.Now().Add(2*time.Second))))
var packet [1500]byte
_, _, err = silent.ReadFrom(packet[:])
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(a.TraversalStats().NumAddrsTried, uint32(1)))
qt.Assert(t, qt.Equals(a.NumContacted(), uint32(1)))
a.Close()
select {
case <-a.Finished():
case <-time.After(2 * time.Second):
t.Fatal("stats traversal did not finish")
}
}
Loading
Loading