ext_test.go 7.77 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"
Jeromy's avatar
Jeromy committed
7

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
9
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
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
	routing "github.com/jbenet/go-ipfs/routing"
15
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
16
	u "github.com/jbenet/go-ipfs/util"
17
	testutil "github.com/jbenet/go-ipfs/util/testutil"
Jeromy's avatar
Jeromy committed
18

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

23 24 25 26 27 28
// 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
29 30
// 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
31
type fauxSender struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32
	sync.Mutex
33
	handlers []mesHandleFunc
Jeromy's avatar
Jeromy committed
34 35
}

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

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

43
func (f *fauxSender) SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44 45 46 47 48 49
	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
50 51 52 53 54
		reply := h(m)
		if reply != nil {
			return reply, nil
		}
	}
Jeromy's avatar
Jeromy committed
55

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64
func (f *fauxSender) SendMessage(ctx context.Context, m msg.NetMessage) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66 67 68 69 70
	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
71 72 73
		reply := h(m)
		if reply != nil {
			return nil
Jeromy's avatar
Jeromy committed
74
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
	}
Jeromy's avatar
Jeromy committed
76 77 78
	return nil
}

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99 100 101 102 103 104
// 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
105 106
}

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127
	peerstore := peer.NewPeerstore()
128
	local := makePeerString(t, "")
Jeromy's avatar
Jeromy committed
129

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

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

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

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
207
}
Jeromy's avatar
Jeromy committed
208 209

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

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

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

226
	local := makePeerString(t, "")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228
	peerstore.Add(local)
Jeromy's avatar
Jeromy committed
229

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

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

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

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

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

	})

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
	ctx := context.Background()
289
	u.Debug = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
290 291
	fn := &fauxNet{}
	fs := &fauxSender{}
292
	local := makePeerString(t, "")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294
	peerstore.Add(local)
295

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

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

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

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

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

	})

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