Browse Source

Fix PeerSet.Remove() bug.

pull/39/head
Jae Kwon 10 years ago
parent
commit
85110224b4
3 changed files with 67 additions and 3 deletions
  1. +1
    -1
      p2p/addrbook.go
  2. +3
    -2
      p2p/peer_set.go
  3. +63
    -0
      p2p/peer_set_test.go

+ 1
- 1
p2p/addrbook.go View File

@ -334,7 +334,7 @@ func (a *AddrBook) loadFromFile(filePath string) {
// If doesn't exist, do nothing. // If doesn't exist, do nothing.
_, err := os.Stat(filePath) _, err := os.Stat(filePath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
return
panic(Fmt("File does not exist: %v", filePath))
} }
// Load addrBookJSON{} // Load addrBookJSON{}


+ 3
- 2
p2p/peer_set.go View File

@ -70,12 +70,13 @@ func (ps *PeerSet) Remove(peer *Peer) {
// If it's the last peer, that's an easy special case. // If it's the last peer, that's an easy special case.
if index == len(ps.list)-1 { if index == len(ps.list)-1 {
ps.list = newList ps.list = newList
delete(ps.lookup, peer.Key)
return return
} }
// Move the last item from ps.list to "index" in list. // Move the last item from ps.list to "index" in list.
lastPeer := ps.list[len(ps.list)-1] lastPeer := ps.list[len(ps.list)-1]
lastPeerAddr := lastPeer.mconn.RemoteAddress.String()
lastPeerItem := ps.lookup[lastPeerAddr]
lastPeerKey := lastPeer.Key
lastPeerItem := ps.lookup[lastPeerKey]
newList[index] = lastPeer newList[index] = lastPeer
lastPeerItem.index = index lastPeerItem.index = index
ps.list = newList ps.list = newList


+ 63
- 0
p2p/peer_set_test.go View File

@ -0,0 +1,63 @@
package p2p
import (
"math/rand"
"testing"
. "github.com/tendermint/tendermint/common"
)
// Returns an empty dummy peer
func randPeer() *Peer {
return &Peer{
Key: Fmt("%v.%v.%v.%v:%v", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%10000+80),
}
}
func TestAddRemoveOne(t *testing.T) {
peerSet := NewPeerSet()
peer := randPeer()
added := peerSet.Add(peer)
if !added {
t.Errorf("Failed to add new peer")
}
if peerSet.Size() != 1 {
t.Errorf("Failed to add new peer and increment size")
}
peerSet.Remove(peer)
if peerSet.Has(peer.Key) {
t.Errorf("Failed to remove peer")
}
if peerSet.Size() != 0 {
t.Errorf("Failed to remove peer and decrement size")
}
}
func TestAddRemoveMany(t *testing.T) {
peerSet := NewPeerSet()
peers := []*Peer{}
for i := 0; i < 100; i++ {
peer := randPeer()
added := peerSet.Add(peer)
if !added {
t.Errorf("Failed to add new peer")
}
if peerSet.Size() != i+1 {
t.Errorf("Failed to add new peer and increment size")
}
peers = append(peers, peer)
}
for i, peer := range peers {
peerSet.Remove(peer)
if peerSet.Has(peer.Key) {
t.Errorf("Failed to remove peer")
}
if peerSet.Size() != len(peers)-i-1 {
t.Errorf("Failed to remove peer and decrement size")
}
}
}

Loading…
Cancel
Save