table_test.go 1.84 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
package dht

import (
	crand "crypto/rand"
	"crypto/sha256"
	"math/rand"
	"container/list"
	"testing"

	peer "github.com/jbenet/go-ipfs/peer"
)

func _randPeer() *peer.Peer {
	p := new(peer.Peer)
	p.ID = make(peer.ID, 16)
	crand.Read(p.ID)
	return p
}

func _randID() ID {
	buf := make([]byte, 16)
	crand.Read(buf)

	hash := sha256.Sum256(buf)
	return ID(hash[:])
}

// Test basic features of the bucket struct
func TestBucket(t *testing.T) {
	b := new(Bucket)

	peers := make([]*peer.Peer, 100)
	for i := 0; i < 100; i++ {
		peers[i] = _randPeer()
		b.PushFront(peers[i])
	}

	local := _randPeer()
	local_id := convertPeerID(local.ID)

	i := rand.Intn(len(peers))
	e := b.Find(peers[i].ID)
	if e == nil {
		t.Errorf("Failed to find peer: %v", peers[i])
	}

	spl := b.Split(0, convertPeerID(local.ID))
	llist := (*list.List)(b)
	for e := llist.Front(); e != nil; e = e.Next() {
		p := convertPeerID(e.Value.(*peer.Peer).ID)
		cpl := xor(p, local_id).commonPrefixLen()
		if cpl > 0 {
			t.Fatalf("Split failed. found id with cpl > 0 in 0 bucket")
		}
	}

	rlist := (*list.List)(spl)
	for e := rlist.Front(); e != nil; e = e.Next() {
		p := convertPeerID(e.Value.(*peer.Peer).ID)
		cpl := xor(p, local_id).commonPrefixLen()
		if cpl == 0 {
			t.Fatalf("Split failed. found id with cpl == 0 in non 0 bucket")
		}
	}
}

// Right now, this just makes sure that it doesnt hang or crash
func TestTableUpdate(t *testing.T) {
	local := _randPeer()
	rt := NewRoutingTable(10, convertPeerID(local.ID))

	peers := make([]*peer.Peer, 100)
	for i := 0; i < 100; i++ {
		peers[i] = _randPeer()
	}

	// Testing Update
	for i := 0; i < 10000; i++ {
		p := rt.Update(peers[rand.Intn(len(peers))])
		if p != nil {
			t.Log("evicted peer.")
		}
	}

	for i := 0; i < 100; i++ {
		id := _randID()
		ret := rt.NearestPeers(id, 5)
		if len(ret) == 0 {
			t.Fatal("Failed to find node near ID.")
		}
	}
}