ext_test.go 7.73 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5
package dht

import (
	"testing"

Jeromy's avatar
Jeromy committed
6
	crand "crypto/rand"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
8
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
9

10
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12
	msg "github.com/jbenet/go-ipfs/net/message"
	mux "github.com/jbenet/go-ipfs/net/mux"
Jeromy's avatar
Jeromy committed
13
	peer "github.com/jbenet/go-ipfs/peer"
14
	"github.com/jbenet/go-ipfs/routing"
15
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
16
	u "github.com/jbenet/go-ipfs/util"
Jeromy's avatar
Jeromy committed
17

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
	"sync"
Jeromy's avatar
Jeromy committed
19 20 21
	"time"
)

22 23 24 25 26 27
// mesHandleFunc is a function that takes in outgoing messages
// and can respond to them, simulating other peers on the network.
// returning nil will chose not to respond and pass the message onto the
// next registered handler
type mesHandleFunc func(msg.NetMessage) msg.NetMessage

Jeromy's avatar
Jeromy committed
28 29
// fauxNet is a standin for a swarm.Network in order to more easily recreate
// different testing scenarios
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
type fauxSender struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
	sync.Mutex
32
	handlers []mesHandleFunc
Jeromy's avatar
Jeromy committed
33 34
}

35
func (f *fauxSender) AddHandler(fn func(msg.NetMessage) msg.NetMessage) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36 37 38
	f.Lock()
	defer f.Unlock()

39 40
	f.handlers = append(f.handlers, fn)
}
Jeromy's avatar
Jeromy committed
41

42
func (f *fauxSender) SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45 46 47 48
	f.Lock()
	handlers := make([]mesHandleFunc, len(f.handlers))
	copy(handlers, f.handlers)
	f.Unlock()

	for _, h := range handlers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49 50 51 52 53
		reply := h(m)
		if reply != nil {
			return reply, nil
		}
	}
Jeromy's avatar
Jeromy committed
54

55 56 57 58 59 60
	// no reply? ok force a timeout
	select {
	case <-ctx.Done():
	}

	return nil, ctx.Err()
Jeromy's avatar
Jeromy committed
61 62
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
func (f *fauxSender) SendMessage(ctx context.Context, m msg.NetMessage) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66 67 68 69
	f.Lock()
	handlers := make([]mesHandleFunc, len(f.handlers))
	copy(handlers, f.handlers)
	f.Unlock()

	for _, h := range handlers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70 71 72
		reply := h(m)
		if reply != nil {
			return nil
Jeromy's avatar
Jeromy committed
73
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
	}
Jeromy's avatar
Jeromy committed
75 76 77
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78 79 80
// fauxNet is a standin for a swarm.Network in order to more easily recreate
// different testing scenarios
type fauxNet struct {
81
}
Jeromy's avatar
Jeromy committed
82

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
// DialPeer attempts to establish a connection to a given peer
84
func (f *fauxNet) DialPeer(context.Context, peer.Peer) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85
	return nil
86 87
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88
// ClosePeer connection to peer
89
func (f *fauxNet) ClosePeer(peer.Peer) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
	return nil
Jeromy's avatar
Jeromy committed
91 92
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
// IsConnected returns whether a connection to given peer exists.
94
func (f *fauxNet) IsConnected(peer.Peer) (bool, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95
	return true, nil
96 97
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99 100 101 102 103
// GetProtocols returns the protocols registered in the network.
func (f *fauxNet) GetProtocols() *mux.ProtocolMap { return nil }

// SendMessage sends given Message out
func (f *fauxNet) SendMessage(msg.NetMessage) error {
	return nil
Jeromy's avatar
Jeromy committed
104 105
}

106
func (f *fauxNet) GetPeerList() []peer.Peer {
107 108 109
	return nil
}

110 111 112 113
func (f *fauxNet) GetBandwidthTotals() (uint64, uint64) {
	return 0, 0
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115 116
// Close terminates all network operation
func (f *fauxNet) Close() error { return nil }

117
func TestGetFailures(t *testing.T) {
118 119 120
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122 123 124
	ctx := context.Background()
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
125

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126
	peerstore := peer.NewPeerstore()
127
	local := makePeer(nil)
Jeromy's avatar
Jeromy committed
128

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
130
	other := makePeer(nil)
131 132 133
	d.Update(other)

	// This one should time out
134
	// u.POut("Timout Test\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136
	ctx1, _ := context.WithTimeout(context.Background(), time.Second)
	_, err := d.GetValue(ctx1, u.Key("test"))
Jeromy's avatar
Jeromy committed
137
	if err != nil {
138 139
		if err != context.DeadlineExceeded {
			t.Fatal("Got different error than we expected", err)
140 141 142
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
143 144
	}

145
	// u.POut("NotFound Test\n")
146
	// Reply with failures to every message
147
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
148
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149
		err := proto.Unmarshal(mes.Data(), pmes)
150 151 152 153
		if err != nil {
			t.Fatal(err)
		}

154
		resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155
			Type: pmes.Type,
156
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157 158
		m, err := msg.FromObject(mes.Peer(), resp)
		return m
159 160 161
	})

	// This one should fail with NotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163
	ctx2, _ := context.WithTimeout(context.Background(), time.Second)
	_, err = d.GetValue(ctx2, u.Key("test"))
164
	if err != nil {
165
		if err != routing.ErrNotFound {
166
			t.Fatalf("Expected ErrNotFound, got: %s", err)
167 168 169 170
		}
	} else {
		t.Fatal("expected error, got none.")
	}
171

172
	fs.handlers = nil
173
	// Now we test this DHT's handleGetValue failure
174
	typ := pb.Message_GET_VALUE
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
	str := "hello"
176 177 178 179
	rec, err := d.makePutRecord(u.Key(str), []byte("blah"))
	if err != nil {
		t.Fatal(err)
	}
180
	req := pb.Message{
181 182 183
		Type:   &typ,
		Key:    &str,
		Record: rec,
184
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185

186
	// u.POut("handleGetValue Test\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187 188 189 190 191
	mes, err := msg.FromObject(other, &req)
	if err != nil {
		t.Error(err)
	}

192
	mes = d.HandleMessage(ctx, mes)
193

194
	pmes := new(pb.Message)
195 196 197 198
	err = proto.Unmarshal(mes.Data(), pmes)
	if err != nil {
		t.Fatal(err)
	}
199
	if pmes.GetRecord() != nil {
200 201
		t.Fatal("shouldnt have value")
	}
202
	if len(pmes.GetCloserPeers()) > 0 {
203 204 205 206 207 208
		t.Fatal("shouldnt have closer peers")
	}
	if pmes.GetProviderPeers() != nil {
		t.Fatal("shouldnt have provider peers")
	}

Jeromy's avatar
Jeromy committed
209
}
Jeromy's avatar
Jeromy committed
210 211

// TODO: Maybe put these in some sort of "ipfs_testutil" package
212 213 214 215
func _randPeer() peer.Peer {
	id := make(peer.ID, 16)
	crand.Read(id)
	p := peer.WithID(id)
Jeromy's avatar
Jeromy committed
216 217 218 219
	return p
}

func TestNotFound(t *testing.T) {
220 221 222
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
223

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225 226
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
227

228
	local := makePeer(nil)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230
	peerstore.Add(local)
Jeromy's avatar
Jeromy committed
231

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
Jeromy's avatar
Jeromy committed
233

234
	var ps []peer.Peer
Jeromy's avatar
Jeromy committed
235 236 237 238 239 240
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}

	// Reply with random peers to every message
241
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
242
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243
		err := proto.Unmarshal(mes.Data(), pmes)
Jeromy's avatar
Jeromy committed
244 245 246 247 248
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
249 250
		case pb.Message_GET_VALUE:
			resp := &pb.Message{Type: pmes.Type}
Jeromy's avatar
Jeromy committed
251

252
			peers := []peer.Peer{}
Jeromy's avatar
Jeromy committed
253
			for i := 0; i < 7; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254 255
				peers = append(peers, _randPeer())
			}
256
			resp.CloserPeers = pb.PeersToPBPeers(peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257 258 259
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
Jeromy's avatar
Jeromy committed
260
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261
			return mes
Jeromy's avatar
Jeromy committed
262 263 264 265 266 267
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
268
	ctx, _ = context.WithTimeout(ctx, time.Second*5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269
	v, err := d.GetValue(ctx, u.Key("hello"))
270
	log.Debugf("get value got %v", v)
Jeromy's avatar
Jeromy committed
271 272
	if err != nil {
		switch err {
273
		case routing.ErrNotFound:
Jeromy's avatar
Jeromy committed
274 275 276 277 278 279 280 281 282 283
			//Success!
			return
		case u.ErrTimeout:
			t.Fatal("Should not have gotten timeout!")
		default:
			t.Fatalf("Got unexpected error: %s", err)
		}
	}
	t.Fatal("Expected to recieve an error.")
}
284 285 286 287

// If less than K nodes are in the entire network, it should fail when we make
// a GET rpc and nobody has the value
func TestLessThanKResponses(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288 289
	// t.Skip("skipping test because it makes a lot of output")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
290
	ctx := context.Background()
291
	u.Debug = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292 293
	fn := &fauxNet{}
	fs := &fauxSender{}
294
	local := makePeer(nil)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296
	peerstore.Add(local)
297

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
298
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
299

300
	var ps []peer.Peer
301 302 303 304 305 306 307
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}
	other := _randPeer()

	// Reply with random peers to every message
308
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
309
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
		err := proto.Unmarshal(mes.Data(), pmes)
311 312 313 314 315
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
316 317
		case pb.Message_GET_VALUE:
			resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318
				Type:        pmes.Type,
319
				CloserPeers: pb.PeersToPBPeers([]peer.Peer{other}),
320 321
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322 323 324 325 326
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
			}
			return mes
327 328 329 330 331 332
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
333
	ctx, _ = context.WithTimeout(ctx, time.Second*30)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334
	_, err := d.GetValue(ctx, u.Key("hello"))
335 336
	if err != nil {
		switch err {
337
		case routing.ErrNotFound:
338 339 340 341 342 343 344 345 346 347
			//Success!
			return
		case u.ErrTimeout:
			t.Fatal("Should not have gotten timeout!")
		default:
			t.Fatalf("Got unexpected error: %s", err)
		}
	}
	t.Fatal("Expected to recieve an error.")
}