func TestClientOverMax(t *testing.T) {
	rs := VirtualRoutingServer()
	k := u.Key("hello")
	numProvidersForHelloKey := 100
	for i := 0; i < numProvidersForHelloKey; i++ {
		peer := peer.WithIDString(string(i))
		err := rs.Announce(peer, k)
		if err != nil {
			t.Fatal(err)
		}
	}
	providersFromHashTable := rs.Providers(k)
	if len(providersFromHashTable) != numProvidersForHelloKey {
		t.Log(1 == len(providersFromHashTable))
		t.Fatal("not all providers were returned")
	}

	max := 10
	peer := peer.WithIDString("TODO")
	client := rs.Client(peer)

	providersFromClient := client.FindProvidersAsync(context.Background(), k, max)
	i := 0
	for _ = range providersFromClient {
		i++
	}
	if i != max {
		t.Fatal("Too many providers returned")
	}
}
func TestToAndFromNetMessage(t *testing.T) {

	original := New()
	original.AddBlock(*blocks.NewBlock([]byte("W")))
	original.AddBlock(*blocks.NewBlock([]byte("E")))
	original.AddBlock(*blocks.NewBlock([]byte("F")))
	original.AddBlock(*blocks.NewBlock([]byte("M")))

	p := peer.WithIDString("X")
	netmsg, err := original.ToNet(p)
	if err != nil {
		t.Fatal(err)
	}

	m2, err := FromNet(netmsg)
	if err != nil {
		t.Fatal(err)
	}

	keys := make(map[u.Key]bool)
	for _, b := range m2.Blocks() {
		keys[b.Key()] = true
	}

	for _, b := range original.Blocks() {
		if _, ok := keys[b.Key()]; !ok {
			t.Fail()
		}
	}
}
func TestToNetFromNetPreservesWantList(t *testing.T) {
	original := New()
	original.AddWanted(u.Key("M"))
	original.AddWanted(u.Key("B"))
	original.AddWanted(u.Key("D"))
	original.AddWanted(u.Key("T"))
	original.AddWanted(u.Key("F"))

	p := peer.WithIDString("X")
	netmsg, err := original.ToNet(p)
	if err != nil {
		t.Fatal(err)
	}

	copied, err := FromNet(netmsg)
	if err != nil {
		t.Fatal(err)
	}

	keys := make(map[u.Key]bool)
	for _, k := range copied.Wantlist() {
		keys[k] = true
	}

	for _, k := range original.Wantlist() {
		if _, ok := keys[k]; !ok {
			t.Fatalf("Key Missing: \"%v\"", k)
		}
	}
}
func TestClientFindProviders(t *testing.T) {
	peer := peer.WithIDString("42")
	rs := VirtualRoutingServer()
	client := rs.Client(peer)

	k := u.Key("hello")
	err := client.Provide(context.Background(), k)
	if err != nil {
		t.Fatal(err)
	}
	max := 100

	providersFromHashTable := rs.Providers(k)

	isInHT := false
	for _, p := range providersFromHashTable {
		if bytes.Equal(p.ID(), peer.ID()) {
			isInHT = true
		}
	}
	if !isInHT {
		t.Fatal("Despite client providing key, peer wasn't in hash table as a provider")
	}
	providersFromClient := client.FindProvidersAsync(context.Background(), u.Key("hello"), max)
	isInClient := false
	for p := range providersFromClient {
		if bytes.Equal(p.ID(), peer.ID()) {
			isInClient = true
		}
	}
	if !isInClient {
		t.Fatal("Despite client providing key, client didn't receive peer when finding providers")
	}
}
func TestSendMessageAsyncButWaitForResponse(t *testing.T) {
	net := VirtualNetwork()
	idOfResponder := []byte("responder")
	waiter := net.Adapter(peer.WithIDString("waiter"))
	responder := net.Adapter(peer.WithID(idOfResponder))

	var wg sync.WaitGroup

	wg.Add(1)

	expectedStr := "received async"

	responder.SetDelegate(lambda(func(
		ctx context.Context,
		fromWaiter peer.Peer,
		msgFromWaiter bsmsg.BitSwapMessage) (
		peer.Peer, bsmsg.BitSwapMessage) {

		msgToWaiter := bsmsg.New()
		msgToWaiter.AddBlock(*blocks.NewBlock([]byte(expectedStr)))

		return fromWaiter, msgToWaiter
	}))

	waiter.SetDelegate(lambda(func(
		ctx context.Context,
		fromResponder peer.Peer,
		msgFromResponder bsmsg.BitSwapMessage) (
		peer.Peer, bsmsg.BitSwapMessage) {

		// TODO assert that this came from the correct peer and that the message contents are as expected
		ok := false
		for _, b := range msgFromResponder.Blocks() {
			if string(b.Data) == expectedStr {
				wg.Done()
				ok = true
			}
		}

		if !ok {
			t.Fatal("Message not received from the responder")

		}
		return nil, nil
	}))

	messageSentAsync := bsmsg.New()
	messageSentAsync.AddBlock(*blocks.NewBlock([]byte("data")))
	errSending := waiter.SendMessage(
		context.Background(), peer.WithID(idOfResponder), messageSentAsync)
	if errSending != nil {
		t.Fatal(errSending)
	}

	wg.Wait() // until waiter delegate function is executed
}
func TestToNetMethodSetsPeer(t *testing.T) {
	m := New()
	p := peer.WithIDString("X")
	netmsg, err := m.ToNet(p)
	if err != nil {
		t.Fatal(err)
	}
	if !(netmsg.Peer().Key() == p.Key()) {
		t.Fatal("Peer key is different")
	}
}
func TestProviderManager(t *testing.T) {
	ctx := context.Background()
	mid := peer.ID("testing")
	p := NewProviderManager(ctx, mid)
	a := u.Key("test")
	p.AddProvider(a, peer.WithIDString("testingprovider"))
	resp := p.GetProviders(a)
	if len(resp) != 1 {
		t.Fatal("Could not retrieve provider.")
	}
	p.Close()
}
// TODO does dht ensure won't receive self as a provider? probably not.
func TestCanceledContext(t *testing.T) {
	rs := VirtualRoutingServer()
	k := u.Key("hello")

	t.Log("async'ly announce infinite stream of providers for key")
	i := 0
	go func() { // infinite stream
		for {
			peer := peer.WithIDString(string(i))
			err := rs.Announce(peer, k)
			if err != nil {
				t.Fatal(err)
			}
			i++
		}
	}()

	local := peer.WithIDString("peer id doesn't matter")
	client := rs.Client(local)

	t.Log("warning: max is finite so this test is non-deterministic")
	t.Log("context cancellation could simply take lower priority")
	t.Log("and result in receiving the max number of results")
	max := 1000

	t.Log("cancel the context before consuming")
	ctx, cancelFunc := context.WithCancel(context.Background())
	cancelFunc()
	providers := client.FindProvidersAsync(ctx, k, max)

	numProvidersReturned := 0
	for _ = range providers {
		numProvidersReturned++
	}
	t.Log(numProvidersReturned)

	if numProvidersReturned == max {
		t.Fatal("Context cancel had no effect")
	}
}
func TestSendRequestToCooperativePeer(t *testing.T) {
	net := VirtualNetwork()

	idOfRecipient := []byte("recipient")

	t.Log("Get two network adapters")

	initiator := net.Adapter(peer.WithIDString("initiator"))
	recipient := net.Adapter(peer.WithID(idOfRecipient))

	expectedStr := "response from recipient"
	recipient.SetDelegate(lambda(func(
		ctx context.Context,
		from peer.Peer,
		incoming bsmsg.BitSwapMessage) (
		peer.Peer, bsmsg.BitSwapMessage) {

		t.Log("Recipient received a message from the network")

		// TODO test contents of incoming message

		m := bsmsg.New()
		m.AddBlock(*blocks.NewBlock([]byte(expectedStr)))

		return from, m
	}))

	t.Log("Build a message and send a synchronous request to recipient")

	message := bsmsg.New()
	message.AddBlock(*blocks.NewBlock([]byte("data")))
	response, err := initiator.SendRequest(
		context.Background(), peer.WithID(idOfRecipient), message)
	if err != nil {
		t.Fatal(err)
	}

	t.Log("Check the contents of the response from recipient")

	for _, blockFromRecipient := range response.Blocks() {
		if string(blockFromRecipient.Data) == expectedStr {
			return
		}
	}
	t.Fatal("Should have returned after finding expected block data")
}
func TestProviderForKeyButNetworkCannotFind(t *testing.T) {

	net := tn.VirtualNetwork()
	rs := mock.VirtualRoutingServer()
	g := NewSessionGenerator(net, rs)

	block := blocks.NewBlock([]byte("block"))
	rs.Announce(peer.WithIDString("testing"), block.Key()) // but not on network

	solo := g.Next()

	ctx, _ := context.WithTimeout(context.Background(), time.Nanosecond)
	_, err := solo.exchange.Block(ctx, block.Key())

	if err != context.DeadlineExceeded {
		t.Fatal("Expected DeadlineExceeded error")
	}
}
func TestRoutingResolve(t *testing.T) {
	local := peer.WithIDString("testID")
	lds := ds.NewMapDatastore()
	d := mock.NewMockRouter(local, lds)

	resolver := NewRoutingResolver(d)
	publisher := NewRoutingPublisher(d)

	privk, pubk, err := ci.GenerateKeyPair(ci.RSA, 512)
	if err != nil {
		t.Fatal(err)
	}

	err = publisher.Publish(privk, "Hello")
	if err == nil {
		t.Fatal("should have errored out when publishing a non-multihash val")
	}

	h := u.Key(u.Hash([]byte("Hello"))).Pretty()
	err = publisher.Publish(privk, h)
	if err != nil {
		t.Fatal(err)
	}

	pubkb, err := pubk.Bytes()
	if err != nil {
		t.Fatal(err)
	}

	pkhash := u.Hash(pubkb)
	res, err := resolver.Resolve(u.Key(pkhash).Pretty())
	if err != nil {
		t.Fatal(err)
	}

	if res != h {
		t.Fatal("Got back incorrect value.")
	}
}
Example #12
0
func newPeer(id string) peer.Peer {
	return peer.WithIDString(id)
}
func newPeerAndStrategist(idStr string) peerAndStrategist {
	return peerAndStrategist{
		Peer:     peer.WithIDString(idStr),
		Strategy: New(true),
	}
}