dht_test.go 9.07 KB
Newer Older
1 2 3
package dht

import (
4
	"encoding/hex"
Matt Joiner's avatar
Matt Joiner committed
5
	"errors"
6
	"io"
7
	"math/big"
8 9
	"net"
	"testing"
10
	"time"
11

12
	_ "github.com/anacrolix/envpprof"
Matt Joiner's avatar
Matt Joiner committed
13 14
	"github.com/anacrolix/missinggo/inproc"
	"github.com/anacrolix/sync"
Matt Joiner's avatar
Matt Joiner committed
15
	"github.com/anacrolix/torrent/bencode"
16
	"github.com/stretchr/testify/assert"
17
	"github.com/stretchr/testify/require"
18

Matt Joiner's avatar
Matt Joiner committed
19
	"github.com/anacrolix/log"
Matt Joiner's avatar
Matt Joiner committed
20 21

	"github.com/anacrolix/dht/v2/krpc"
22 23
)

24 25 26 27 28
func TestSetNilBigInt(t *testing.T) {
	i := new(big.Int)
	i.SetBytes(make([]byte, 2))
}

29
func TestMarshalCompactNodeInfo(t *testing.T) {
30
	cni := krpc.CompactIPv4NodeInfo{krpc.NodeInfo{
31
		ID: [20]byte{'a', 'b', 'c'},
32
	}}
33
	addr, err := net.ResolveUDPAddr("udp4", "1.2.3.4:5")
Matt Joiner's avatar
Matt Joiner committed
34
	require.NoError(t, err)
35 36 37
	cni[0].Addr.FromUDPAddr(addr)
	cni[0].Addr.IP = cni[0].Addr.IP.To4()
	b, err := cni.MarshalBinary()
Matt Joiner's avatar
Matt Joiner committed
38
	require.NoError(t, err)
39 40 41
	var bb [26]byte
	copy(bb[:], []byte("abc"))
	copy(bb[20:], []byte("\x01\x02\x03\x04\x00\x05"))
42
	assert.EqualValues(t, string(bb[:]), string(b))
43
}
44 45 46

const zeroID = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

Matt Joiner's avatar
Matt Joiner committed
47
var testIDs []int160
48 49 50 51 52 53 54 55 56

func init() {
	for _, s := range []string{
		zeroID,
		"\x03" + zeroID[1:],
		"\x03" + zeroID[1:18] + "\x55\xf0",
		"\x55" + zeroID[1:17] + "\xff\x55\x0f",
		"\x54" + zeroID[1:18] + "\x50\x0f",
	} {
Matt Joiner's avatar
Matt Joiner committed
57
		testIDs = append(testIDs, int160FromByteString(s))
58
	}
Matt Joiner's avatar
Matt Joiner committed
59
	testIDs = append(testIDs, int160{})
Matt Joiner's avatar
Matt Joiner committed
60 61 62
}

func TestDistances(t *testing.T) {
63 64 65
	expectBitcount := func(i int160, count int) {
		if bitCount(i.Bytes()) != count {
			t.Fatalf("expected bitcount of %d: got %d", count, bitCount(i.Bytes()))
66
		}
Matt Joiner's avatar
Matt Joiner committed
67
	}
68 69 70
	expectBitcount(distance(testIDs[3], testIDs[0]), 4+8+4+4)
	expectBitcount(distance(testIDs[3], testIDs[1]), 4+8+4+4)
	expectBitcount(distance(testIDs[3], testIDs[2]), 4+8+8)
71 72 73
}

func TestMaxDistanceString(t *testing.T) {
74 75 76
	var max int160
	max.SetMax()
	require.EqualValues(t, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", max.Bytes())
77 78
}

Matt Joiner's avatar
Matt Joiner committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
// func TestClosestNodes(t *testing.T) {
// 	cn := newKClosestNodeIDs(2, testIDs[3])
// 	for _, i := range rand.Perm(len(testIDs)) {
// 		cn.Push(testIDs[i])
// 	}
// 	ids := iter.ToSlice(cn.IDs())
// 	assert.Len(t, ids, 2)
// 	m := map[string]bool{}
// 	for _, id := range ids {
// 		m[id.(nodeID).ByteString()] = true
// 	}
// 	log.Printf("%q", m)
// 	assert.True(t, m[testIDs[3].ByteString()])
// 	assert.True(t, m[testIDs[4].ByteString()])
// }
94

95 96
func TestDHTDefaultConfig(t *testing.T) {
	s, err := NewServer(nil)
Matt Joiner's avatar
Matt Joiner committed
97
	assert.NoError(t, err)
98 99
	s.Close()
}
100 101

func TestPing(t *testing.T) {
Matt Joiner's avatar
Matt Joiner committed
102
	recvConn := mustListen("127.0.0.1:5680")
103
	srv, err := NewServer(&ServerConfig{
Matt Joiner's avatar
Matt Joiner committed
104 105
		Conn:       recvConn,
		NoSecurity: true,
Matt Joiner's avatar
Matt Joiner committed
106
		Logger:     log.Default(),
107 108
	})
	require.NoError(t, err)
109
	defer srv.Close()
110
	srv0, err := NewServer(&ServerConfig{
Matt Joiner's avatar
Matt Joiner committed
111
		Conn:          mustListen("127.0.0.1:5681"),
112
		StartingNodes: addrResolver("127.0.0.1:5680"),
Matt Joiner's avatar
Matt Joiner committed
113
		Logger:        log.Default(),
114 115
	})
	require.NoError(t, err)
116
	defer srv0.Close()
Matt Joiner's avatar
Matt Joiner committed
117 118
	ok := make(chan bool)
	err = srv.Ping(&net.UDPAddr{
119
		IP:   []byte{127, 0, 0, 1},
120
		Port: srv0.Addr().(*net.UDPAddr).Port,
Matt Joiner's avatar
Matt Joiner committed
121 122 123 124 125
	}, func(m krpc.Msg, err error) {
		if err != nil {
			panic(err)
		}
		ok <- *m.SenderID() == srv0.ID()
126
	})
Matt Joiner's avatar
Matt Joiner committed
127
	require.NoError(t, err)
128
	require.True(t, <-ok)
129
}
130

Matt Joiner's avatar
Matt Joiner committed
131
func TestServerCustomNodeId(t *testing.T) {
Matt Joiner's avatar
Matt Joiner committed
132 133 134 135 136 137 138 139
	idHex := "5a3ce1c14e7a08645677bbd1cfe7d8f956d53256"
	idBytes, err := hex.DecodeString(idHex)
	require.NoError(t, err)
	var id [20]byte
	n := copy(id[:], idBytes)
	require.Equal(t, 20, n)
	// How to test custom *secure* ID when tester computers will have
	// different IDs? Generate custom ids for local IPs and use mini-ID?
Matt Joiner's avatar
Matt Joiner committed
140
	s, err := NewServer(&ServerConfig{
Matt Joiner's avatar
Matt Joiner committed
141 142
		NodeId: id,
		Conn:   mustListen(":0"),
Matt Joiner's avatar
Matt Joiner committed
143 144 145
	})
	require.NoError(t, err)
	defer s.Close()
Matt Joiner's avatar
Matt Joiner committed
146
	assert.Equal(t, id, s.ID())
Matt Joiner's avatar
Matt Joiner committed
147 148
}

149 150
func TestAnnounceTimeout(t *testing.T) {
	s, err := NewServer(&ServerConfig{
151
		StartingNodes: addrResolver("1.2.3.4:5"),
Matt Joiner's avatar
Matt Joiner committed
152
		Conn:          mustListen(":0"),
Matt Joiner's avatar
Matt Joiner committed
153 154 155
		QueryResendDelay: func() time.Duration {
			return 0
		},
156 157
	})
	require.NoError(t, err)
158 159 160
	var ih [20]byte
	copy(ih[:], "12341234123412341234")
	a, err := s.Announce(ih, 0, true)
Matt Joiner's avatar
Matt Joiner committed
161
	assert.NoError(t, err)
162 163 164 165 166 167
	<-a.Peers
	a.Close()
	s.Close()
}

func TestEqualPointers(t *testing.T) {
168
	assert.EqualValues(t, &krpc.Msg{R: &krpc.Return{}}, &krpc.Msg{R: &krpc.Return{}})
169
}
170 171 172 173

func TestHook(t *testing.T) {
	t.Log("TestHook: Starting with Ping intercept/passthrough")
	srv, err := NewServer(&ServerConfig{
Matt Joiner's avatar
Matt Joiner committed
174 175
		Conn:     mustListen("127.0.0.1:5678"),
		PublicIP: net.IPv4(127, 0, 0, 1),
176 177 178 179 180 181
	})
	require.NoError(t, err)
	defer srv.Close()
	// Establish server with a hook attached to "ping"
	hookCalled := make(chan bool)
	srv0, err := NewServer(&ServerConfig{
Matt Joiner's avatar
Matt Joiner committed
182 183
		Conn:          mustListen("127.0.0.1:5679"),
		PublicIP:      net.IPv4(127, 0, 0, 1),
184
		StartingNodes: addrResolver("127.0.0.1:5678"),
185
		OnQuery: func(m *krpc.Msg, addr net.Addr) bool {
186 187 188 189 190 191 192 193 194 195
			if m.Q == "ping" {
				hookCalled <- true
			}
			return true
		},
	})
	require.NoError(t, err)
	defer srv0.Close()
	// Ping srv0 from srv to trigger hook. Should also receive a response.
	t.Log("TestHook: Servers created, hook for ping established. Calling Ping.")
Matt Joiner's avatar
Matt Joiner committed
196
	err = srv.Ping(&net.UDPAddr{
197 198
		IP:   []byte{127, 0, 0, 1},
		Port: srv0.Addr().(*net.UDPAddr).Port,
Matt Joiner's avatar
Matt Joiner committed
199
	}, func(m krpc.Msg, err error) {
200 201
		t.Log("TestHook: Sender received response from pinged hook server, so normal execution resumed.")
	})
Matt Joiner's avatar
Matt Joiner committed
202
	assert.NoError(t, err)
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
	// Await signal that hook has been called.
	select {
	case <-hookCalled:
		{
			// Success, hook was triggered. Todo: Ensure that "ok" channel
			// receives, also, indicating normal handling proceeded also.
			t.Log("TestHook: Received ping, hook called and returned to normal execution!")
			return
		}
	case <-time.After(time.Second * 1):
		{
			t.Error("Failed to see evidence of ping hook being called after 2 seconds.")
		}
	}
}
218 219 220 221 222 223

// Check that address resolution doesn't rat out invalid SendTo addr
// arguments.
func TestResolveBadAddr(t *testing.T) {
	ua, err := net.ResolveUDPAddr("udp", "0.131.255.145:33085")
	require.NoError(t, err)
224
	assert.False(t, validNodeAddr(ua))
225
}
226 227 228 229 230 231 232 233 234 235

func TestGlobalBootstrapAddrs(t *testing.T) {
	addrs, err := GlobalBootstrapAddrs()
	if err != nil {
		t.Skip(err)
	}
	for _, a := range addrs {
		t.Log(a)
	}
}
Matt Joiner's avatar
Matt Joiner committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

// https://github.com/anacrolix/dht/pull/19
func TestBadGetPeersResponse(t *testing.T) {
	pc, err := net.ListenPacket("udp", "localhost:0")
	require.NoError(t, err)
	defer pc.Close()
	s, err := NewServer(&ServerConfig{
		StartingNodes: func() ([]Addr, error) {
			return []Addr{NewAddr(pc.LocalAddr().(*net.UDPAddr))}, nil
		},
		Conn: mustListen("localhost:0"),
	})
	require.NoError(t, err)
	defer s.Close()
	go func() {
		b := make([]byte, 1024)
		n, addr, err := pc.ReadFrom(b)
		require.NoError(t, err)
		var rm krpc.Msg
		bencode.Unmarshal(b[:n], &rm)
		m := krpc.Msg{
			R: &krpc.Return{},
			T: rm.T,
		}
		b, err = bencode.Marshal(m)
		require.NoError(t, err)
		pc.WriteTo(b, addr)
	}()
	a, err := s.Announce([20]byte{}, 0, true)
	require.NoError(t, err)
	_, ok := <-a.Peers
	require.False(t, ok)
}
Matt Joiner's avatar
Matt Joiner committed
269 270 271 272

func TestBootstrapRace(t *testing.T) {
	remotePc, err := inproc.ListenPacket("", "localhost:0")
	require.NoError(t, err)
273 274 275 276
	defer remotePc.Close()
	serverPc := bootstrapRacePacketConn{
		read: make(chan read),
	}
Matt Joiner's avatar
Matt Joiner committed
277 278
	t.Logf("remote addr: %s", remotePc.LocalAddr())
	s, err := NewServer(&ServerConfig{
279
		Conn:             &serverPc,
Matt Joiner's avatar
Matt Joiner committed
280 281
		StartingNodes:    addrResolver(remotePc.LocalAddr().String()),
		QueryResendDelay: func() time.Duration { return 0 },
Matt Joiner's avatar
Matt Joiner committed
282
		Logger:           log.Default(),
Matt Joiner's avatar
Matt Joiner committed
283 284 285 286 287 288 289 290
	})
	require.NoError(t, err)
	defer s.Close()
	go func() {
		for i := 0; i < maxTransactionSends-1; i++ {
			remotePc.ReadFrom(nil)
		}
		var b [1024]byte
Matt Joiner's avatar
Matt Joiner committed
291
		_, addr, _ := remotePc.ReadFrom(b[:])
Matt Joiner's avatar
Matt Joiner committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
		var m krpc.Msg
		bencode.Unmarshal(b[:], &m)
		m.Y = "r"
		rb, err := bencode.Marshal(m)
		if err != nil {
			panic(err)
		}
		remotePc.WriteTo(rb, addr)
	}()
	ts, err := s.Bootstrap()
	t.Logf("%#v", ts)
	require.NoError(t, err)
}

type emptyNetAddr struct{}

func (emptyNetAddr) Network() string { return "" }
func (emptyNetAddr) String() string  { return "" }

311 312 313 314 315 316
type read struct {
	b    []byte
	addr net.Addr
}

type bootstrapRacePacketConn struct {
Matt Joiner's avatar
Matt Joiner committed
317 318
	mu     sync.Mutex
	writes int
319
	read   chan read
Matt Joiner's avatar
Matt Joiner committed
320 321
}

322 323 324 325
func (me *bootstrapRacePacketConn) Close() error {
	close(me.read)
	return nil
}
Matt Joiner's avatar
Matt Joiner committed
326
func (me *bootstrapRacePacketConn) LocalAddr() net.Addr { return emptyNetAddr{} }
327 328 329 330 331 332 333 334 335
func (me *bootstrapRacePacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
	r, ok := <-me.read
	if !ok {
		return 0, nil, io.EOF
	}
	copy(b, r.b)
	log.Printf("reading %q from %s", r.b, r.addr)
	return len(r.b), r.addr, nil
}
Matt Joiner's avatar
Matt Joiner committed
336 337 338
func (me *bootstrapRacePacketConn) SetDeadline(time.Time) error      { return nil }
func (me *bootstrapRacePacketConn) SetReadDeadline(time.Time) error  { return nil }
func (me *bootstrapRacePacketConn) SetWriteDeadline(time.Time) error { return nil }
Matt Joiner's avatar
Matt Joiner committed
339

340
func (me *bootstrapRacePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
Matt Joiner's avatar
Matt Joiner committed
341 342 343 344 345
	me.mu.Lock()
	defer me.mu.Unlock()
	me.writes++
	log.Printf("wrote %d times", me.writes)
	if me.writes == maxTransactionSends {
346 347 348 349 350 351 352 353
		var m krpc.Msg
		bencode.Unmarshal(b[:], &m)
		m.Y = "r"
		rb, err := bencode.Marshal(m)
		if err != nil {
			panic(err)
		}
		me.read <- read{rb, addr}
Matt Joiner's avatar
Matt Joiner committed
354 355 356 357
		return 0, errors.New("write error")
	}
	return len(b), nil
}