udp_test.go 10.7 KB
Newer Older
1 2 3
package discover

import (
4 5 6
	"bytes"
	"crypto/ecdsa"
	"errors"
F
Felix Lange 已提交
7
	"fmt"
8
	"io"
9 10 11
	logpkg "log"
	"net"
	"os"
12 13 14 15
	"path"
	"reflect"
	"runtime"
	"sync"
16 17 18 19 20 21 22
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/logger"
)

func init() {
23
	logger.AddLogSystem(logger.NewStdLogSystem(os.Stdout, logpkg.LstdFlags, logger.ErrorLevel))
24 25
}

F
Felix Lange 已提交
26 27 28 29 30 31 32 33 34
// shared test variables
var (
	futureExp          = uint64(time.Now().Add(10 * time.Hour).Unix())
	testTarget         = MustHexID("01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101")
	testRemote         = rpcEndpoint{IP: net.ParseIP("1.1.1.1").To4(), UDP: 1, TCP: 2}
	testLocalAnnounced = rpcEndpoint{IP: net.ParseIP("2.2.2.2").To4(), UDP: 3, TCP: 4}
	testLocal          = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6}
)

35 36 37 38 39 40 41 42 43
type udpTest struct {
	t                   *testing.T
	pipe                *dgramPipe
	table               *Table
	udp                 *udp
	sent                [][]byte
	localkey, remotekey *ecdsa.PrivateKey
	remoteaddr          *net.UDPAddr
}
44

45 46 47 48 49 50 51
func newUDPTest(t *testing.T) *udpTest {
	test := &udpTest{
		t:          t,
		pipe:       newpipe(),
		localkey:   newkey(),
		remotekey:  newkey(),
		remoteaddr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 30303},
52
	}
53
	test.table, test.udp = newUDP(test.localkey, test.pipe, nil, "")
54 55 56 57 58 59 60 61
	return test
}

// handles a packet as if it had been sent to the transport.
func (test *udpTest) packetIn(wantError error, ptype byte, data packet) error {
	enc, err := encodePacket(test.remotekey, ptype, data)
	if err != nil {
		return test.errorf("packet (%d) encode error: %v", err)
62
	}
63
	test.sent = append(test.sent, enc)
F
Felix Lange 已提交
64
	if err = test.udp.handlePacket(test.remoteaddr, enc); err != wantError {
65
		return test.errorf("error mismatch: got %q, want %q", err, wantError)
66
	}
67
	return nil
68 69
}

70 71 72 73 74 75 76
// waits for a packet to be sent by the transport.
// validate should have type func(*udpTest, X) error, where X is a packet type.
func (test *udpTest) waitPacketOut(validate interface{}) error {
	dgram := test.pipe.waitPacketOut()
	p, _, _, err := decodePacket(dgram)
	if err != nil {
		return test.errorf("sent packet decode error: %v", err)
77
	}
78 79 80 81 82 83
	fn := reflect.ValueOf(validate)
	exptype := fn.Type().In(0)
	if reflect.TypeOf(p) != exptype {
		return test.errorf("sent packet type mismatch, got: %v, want: %v", reflect.TypeOf(p), exptype)
	}
	fn.Call([]reflect.Value{reflect.ValueOf(p)})
84 85 86
	return nil
}

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
func (test *udpTest) errorf(format string, args ...interface{}) error {
	_, file, line, ok := runtime.Caller(2) // errorf + waitPacketOut
	if ok {
		file = path.Base(file)
	} else {
		file = "???"
		line = 1
	}
	err := fmt.Errorf(format, args...)
	fmt.Printf("\t%s:%d: %v\n", file, line, err)
	test.t.Fail()
	return err
}

func TestUDP_packetErrors(t *testing.T) {
	test := newUDPTest(t)
	defer test.table.Close()

F
Felix Lange 已提交
105 106
	test.packetIn(errExpired, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: Version})
	test.packetIn(errBadVersion, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: 99, Expiration: futureExp})
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
	test.packetIn(errUnsolicitedReply, pongPacket, &pong{ReplyTok: []byte{}, Expiration: futureExp})
	test.packetIn(errUnknownNode, findnodePacket, &findnode{Expiration: futureExp})
	test.packetIn(errUnsolicitedReply, neighborsPacket, &neighbors{Expiration: futureExp})
}

func TestUDP_pingTimeout(t *testing.T) {
	t.Parallel()
	test := newUDPTest(t)
	defer test.table.Close()

	toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
	toid := NodeID{1, 2, 3, 4}
	if err := test.udp.ping(toid, toaddr); err != errTimeout {
		t.Error("expected timeout error, got", err)
	}
}

func TestUDP_findnodeTimeout(t *testing.T) {
125
	t.Parallel()
126 127
	test := newUDPTest(t)
	defer test.table.Close()
128

129 130 131 132 133 134 135 136 137 138 139
	toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
	toid := NodeID{1, 2, 3, 4}
	target := NodeID{4, 5, 6, 7}
	result, err := test.udp.findnode(toid, toaddr, target)
	if err != errTimeout {
		t.Error("expected timeout error, got", err)
	}
	if len(result) > 0 {
		t.Error("expected empty result, got", result)
	}
}
140

141 142 143 144 145 146 147 148
func TestUDP_findnode(t *testing.T) {
	test := newUDPTest(t)
	defer test.table.Close()

	// put a few nodes into the table. their exact
	// distribution shouldn't matter much, altough we need to
	// take care not to overflow any bucket.
	target := testTarget
F
Felix Lange 已提交
149 150
	nodes := &nodesByDistance{target: target}
	for i := 0; i < bucketSize; i++ {
151
		nodes.push(&Node{
F
Felix Lange 已提交
152 153 154 155
			IP:  net.IP{1, 2, 3, byte(i)},
			UDP: uint16(i + 2),
			TCP: uint16(i + 3),
			ID:  randomID(test.table.self.ID, i+2),
156
		}, bucketSize)
157
	}
158 159 160 161
	test.table.add(nodes.entries)

	// ensure there's a bond with the test node,
	// findnode won't be accepted otherwise.
162
	test.table.db.updateNode(&Node{
F
Felix Lange 已提交
163 164 165 166
		ID:  PubkeyID(&test.remotekey.PublicKey),
		IP:  test.remoteaddr.IP,
		UDP: uint16(test.remoteaddr.Port),
		TCP: 99,
167
	})
168 169 170 171 172 173
	// check that closest neighbors are returned.
	test.packetIn(nil, findnodePacket, &findnode{Target: testTarget, Expiration: futureExp})
	test.waitPacketOut(func(p *neighbors) {
		expected := test.table.closest(testTarget, bucketSize)
		if len(p.Nodes) != bucketSize {
			t.Errorf("wrong number of results: got %d, want %d", len(p.Nodes), bucketSize)
F
Felix Lange 已提交
174
		}
175 176 177
		for i := range p.Nodes {
			if p.Nodes[i].ID != expected.entries[i].ID {
				t.Errorf("result mismatch at %d:\n  got:  %v\n  want: %v", i, p.Nodes[i], expected.entries[i])
F
Felix Lange 已提交
178 179 180
			}
		}
	})
181 182
}

183 184 185
func TestUDP_findnodeMultiReply(t *testing.T) {
	test := newUDPTest(t)
	defer test.table.Close()
186

187 188 189 190 191 192 193 194 195 196 197
	// queue a pending findnode request
	resultc, errc := make(chan []*Node), make(chan error)
	go func() {
		rid := PubkeyID(&test.remotekey.PublicKey)
		ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget)
		if err != nil && len(ns) == 0 {
			errc <- err
		} else {
			resultc <- ns
		}
	}()
198

199 200 201 202 203 204 205
	// wait for the findnode to be sent.
	// after it is sent, the transport is waiting for a reply
	test.waitPacketOut(func(p *findnode) {
		if p.Target != testTarget {
			t.Errorf("wrong target: got %v, want %v", p.Target, testTarget)
		}
	})
206

207 208
	// send the reply as two packets.
	list := []*Node{
F
Felix Lange 已提交
209
		MustParseNode("enode://ba85011c70bcc5c04d8607d3a0ed29aa6179c092cbdda10d5d32684fb33ed01bd94f588ca8f91ac48318087dcb02eaf36773a7a453f0eedd6742af668097b29c@10.0.1.16:30303?discport=30304"),
210
		MustParseNode("enode://81fa361d25f157cd421c60dcc28d8dac5ef6a89476633339c5df30287474520caca09627da18543d9079b5b288698b542d56167aa5c09111e55acdbbdf2ef799@10.0.1.16:30303"),
F
Felix Lange 已提交
211
		MustParseNode("enode://9bffefd833d53fac8e652415f4973bee289e8b1a5c6c4cbe70abf817ce8a64cee11b823b66a987f51aaa9fba0d6a91b3e6bf0d5a5d1042de8e9eeea057b217f8@10.0.1.36:30301?discport=17"),
212
		MustParseNode("enode://1b5b4aa662d7cb44a7221bfba67302590b643028197a7d5214790f3bac7aaa4a3241be9e83c09cf1f6c69d007c634faae3dc1b1221793e8446c0b3a09de65960@10.0.1.16:30303"),
213
	}
214 215
	test.packetIn(nil, neighborsPacket, &neighbors{Expiration: futureExp, Nodes: list[:2]})
	test.packetIn(nil, neighborsPacket, &neighbors{Expiration: futureExp, Nodes: list[2:]})
216

217 218 219 220 221 222 223 224 225 226
	// check that the sent neighbors are all returned by findnode
	select {
	case result := <-resultc:
		if !reflect.DeepEqual(result, list) {
			t.Errorf("neighbors mismatch:\n  got:  %v\n  want: %v", result, list)
		}
	case err := <-errc:
		t.Errorf("findnode error: %v", err)
	case <-time.After(5 * time.Second):
		t.Error("findnode did not return within 5 seconds")
227 228 229
	}
}

230 231 232
func TestUDP_successfulPing(t *testing.T) {
	test := newUDPTest(t)
	defer test.table.Close()
233

234 235
	done := make(chan struct{})
	go func() {
F
Felix Lange 已提交
236 237
		// The remote side sends a ping packet to initiate the exchange.
		test.packetIn(nil, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: Version, Expiration: futureExp})
238 239
		close(done)
	}()
F
Felix Lange 已提交
240

241 242 243 244
	// the ping is replied to.
	test.waitPacketOut(func(p *pong) {
		pinghash := test.sent[0][:macSize]
		if !bytes.Equal(p.ReplyTok, pinghash) {
F
Felix Lange 已提交
245 246 247 248 249 250 251 252 253 254
			t.Errorf("got pong.ReplyTok %x, want %x", p.ReplyTok, pinghash)
		}
		wantTo := rpcEndpoint{
			// The mirrored UDP address is the UDP packet sender
			IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port),
			// The mirrored TCP port is the one from the ping packet
			TCP: testRemote.TCP,
		}
		if !reflect.DeepEqual(p.To, wantTo) {
			t.Errorf("got pong.To %v, want %v", p.To, wantTo)
255
		}
256
	})
257

258
	// remote is unknown, the table pings back.
F
Felix Lange 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272
	test.waitPacketOut(func(p *ping) error {
		if !reflect.DeepEqual(p.From, test.udp.ourEndpoint) {
			t.Errorf("got ping.From %v, want %v", p.From, test.udp.ourEndpoint)
		}
		wantTo := rpcEndpoint{
			// The mirrored UDP address is the UDP packet sender.
			IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port),
			TCP: 0,
		}
		if !reflect.DeepEqual(p.To, wantTo) {
			t.Errorf("got ping.To %v, want %v", p.To, wantTo)
		}
		return nil
	})
273 274 275 276 277 278 279 280 281 282 283 284 285 286
	test.packetIn(nil, pongPacket, &pong{Expiration: futureExp})

	// ping should return shortly after getting the pong packet.
	<-done

	// check that the node was added.
	rid := PubkeyID(&test.remotekey.PublicKey)
	rnode := find(test.table, rid)
	if rnode == nil {
		t.Fatalf("node %v not found in table", rid)
	}
	if !bytes.Equal(rnode.IP, test.remoteaddr.IP) {
		t.Errorf("node has wrong IP: got %v, want: %v", rnode.IP, test.remoteaddr.IP)
	}
F
Felix Lange 已提交
287 288
	if int(rnode.UDP) != test.remoteaddr.Port {
		t.Errorf("node has wrong UDP port: got %v, want: %v", rnode.UDP, test.remoteaddr.Port)
289
	}
F
Felix Lange 已提交
290 291
	if rnode.TCP != testRemote.TCP {
		t.Errorf("node has wrong TCP port: got %v, want: %v", rnode.TCP, testRemote.TCP)
292 293 294 295 296 297 298 299
	}
}

func find(tab *Table, id NodeID) *Node {
	for _, b := range tab.buckets {
		for _, e := range b.entries {
			if e.ID == id {
				return e
F
Felix Lange 已提交
300 301
			}
		}
302
	}
303
	return nil
F
Felix Lange 已提交
304
}
305

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
// dgramPipe is a fake UDP socket. It queues all sent datagrams.
type dgramPipe struct {
	mu      *sync.Mutex
	cond    *sync.Cond
	closing chan struct{}
	closed  bool
	queue   [][]byte
}

func newpipe() *dgramPipe {
	mu := new(sync.Mutex)
	return &dgramPipe{
		closing: make(chan struct{}),
		cond:    &sync.Cond{L: mu},
		mu:      mu,
321
	}
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
}

// WriteToUDP queues a datagram.
func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) {
	msg := make([]byte, len(b))
	copy(msg, b)
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.closed {
		return 0, errors.New("closed")
	}
	c.queue = append(c.queue, msg)
	c.cond.Signal()
	return len(b), nil
}

// ReadFromUDP just hangs until the pipe is closed.
func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
	<-c.closing
	return 0, nil, io.EOF
}

func (c *dgramPipe) Close() error {
	c.mu.Lock()
	defer c.mu.Unlock()
	if !c.closed {
		close(c.closing)
		c.closed = true
350
	}
F
Felix Lange 已提交
351
	return nil
352
}
353 354

func (c *dgramPipe) LocalAddr() net.Addr {
F
Felix Lange 已提交
355
	return &net.UDPAddr{IP: testLocal.IP, Port: int(testLocal.UDP)}
356 357 358 359 360 361 362 363 364 365 366 367 368
}

func (c *dgramPipe) waitPacketOut() []byte {
	c.mu.Lock()
	defer c.mu.Unlock()
	for len(c.queue) == 0 {
		c.cond.Wait()
	}
	p := c.queue[0]
	copy(c.queue, c.queue[1:])
	c.queue = c.queue[:len(c.queue)-1]
	return p
}