ext_test.go 7.75 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) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118 119
	// t.Skip("skipping test because it makes a lot of output")

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124
	peerstore := peer.NewPeerstore()
125
	local := peer.WithIDString("test_peer")
Jeromy's avatar
Jeromy committed
126

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
128
	other := peer.WithIDString("other_peer")
129 130 131
	d.Update(other)

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

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

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

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

170
	fs.handlers = nil
171
	// Now we test this DHT's handleGetValue failure
172
	typ := pb.Message_GET_VALUE
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173
	str := "hello"
174
	req := pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175 176
		Type:  &typ,
		Key:   &str,
177 178
		Value: []byte{0},
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179

180
	// u.POut("handleGetValue Test\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181 182 183 184 185
	mes, err := msg.FromObject(other, &req)
	if err != nil {
		t.Error(err)
	}

186
	mes = d.HandleMessage(ctx, mes)
187

188
	pmes := new(pb.Message)
189 190 191 192 193 194 195 196 197 198 199 200 201 202
	err = proto.Unmarshal(mes.Data(), pmes)
	if err != nil {
		t.Fatal(err)
	}
	if pmes.GetValue() != nil {
		t.Fatal("shouldnt have value")
	}
	if pmes.GetCloserPeers() != nil {
		t.Fatal("shouldnt have closer peers")
	}
	if pmes.GetProviderPeers() != nil {
		t.Fatal("shouldnt have provider peers")
	}

Jeromy's avatar
Jeromy committed
203
}
Jeromy's avatar
Jeromy committed
204 205

// TODO: Maybe put these in some sort of "ipfs_testutil" package
206 207 208 209
func _randPeer() peer.Peer {
	id := make(peer.ID, 16)
	crand.Read(id)
	p := peer.WithID(id)
Jeromy's avatar
Jeromy committed
210 211 212 213
	return p
}

func TestNotFound(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214 215
	// t.Skip("skipping test because it makes a lot of output")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217 218
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
219

220
	local := peer.WithIDString("test_peer")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222
	peerstore.Add(local)
Jeromy's avatar
Jeromy committed
223

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

226
	var ps []peer.Peer
Jeromy's avatar
Jeromy committed
227 228 229 230 231 232
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}

	// Reply with random peers to every message
233
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
234
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
		err := proto.Unmarshal(mes.Data(), pmes)
Jeromy's avatar
Jeromy committed
236 237 238 239 240
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
241 242
		case pb.Message_GET_VALUE:
			resp := &pb.Message{Type: pmes.Type}
Jeromy's avatar
Jeromy committed
243

244
			peers := []peer.Peer{}
Jeromy's avatar
Jeromy committed
245
			for i := 0; i < 7; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246 247
				peers = append(peers, _randPeer())
			}
248
			resp.CloserPeers = pb.PeersToPBPeers(peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249 250 251
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
Jeromy's avatar
Jeromy committed
252
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
253
			return mes
Jeromy's avatar
Jeromy committed
254 255 256 257 258 259
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
	ctx, _ = context.WithTimeout(ctx, time.Second*5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261
	v, err := d.GetValue(ctx, u.Key("hello"))
262
	log.Debugf("get value got %v", v)
Jeromy's avatar
Jeromy committed
263 264
	if err != nil {
		switch err {
265
		case routing.ErrNotFound:
Jeromy's avatar
Jeromy committed
266 267 268 269 270 271 272 273 274 275
			//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.")
}
276 277 278 279

// 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
280 281
	// t.Skip("skipping test because it makes a lot of output")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
	ctx := context.Background()
283
	u.Debug = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284 285
	fn := &fauxNet{}
	fs := &fauxSender{}
286
	local := peer.WithIDString("test_peer")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
287
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
	peerstore.Add(local)
289

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

292
	var ps []peer.Peer
293 294 295 296 297 298 299
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}
	other := _randPeer()

	// Reply with random peers to every message
300
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
301
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302
		err := proto.Unmarshal(mes.Data(), pmes)
303 304 305 306 307
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
308 309
		case pb.Message_GET_VALUE:
			resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
				Type:        pmes.Type,
311
				CloserPeers: pb.PeersToPBPeers([]peer.Peer{other}),
312 313
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
314 315 316 317 318
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
			}
			return mes
319 320 321 322 323 324
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
325
	ctx, _ = context.WithTimeout(ctx, time.Second*30)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326
	_, err := d.GetValue(ctx, u.Key("hello"))
327 328
	if err != nil {
		switch err {
329
		case routing.ErrNotFound:
330 331 332 333 334 335 336 337 338 339
			//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.")
}