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

import (
	"testing"

Jeromy's avatar
Jeromy committed
6 7
	crand "crypto/rand"

8 9
	"code.google.com/p/goprotobuf/proto"

Jeromy's avatar
Jeromy committed
10
	ds "github.com/jbenet/datastore.go"
Jeromy's avatar
Jeromy committed
11 12
	peer "github.com/jbenet/go-ipfs/peer"
	swarm "github.com/jbenet/go-ipfs/swarm"
13 14
	u "github.com/jbenet/go-ipfs/util"
	ma "github.com/jbenet/go-multiaddr"
Jeromy's avatar
Jeromy committed
15 16 17 18 19 20 21

	"time"
)

// fauxNet is a standin for a swarm.Network in order to more easily recreate
// different testing scenarios
type fauxNet struct {
22 23
	Chan     *swarm.Chan
	handlers []mesHandleFunc
Jeromy's avatar
Jeromy committed
24 25 26 27

	swarm.Network
}

28 29 30 31
// 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
Jeromy's avatar
Jeromy committed
32 33 34 35 36 37 38 39 40
type mesHandleFunc func(*swarm.Message) *swarm.Message

func newFauxNet() *fauxNet {
	fn := new(fauxNet)
	fn.Chan = swarm.NewChan(8)

	return fn
}

41 42 43
// Instead of 'Listening' Start up a goroutine that will check
// all outgoing messages against registered message handlers,
// and reply if needed
Jeromy's avatar
Jeromy committed
44 45 46 47 48
func (f *fauxNet) Listen() error {
	go func() {
		for {
			select {
			case in := <-f.Chan.Outgoing:
49
				for _, h := range f.handlers {
Jeromy's avatar
Jeromy committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
					reply := h(in)
					if reply != nil {
						f.Chan.Incoming <- reply
						break
					}
				}
			}
		}
	}()
	return nil
}

func (f *fauxNet) AddHandler(fn func(*swarm.Message) *swarm.Message) {
	f.handlers = append(f.handlers, fn)
}

func (f *fauxNet) Send(mes *swarm.Message) {
67 68
	f.Chan.Outgoing <- mes
}
Jeromy's avatar
Jeromy committed
69

70 71 72 73
func (f *fauxNet) GetErrChan() chan error {
	return f.Chan.Errors
}

74 75
func (f *fauxNet) GetChannel(t swarm.PBWrapper_MessageType) *swarm.Chan {
	return f.Chan
Jeromy's avatar
Jeromy committed
76 77
}

78 79 80 81
func (f *fauxNet) Connect(addr *ma.Multiaddr) (*peer.Peer, error) {
	return nil, nil
}

Jeromy's avatar
Jeromy committed
82 83 84 85
func (f *fauxNet) GetConnection(id peer.ID, addr *ma.Multiaddr) (*peer.Peer, error) {
	return &peer.Peer{ID: id, Addresses: []*ma.Multiaddr{addr}}, nil
}

86
func TestGetFailures(t *testing.T) {
Jeromy's avatar
Jeromy committed
87 88 89 90
	fn := newFauxNet()
	fn.Listen()

	local := new(peer.Peer)
91
	local.ID = peer.ID("test_peer")
Jeromy's avatar
Jeromy committed
92

Jeromy's avatar
Jeromy committed
93
	d := NewDHT(local, fn, ds.NewMapDatastore())
Jeromy's avatar
Jeromy committed
94

95 96
	other := &peer.Peer{ID: peer.ID("other_peer")}

Jeromy's avatar
Jeromy committed
97 98
	d.Start()

99 100 101
	d.Update(other)

	// This one should time out
102
	_, err := d.GetValue(u.Key("test"), time.Millisecond*10)
Jeromy's avatar
Jeromy committed
103
	if err != nil {
104
		if err != u.ErrTimeout {
105 106 107 108
			t.Fatal("Got different error than we expected.")
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
109 110
	}

111
	// Reply with failures to every message
112 113 114 115 116 117 118
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		pmes := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, pmes)
		if err != nil {
			t.Fatal(err)
		}

Chas Leichner's avatar
Chas Leichner committed
119
		resp := Message{
120
			Type:     pmes.GetType(),
Chas Leichner's avatar
Chas Leichner committed
121
			ID:       pmes.GetId(),
122 123 124 125 126 127 128
			Response: true,
			Success:  false,
		}
		return swarm.NewMessage(mes.Peer, resp.ToProtobuf())
	})

	// This one should fail with NotFound
129
	_, err = d.GetValue(u.Key("test"), time.Millisecond*1000)
130 131
	if err != nil {
		if err != u.ErrNotFound {
132
			t.Fatalf("Expected ErrNotFound, got: %s", err)
133 134 135 136
		}
	} else {
		t.Fatal("expected error, got none.")
	}
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

	success := make(chan struct{})
	fn.handlers = nil
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		resp := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, resp)
		if err != nil {
			t.Fatal(err)
		}
		if resp.GetSuccess() {
			t.Fatal("Get returned success when it shouldnt have.")
		}
		success <- struct{}{}
		return nil
	})

	// Now we test this DHT's handleGetValue failure
Chas Leichner's avatar
Chas Leichner committed
154
	req := Message{
155 156
		Type:  PBDHTMessage_GET_VALUE,
		Key:   "hello",
157
		ID:    swarm.GenerateMessageID(),
158 159 160 161 162
		Value: []byte{0},
	}
	fn.Chan.Incoming <- swarm.NewMessage(other, req.ToProtobuf())

	<-success
Jeromy's avatar
Jeromy committed
163
}
Jeromy's avatar
Jeromy committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

// TODO: Maybe put these in some sort of "ipfs_testutil" package
func _randPeer() *peer.Peer {
	p := new(peer.Peer)
	p.ID = make(peer.ID, 16)
	p.Addresses = []*ma.Multiaddr{nil}
	crand.Read(p.ID)
	return p
}

func TestNotFound(t *testing.T) {
	fn := newFauxNet()
	fn.Listen()

	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")

Jeromy's avatar
Jeromy committed
181
	d := NewDHT(local, fn, ds.NewMapDatastore())
Jeromy's avatar
Jeromy committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	d.Start()

	var ps []*peer.Peer
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}

	// Reply with random peers to every message
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		t.Log("Handling message...")
		pmes := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, pmes)
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
		case PBDHTMessage_GET_VALUE:
			resp := Message{
				Type:     pmes.GetType(),
				ID:       pmes.GetId(),
				Response: true,
				Success:  false,
			}

			for i := 0; i < 7; i++ {
				resp.Peers = append(resp.Peers, _randPeer())
			}
			return swarm.NewMessage(mes.Peer, resp.ToProtobuf())
		default:
			panic("Shouldnt recieve this.")
		}

	})

	_, err := d.GetValue(u.Key("hello"), time.Second*30)
	if err != nil {
		switch err {
		case u.ErrNotFound:
			//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.")
}
232 233 234 235 236 237 238 239 240 241 242

// 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) {
	u.Debug = false
	fn := newFauxNet()
	fn.Listen()

	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")

Jeromy's avatar
Jeromy committed
243
	d := NewDHT(local, fn, ds.NewMapDatastore())
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	d.Start()

	var ps []*peer.Peer
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}
	other := _randPeer()

	// Reply with random peers to every message
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		t.Log("Handling message...")
		pmes := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, pmes)
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
		case PBDHTMessage_GET_VALUE:
			resp := Message{
				Type:     pmes.GetType(),
				ID:       pmes.GetId(),
				Response: true,
				Success:  false,
				Peers:    []*peer.Peer{other},
			}

			return swarm.NewMessage(mes.Peer, resp.ToProtobuf())
		default:
			panic("Shouldnt recieve this.")
		}

	})

	_, err := d.GetValue(u.Key("hello"), time.Second*30)
	if err != nil {
		switch err {
		case u.ErrNotFound:
			//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.")
}