OSDN Git Service

b1025a177419d5e150d3d7326be466666d74dd64
[bytom/vapor.git] / p2p / switch_test.go
1 package p2p
2
3 import (
4         "io/ioutil"
5         "os"
6         "sync"
7         "testing"
8         "time"
9
10         "github.com/davecgh/go-spew/spew"
11         "github.com/tendermint/go-crypto"
12
13         cfg "github.com/vapor/config"
14         dbm "github.com/vapor/database/leveldb"
15         "github.com/vapor/errors"
16         conn "github.com/vapor/p2p/connection"
17 )
18
19 var (
20         testCfg *cfg.Config
21 )
22
23 func init() {
24         testCfg = cfg.DefaultConfig()
25 }
26
27 /*
28 Each peer has one `MConnection` (multiplex connection) instance.
29
30 __multiplex__ *noun* a system or signal involving simultaneous transmission of
31 several messages along a single channel of communication.
32
33 Each `MConnection` handles message transmission on multiple abstract communication
34 `Channel`s.  Each channel has a globally unique byte id.
35 The byte id and the relative priorities of each `Channel` are configured upon
36 initialization of the connection.
37
38 There are two methods for sending messages:
39         func (m MConnection) Send(chID byte, msgBytes []byte) bool {}
40         func (m MConnection) TrySend(chID byte, msgBytes []byte}) bool {}
41
42 `Send(chID, msgBytes)` is a blocking call that waits until `msg` is
43 successfully queued for the channel with the given id byte `chID`, or until the
44 request times out.  The message `msg` is serialized using Go-Amino.
45
46 `TrySend(chID, msgBytes)` is a nonblocking call that returns false if the
47 channel's queue is full.
48
49 Inbound message bytes are handled with an onReceive callback function.
50 */
51 type PeerMessage struct {
52         PeerID  string
53         Bytes   []byte
54         Counter int
55 }
56
57 type TestReactor struct {
58         BaseReactor
59
60         mtx          sync.Mutex
61         channels     []*conn.ChannelDescriptor
62         logMessages  bool
63         msgsCounter  int
64         msgsReceived map[byte][]PeerMessage
65 }
66
67 func NewTestReactor(channels []*conn.ChannelDescriptor, logMessages bool) *TestReactor {
68         tr := &TestReactor{
69                 channels:     channels,
70                 logMessages:  logMessages,
71                 msgsReceived: make(map[byte][]PeerMessage),
72         }
73         tr.BaseReactor = *NewBaseReactor("TestReactor", tr)
74
75         return tr
76 }
77
78 // GetChannels implements Reactor
79 func (tr *TestReactor) GetChannels() []*conn.ChannelDescriptor {
80         return tr.channels
81 }
82
83 // OnStart implements BaseService
84 func (tr *TestReactor) OnStart() error {
85         tr.BaseReactor.OnStart()
86         return nil
87 }
88
89 // OnStop implements BaseService
90 func (tr *TestReactor) OnStop() {
91         tr.BaseReactor.OnStop()
92 }
93
94 // AddPeer implements Reactor by sending our state to peer.
95 func (tr *TestReactor) AddPeer(peer *Peer) error {
96         return nil
97 }
98
99 // RemovePeer implements Reactor by removing peer from the pool.
100 func (tr *TestReactor) RemovePeer(peer *Peer, reason interface{}) {
101 }
102
103 // Receive implements Reactor by handling 4 types of messages (look below).
104 func (tr *TestReactor) Receive(chID byte, peer *Peer, msgBytes []byte) {
105         if tr.logMessages {
106                 tr.mtx.Lock()
107                 defer tr.mtx.Unlock()
108                 tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.ID(), msgBytes, tr.msgsCounter})
109                 tr.msgsCounter++
110         }
111 }
112
113 func initSwitchFunc(sw *Switch) *Switch {
114         // Make two reactors of two channels each
115         sw.AddReactor("foo", NewTestReactor([]*conn.ChannelDescriptor{
116                 {ID: byte(0x00), Priority: 10},
117                 {ID: byte(0x01), Priority: 10},
118         }, true))
119         sw.AddReactor("bar", NewTestReactor([]*conn.ChannelDescriptor{
120                 {ID: byte(0x02), Priority: 10},
121                 {ID: byte(0x03), Priority: 10},
122         }, true))
123
124         return sw
125 }
126
127 //Test connect self.
128 func TestFiltersOutItself(t *testing.T) {
129         dirPath, err := ioutil.TempDir(".", "")
130         if err != nil {
131                 t.Fatal(err)
132         }
133         defer os.RemoveAll(dirPath)
134
135         testDB := dbm.NewDB("testdb", "leveldb", dirPath)
136         cfg := *testCfg
137         cfg.P2P.ListenAddress = "127.0.1.1:0"
138         swPrivKey := crypto.GenPrivKeyEd25519()
139         cfg.P2P.PrivateKey = swPrivKey.String()
140         s1 := MakeSwitch(&cfg, testDB, swPrivKey, initSwitchFunc)
141         s1.Start()
142         defer s1.Stop()
143
144         // simulate s1 having a public key and creating a remote peer with the same key
145         rpCfg := *testCfg
146         rp := &remotePeer{PrivKey: s1.nodePrivKey, Config: &rpCfg}
147         rp.Start()
148         defer rp.Stop()
149         if err = s1.DialPeerWithAddress(rp.addr); errors.Root(err) != ErrConnectSelf {
150                 t.Fatal(err)
151         }
152
153         //S1 dialing itself ip address
154         addr := NewNetAddress(s1.listeners[0].(*DefaultListener).NetListener().Addr())
155
156         if err := s1.DialPeerWithAddress(addr); errors.Root(err) != ErrConnectSelf {
157                 t.Fatal(err)
158         }
159 }
160
161 func TestDialBannedPeer(t *testing.T) {
162         dirPath, err := ioutil.TempDir(".", "")
163         if err != nil {
164                 t.Fatal(err)
165         }
166         defer os.RemoveAll(dirPath)
167
168         testDB := dbm.NewDB("testdb", "leveldb", dirPath)
169         cfg := *testCfg
170         cfg.P2P.ListenAddress = "127.0.1.1:0"
171         swPrivKey := crypto.GenPrivKeyEd25519()
172         cfg.P2P.PrivateKey = swPrivKey.String()
173         s1 := MakeSwitch(&cfg, testDB, swPrivKey, initSwitchFunc)
174         s1.Start()
175         defer s1.Stop()
176
177         rpCfg := *testCfg
178         rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: &rpCfg}
179         rp.Start()
180         defer rp.Stop()
181         s1.AddBannedPeer(rp.addr.IP.String())
182         if err := s1.DialPeerWithAddress(rp.addr); errors.Root(err) != ErrConnectBannedPeer {
183                 t.Fatal(err)
184         }
185
186         s1.delBannedPeer(rp.addr.IP.String())
187         if err := s1.DialPeerWithAddress(rp.addr); err != nil {
188                 t.Fatal(err)
189         }
190 }
191
192 func TestDuplicateOutBoundPeer(t *testing.T) {
193         dirPath, err := ioutil.TempDir(".", "")
194         if err != nil {
195                 t.Fatal(err)
196         }
197         defer os.RemoveAll(dirPath)
198
199         testDB := dbm.NewDB("testdb", "leveldb", dirPath)
200         cfg := *testCfg
201         cfg.P2P.ListenAddress = "127.0.1.1:0"
202         swPrivKey := crypto.GenPrivKeyEd25519()
203         cfg.P2P.PrivateKey = swPrivKey.String()
204         s1 := MakeSwitch(&cfg, testDB, swPrivKey, initSwitchFunc)
205         s1.Start()
206         defer s1.Stop()
207
208         rpCfg := *testCfg
209         rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: &rpCfg}
210         rp.Start()
211         defer rp.Stop()
212
213         if err = s1.DialPeerWithAddress(rp.addr); err != nil {
214                 t.Fatal(err)
215         }
216
217         if err = s1.DialPeerWithAddress(rp.addr); errors.Root(err) != ErrDuplicatePeer {
218                 t.Fatal(err)
219         }
220 }
221
222 func TestDuplicateInBoundPeer(t *testing.T) {
223         dirPath, err := ioutil.TempDir(".", "")
224         if err != nil {
225                 t.Fatal(err)
226         }
227         defer os.RemoveAll(dirPath)
228
229         testDB := dbm.NewDB("testdb", "leveldb", dirPath)
230         cfg := *testCfg
231         cfg.P2P.ListenAddress = "127.0.1.1:0"
232         swPrivKey := crypto.GenPrivKeyEd25519()
233         cfg.P2P.PrivateKey = swPrivKey.String()
234         s1 := MakeSwitch(&cfg, testDB, swPrivKey, initSwitchFunc)
235         s1.Start()
236         defer s1.Stop()
237
238         inpCfg := *testCfg
239         inp := &inboundPeer{PrivKey: crypto.GenPrivKeyEd25519(), config: &inpCfg}
240         addr := NewNetAddress(s1.listeners[0].(*DefaultListener).NetListener().Addr())
241         if err != nil {
242                 t.Fatal(err)
243         }
244         go inp.dial(addr)
245
246         inp1Cfg := *testCfg
247         inp1 := &inboundPeer{PrivKey: inp.PrivKey, config: &inp1Cfg}
248         go inp1.dial(addr)
249
250         time.Sleep(1 * time.Second)
251         if _, outbound, inbound, dialing := s1.NumPeers(); outbound+inbound+dialing != 1 {
252                 t.Fatal("TestDuplicateInBoundPeer peer size error want 1, got:", outbound, inbound, dialing, spew.Sdump(s1.peers.lookup))
253         }
254 }
255
256 func TestAddInboundPeer(t *testing.T) {
257         dirPath, err := ioutil.TempDir(".", "")
258         if err != nil {
259                 t.Fatal(err)
260         }
261         defer os.RemoveAll(dirPath)
262
263         testDB := dbm.NewDB("testdb", "leveldb", dirPath)
264         cfg := *testCfg
265         cfg.P2P.MaxNumPeers = 2
266         cfg.P2P.ListenAddress = "127.0.1.1:0"
267         swPrivKey := crypto.GenPrivKeyEd25519()
268         cfg.P2P.PrivateKey = swPrivKey.String()
269         s1 := MakeSwitch(&cfg, testDB, swPrivKey, initSwitchFunc)
270         s1.Start()
271         defer s1.Stop()
272
273         inpCfg := *testCfg
274         inpPrivKey := crypto.GenPrivKeyEd25519()
275         inpCfg.P2P.PrivateKey = inpPrivKey.String()
276         inp := &inboundPeer{PrivKey: inpPrivKey, config: &inpCfg}
277         addr := NewNetAddress(s1.listeners[0].(*DefaultListener).NetListener().Addr())
278         if err != nil {
279                 t.Fatal(err)
280         }
281         go inp.dial(addr)
282
283         rpCfg := *testCfg
284         rpPrivKey := crypto.GenPrivKeyEd25519()
285         rpCfg.P2P.PrivateKey = rpPrivKey.String()
286         rp := &remotePeer{PrivKey: rpPrivKey, Config: &rpCfg}
287         rp.Start()
288         defer rp.Stop()
289
290         if err := s1.DialPeerWithAddress(rp.addr); err != nil {
291                 t.Fatal(err)
292         }
293
294         inp2Cfg := *testCfg
295         inp2PrivKey := crypto.GenPrivKeyEd25519()
296         inp2Cfg.P2P.PrivateKey = inp2PrivKey.String()
297         inp2 := &inboundPeer{PrivKey: inp2PrivKey, config: &inp2Cfg}
298
299         go inp2.dial(addr)
300
301         time.Sleep(1 * time.Second)
302         if _, outbound, inbound, dialing := s1.NumPeers(); outbound+inbound+dialing != 2 {
303                 t.Fatal("TestAddInboundPeer peer size error want 2 got:", spew.Sdump(s1.peers.lookup))
304         }
305 }
306
307 func TestStopPeer(t *testing.T) {
308         dirPath, err := ioutil.TempDir(".", "")
309         if err != nil {
310                 t.Fatal(err)
311         }
312         defer os.RemoveAll(dirPath)
313
314         testDB := dbm.NewDB("testdb", "leveldb", dirPath)
315         cfg := *testCfg
316         cfg.P2P.MaxNumPeers = 2
317         cfg.P2P.ListenAddress = "127.0.1.1:0"
318         swPrivKey := crypto.GenPrivKeyEd25519()
319         cfg.P2P.PrivateKey = swPrivKey.String()
320         s1 := MakeSwitch(&cfg, testDB, swPrivKey, initSwitchFunc)
321         s1.Start()
322         defer s1.Stop()
323
324         inpCfg := *testCfg
325         inpPrivKey := crypto.GenPrivKeyEd25519()
326         inpCfg.P2P.PrivateKey = inpPrivKey.String()
327         inp := &inboundPeer{PrivKey: inpPrivKey, config: &inpCfg}
328         addr := NewNetAddress(s1.listeners[0].(*DefaultListener).NetListener().Addr())
329         if err != nil {
330                 t.Fatal(err)
331         }
332         go inp.dial(addr)
333
334         rpCfg := *testCfg
335         rpPrivKey := crypto.GenPrivKeyEd25519()
336         rpCfg.P2P.PrivateKey = rpPrivKey.String()
337         rp := &remotePeer{PrivKey: rpPrivKey, Config: &rpCfg}
338         rp.Start()
339         defer rp.Stop()
340
341         if err := s1.DialPeerWithAddress(rp.addr); err != nil {
342                 t.Fatal(err)
343         }
344         time.Sleep(1 * time.Second)
345         if _, outbound, inbound, dialing := s1.NumPeers(); outbound+inbound+dialing != 2 {
346                 t.Fatal("TestStopPeer peer size error want 2,got:", spew.Sdump(s1.peers.lookup))
347         }
348
349         s1.StopPeerGracefully(s1.peers.list[0].Key)
350         if _, outbound, inbound, dialing := s1.NumPeers(); outbound+inbound+dialing != 1 {
351                 t.Fatal("TestStopPeer peer size error,want 1,got:", spew.Sdump(s1.peers.lookup))
352         }
353
354         s1.StopPeerForError(s1.peers.list[0], "stop for test")
355         if _, outbound, inbound, dialing := s1.NumPeers(); outbound+inbound+dialing != 0 {
356                 t.Fatal("TestStopPeer peer size error,want 0, got:", spew.Sdump(s1.peers.lookup))
357         }
358 }