@cryptotaxi247 / kubo / commits / d6e8e55f0

rmv old swarm

Juan Batiz-Benet committed Sep 14, 2014 at 01:03 UTC d6e8e55f00a6b9986b1688c19f7a3fb48b2ec05a
8 files changed -939
swarm/interface.go deleted
-20
@@ -1,20 +0,0 @@
1 -package swarm
2 -
3 -import (
4 - peer "github.com/jbenet/go-ipfs/peer"
5 - u "github.com/jbenet/go-ipfs/util"
6 -
7 - ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
8 -)
9 -
10 -type Network interface {
11 - GetPeer(u.Key) *peer.Peer
12 - Listen() error
13 - ConnectNew(*ma.Multiaddr) (*peer.Peer, error)
14 - GetConnection(id peer.ID, addr *ma.Multiaddr) (*peer.Peer, error)
15 - Error(error)
16 - GetErrChan() chan error
17 - GetChannel(PBWrapper_MessageType) *Chan
18 - Close()
19 - CloseConnection(*peer.Peer) error
20 -}
swarm/mes_listener.go deleted
-123
@@ -1,123 +0,0 @@
1 -package swarm
2 -
3 -import (
4 - crand "crypto/rand"
5 - "sync"
6 - "time"
7 -
8 - u "github.com/jbenet/go-ipfs/util"
9 -)
10 -
11 -type MessageListener struct {
12 - listeners map[string]*listenInfo
13 - haltchan chan struct{}
14 - unlist chan string
15 - nlist chan *listenInfo
16 - send chan *respMes
17 -}
18 -
19 -// GenerateMessageID creates and returns a new message ID
20 -func GenerateMessageID() string {
21 - buf := make([]byte, 16)
22 - crand.Read(buf)
23 - return string(buf)
24 -}
25 -
26 -// The listen info struct holds information about a message that is being waited for
27 -type listenInfo struct {
28 - // Responses matching the listen ID will be sent through resp
29 - resp chan *Message
30 -
31 - // count is the number of responses to listen for
32 - count int
33 -
34 - // eol is the time at which this listener will expire
35 - eol time.Time
36 -
37 - // sendlock is used to prevent conditions where we try to send on the resp
38 - // channel as its being closed by a timeout in another thread
39 - sendLock sync.Mutex
40 -
41 - closed bool
42 -
43 - id string
44 -}
45 -
46 -func NewMessageListener() *MessageListener {
47 - ml := new(MessageListener)
48 - ml.haltchan = make(chan struct{})
49 - ml.listeners = make(map[string]*listenInfo)
50 - ml.nlist = make(chan *listenInfo, 16)
51 - ml.send = make(chan *respMes, 16)
52 - ml.unlist = make(chan string, 16)
53 - go ml.run()
54 - return ml
55 -}
56 -
57 -func (ml *MessageListener) Listen(id string, count int, timeout time.Duration) <-chan *Message {
58 - li := new(listenInfo)
59 - li.count = count
60 - li.eol = time.Now().Add(timeout)
61 - li.resp = make(chan *Message, count)
62 - li.id = id
63 - ml.nlist <- li
64 - return li.resp
65 -}
66 -
67 -func (ml *MessageListener) Unlisten(id string) {
68 - ml.unlist <- id
69 -}
70 -
71 -type respMes struct {
72 - id string
73 - mes *Message
74 -}
75 -
76 -func (ml *MessageListener) Respond(id string, mes *Message) {
77 - ml.send <- &respMes{
78 - id: id,
79 - mes: mes,
80 - }
81 -}
82 -
83 -func (ml *MessageListener) Halt() {
84 - ml.haltchan <- struct{}{}
85 -}
86 -
87 -func (ml *MessageListener) run() {
88 - for {
89 - select {
90 - case <-ml.haltchan:
91 - return
92 - case id := <-ml.unlist:
93 - trg, ok := ml.listeners[id]
94 - if !ok {
95 - continue
96 - }
97 - close(trg.resp)
98 - delete(ml.listeners, id)
99 - case li := <-ml.nlist:
100 - ml.listeners[li.id] = li
101 - case s := <-ml.send:
102 - trg, ok := ml.listeners[s.id]
103 - if !ok {
104 - u.DOut("Send with no listener.")
105 - continue
106 - }
107 -
108 - if time.Now().After(trg.eol) {
109 - close(trg.resp)
110 - delete(ml.listeners, s.id)
111 - continue
112 - }
113 -
114 - trg.resp <- s.mes
115 - trg.count--
116 -
117 - if trg.count == 0 {
118 - close(trg.resp)
119 - delete(ml.listeners, s.id)
120 - }
121 - }
122 - }
123 -}
swarm/mes_listener_test.go deleted
-32
@@ -1,32 +0,0 @@
1 -package swarm
2 -
3 -import (
4 - "testing"
5 - "time"
6 -
7 - peer "github.com/jbenet/go-ipfs/peer"
8 -)
9 -
10 -// Ensure that the Message Listeners basic functionality works
11 -func TestMessageListener(t *testing.T) {
12 - ml := NewMessageListener()
13 - a := GenerateMessageID()
14 - resp := ml.Listen(a, 1, time.Minute)
15 -
16 - pmes := new(PBWrapper)
17 - pmes.Message = []byte("Hello")
18 - pmes.Type = new(PBWrapper_MessageType)
19 - mes := NewMessage(new(peer.Peer), pmes)
20 -
21 - go ml.Respond(a, mes)
22 -
23 - del := time.After(time.Millisecond * 100)
24 - select {
25 - case get := <-resp:
26 - if string(get.Data) != string(mes.Data) {
27 - t.Fatal("Something got really messed up")
28 - }
29 - case <-del:
30 - t.Fatal("Waiting on message response timed out.")
31 - }
32 -}
swarm/mes_wrapper.pb.go deleted
-85
@@ -1,85 +0,0 @@
1 -// Code generated by protoc-gen-go.
2 -// source: mes_wrapper.proto
3 -// DO NOT EDIT!
4 -
5 -/*
6 -Package swarm is a generated protocol buffer package.
7 -
8 -It is generated from these files:
9 - mes_wrapper.proto
10 -
11 -It has these top-level messages:
12 - PBWrapper
13 -*/
14 -package swarm
15 -
16 -import proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
17 -import math "math"
18 -
19 -// Reference imports to suppress errors if they are not otherwise used.
20 -var _ = proto.Marshal
21 -var _ = math.Inf
22 -
23 -type PBWrapper_MessageType int32
24 -
25 -const (
26 - PBWrapper_TEST PBWrapper_MessageType = 0
27 - PBWrapper_DHT_MESSAGE PBWrapper_MessageType = 1
28 - PBWrapper_BITSWAP PBWrapper_MessageType = 2
29 -)
30 -
31 -var PBWrapper_MessageType_name = map[int32]string{
32 - 0: "TEST",
33 - 1: "DHT_MESSAGE",
34 - 2: "BITSWAP",
35 -}
36 -var PBWrapper_MessageType_value = map[string]int32{
37 - "TEST": 0,
38 - "DHT_MESSAGE": 1,
39 - "BITSWAP": 2,
40 -}
41 -
42 -func (x PBWrapper_MessageType) Enum() *PBWrapper_MessageType {
43 - p := new(PBWrapper_MessageType)
44 - *p = x
45 - return p
46 -}
47 -func (x PBWrapper_MessageType) String() string {
48 - return proto.EnumName(PBWrapper_MessageType_name, int32(x))
49 -}
50 -func (x *PBWrapper_MessageType) UnmarshalJSON(data []byte) error {
51 - value, err := proto.UnmarshalJSONEnum(PBWrapper_MessageType_value, data, "PBWrapper_MessageType")
52 - if err != nil {
53 - return err
54 - }
55 - *x = PBWrapper_MessageType(value)
56 - return nil
57 -}
58 -
59 -type PBWrapper struct {
60 - Type *PBWrapper_MessageType `protobuf:"varint,1,req,enum=swarm.PBWrapper_MessageType" json:"Type,omitempty"`
61 - Message []byte `protobuf:"bytes,2,req" json:"Message,omitempty"`
62 - XXX_unrecognized []byte `json:"-"`
63 -}
64 -
65 -func (m *PBWrapper) Reset() { *m = PBWrapper{} }
66 -func (m *PBWrapper) String() string { return proto.CompactTextString(m) }
67 -func (*PBWrapper) ProtoMessage() {}
68 -
69 -func (m *PBWrapper) GetType() PBWrapper_MessageType {
70 - if m != nil && m.Type != nil {
71 - return *m.Type
72 - }
73 - return PBWrapper_TEST
74 -}
75 -
76 -func (m *PBWrapper) GetMessage() []byte {
77 - if m != nil {
78 - return m.Message
79 - }
80 - return nil
81 -}
82 -
83 -func init() {
84 - proto.RegisterEnum("swarm.PBWrapper_MessageType", PBWrapper_MessageType_name, PBWrapper_MessageType_value)
85 -}
swarm/mes_wrapper.proto deleted
-12
@@ -1,12 +0,0 @@
1 -package swarm;
2 -
3 -message PBWrapper {
4 - enum MessageType {
5 - TEST = 0;
6 - DHT_MESSAGE = 1;
7 - BITSWAP = 2;
8 - }
9 -
10 - required MessageType Type = 1;
11 - required bytes Message = 2;
12 -}
swarm/swarm.go deleted
-507
@@ -1,507 +0,0 @@
1 -package swarm
2 -
3 -import (
4 - "errors"
5 - "fmt"
6 - "net"
7 - "sync"
8 -
9 - proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
10 - ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
11 - ident "github.com/jbenet/go-ipfs/identify"
12 - peer "github.com/jbenet/go-ipfs/peer"
13 - u "github.com/jbenet/go-ipfs/util"
14 -)
15 -
16 -var ErrAlreadyOpen = errors.New("Error: Connection to this peer already open.")
17 -
18 -// Message represents a packet of information sent to or received from a
19 -// particular Peer.
20 -type Message struct {
21 - // To or from, depending on direction.
22 - Peer *peer.Peer
23 -
24 - // Opaque data
25 - Data []byte
26 -}
27 -
28 -// Cleaner looking helper function to make a new message struct
29 -func NewMessage(p *peer.Peer, data proto.Message) *Message {
30 - bytes, err := proto.Marshal(data)
31 - if err != nil {
32 - u.PErr("%v\n", err.Error())
33 - return nil
34 - }
35 - return &Message{
36 - Peer: p,
37 - Data: bytes,
38 - }
39 -}
40 -
41 -// Chan is a swarm channel, which provides duplex communication and errors.
42 -type Chan struct {
43 - Outgoing chan *Message
44 - Incoming chan *Message
45 - Errors chan error
46 - Close chan bool
47 -}
48 -
49 -// NewChan constructs a Chan instance, with given buffer size bufsize.
50 -func NewChan(bufsize int) *Chan {
51 - return &Chan{
52 - Outgoing: make(chan *Message, bufsize),
53 - Incoming: make(chan *Message, bufsize),
54 - Errors: make(chan error, bufsize),
55 - Close: make(chan bool, bufsize),
56 - }
57 -}
58 -
59 -// Contains a set of errors mapping to each of the swarms addresses
60 -// that were listened on
61 -type SwarmListenErr struct {
62 - Errors []error
63 -}
64 -
65 -func (se *SwarmListenErr) Error() string {
66 - if se == nil {
67 - return "<nil error>"
68 - }
69 - var out string
70 - for i, v := range se.Errors {
71 - if v != nil {
72 - out += fmt.Sprintf("%d: %s\n", i, v)
73 - }
74 - }
75 - return out
76 -}
77 -
78 -// Swarm is a connection muxer, allowing connections to other peers to
79 -// be opened and closed, while still using the same Chan for all
80 -// communication. The Chan sends/receives Messages, which note the
81 -// destination or source Peer.
82 -type Swarm struct {
83 - Chan *Chan
84 - conns ConnMap
85 - connsLock sync.RWMutex
86 -
87 - filterChans map[PBWrapper_MessageType]*Chan
88 - toFilter chan *Message
89 - newFilters chan *newFilterInfo
90 -
91 - local *peer.Peer
92 - listeners []net.Listener
93 - haltroute chan struct{}
94 -}
95 -
96 -// NewSwarm constructs a Swarm, with a Chan.
97 -func NewSwarm(local *peer.Peer) *Swarm {
98 - s := &Swarm{
99 - Chan: NewChan(10),
100 - conns: ConnMap{},
101 - local: local,
102 - filterChans: make(map[PBWrapper_MessageType]*Chan),
103 - toFilter: make(chan *Message, 32),
104 - newFilters: make(chan *newFilterInfo),
105 - haltroute: make(chan struct{}),
106 - }
107 - go s.routeMessages()
108 - go s.fanOut()
109 - return s
110 -}
111 -
112 -// Open listeners for each network the swarm should listen on
113 -func (s *Swarm) Listen() error {
114 - var ret_err *SwarmListenErr
115 - for i, addr := range s.local.Addresses {
116 - err := s.connListen(addr)
117 - if err != nil {
118 - if ret_err == nil {
119 - ret_err = new(SwarmListenErr)
120 - ret_err.Errors = make([]error, len(s.local.Addresses))
121 - }
122 - ret_err.Errors[i] = err
123 - u.PErr("Failed to listen on: %s [%s]", addr, err)
124 - }
125 - }
126 - if ret_err == nil {
127 - return nil
128 - }
129 - return ret_err
130 -}
131 -
132 -// Listen for new connections on the given multiaddr
133 -func (s *Swarm) connListen(maddr *ma.Multiaddr) error {
134 - netstr, addr, err := maddr.DialArgs()
135 - if err != nil {
136 - return err
137 - }
138 -
139 - list, err := net.Listen(netstr, addr)
140 - if err != nil {
141 - return err
142 - }
143 -
144 - // NOTE: this may require a lock around it later. currently, only run on setup
145 - s.listeners = append(s.listeners, list)
146 -
147 - // Accept and handle new connections on this listener until it errors
148 - go func() {
149 - for {
150 - nconn, err := list.Accept()
151 - if err != nil {
152 - e := fmt.Errorf("Failed to accept connection: %s - %s [%s]",
153 - netstr, addr, err)
154 - go func() { s.Chan.Errors <- e }()
155 - return
156 - }
157 - go s.handleNewConn(nconn)
158 - }
159 - }()
160 -
161 - return nil
162 -}
163 -
164 -// Handle getting ID from this peer and adding it into the map
165 -func (s *Swarm) handleNewConn(nconn net.Conn) {
166 - p := new(peer.Peer)
167 -
168 - conn := &Conn{
169 - Peer: p,
170 - Addr: nil,
171 - Conn: nconn,
172 - }
173 - newConnChans(conn)
174 -
175 - sin, sout, err := ident.Handshake(s.local, p, conn.Incoming.MsgChan, conn.Outgoing.MsgChan)
176 - if err != nil {
177 - u.PErr("%v\n", err.Error())
178 - conn.Close()
179 - return
180 - }
181 -
182 - // Get address to contact remote peer from
183 - addr := <-sin
184 - maddr, err := ma.NewMultiaddr(string(addr))
185 - if err != nil {
186 - u.PErr("Got invalid address from peer.")
187 - s.Error(err)
188 - return
189 - }
190 - p.AddAddress(maddr)
191 -
192 - conn.secIn = sin
193 - conn.secOut = sout
194 -
195 - err = s.StartConn(conn)
196 - if err != nil {
197 - s.Error(err)
198 - }
199 -}
200 -
201 -// Close closes a swarm.
202 -func (s *Swarm) Close() {
203 - s.connsLock.RLock()
204 - l := len(s.conns)
205 - s.connsLock.RUnlock()
206 -
207 - for i := 0; i < l; i++ {
208 - s.Chan.Close <- true // fan ins
209 - }
210 - s.Chan.Close <- true // fan out
211 - s.Chan.Close <- true // listener
212 -
213 - for _, list := range s.listeners {
214 - list.Close()
215 - }
216 -
217 - s.haltroute <- struct{}{}
218 -
219 - for _, filter := range s.filterChans {
220 - filter.Close <- true
221 - }
222 -}
223 -
224 -// Dial connects to a peer.
225 -//
226 -// The idea is that the client of Swarm does not need to know what network
227 -// the connection will happen over. Swarm can use whichever it choses.
228 -// This allows us to use various transport protocols, do NAT traversal/relay,
229 -// etc. to achive connection.
230 -//
231 -// For now, Dial uses only TCP. This will be extended.
232 -func (s *Swarm) Dial(peer *peer.Peer) (*Conn, error, bool) {
233 - k := peer.Key()
234 -
235 - // check if we already have an open connection first
236 - s.connsLock.RLock()
237 - conn, found := s.conns[k]
238 - s.connsLock.RUnlock()
239 - if found {
240 - return conn, nil, true
241 - }
242 -
243 - // open connection to peer
244 - conn, err := Dial("tcp", peer)
245 - if err != nil {
246 - return nil, err, false
247 - }
248 -
249 - return conn, nil, false
250 -}
251 -
252 -// StartConn adds the passed in connection to its peerMap and starts
253 -// the fanIn routine for that connection
254 -func (s *Swarm) StartConn(conn *Conn) error {
255 - if conn == nil {
256 - return errors.New("Tried to start nil connection.")
257 - }
258 -
259 - u.DOut("Starting connection: %s\n", conn.Peer.Key().Pretty())
260 - // add to conns
261 - s.connsLock.Lock()
262 - if _, ok := s.conns[conn.Peer.Key()]; ok {
263 - s.connsLock.Unlock()
264 - return ErrAlreadyOpen
265 - }
266 - s.conns[conn.Peer.Key()] = conn
267 - s.connsLock.Unlock()
268 -
269 - // kick off reader goroutine
270 - go s.fanIn(conn)
271 - return nil
272 -}
273 -
274 -// Handles the unwrapping + sending of messages to the right connection.
275 -func (s *Swarm) fanOut() {
276 - for {
277 - select {
278 - case <-s.Chan.Close:
279 - return // told to close.
280 - case msg, ok := <-s.Chan.Outgoing:
281 - if !ok {
282 - return
283 - }
284 -
285 - if len(msg.Data) > MaxMessageSize {
286 - s.Error(fmt.Errorf("Exceeded max message size! (tried to send len = %d)", len(msg.Data)))
287 - }
288 -
289 - s.connsLock.RLock()
290 - conn, found := s.conns[msg.Peer.Key()]
291 - s.connsLock.RUnlock()
292 -
293 - if !found {
294 - e := fmt.Errorf("Sent msg to peer without open conn: %v",
295 - msg.Peer)
296 - s.Chan.Errors <- e
297 - continue
298 - }
299 -
300 - // queue it in the connection's buffer
301 - conn.secOut <- msg.Data
302 - }
303 - }
304 -}
305 -
306 -// Handles the receiving + wrapping of messages, per conn.
307 -// Consider using reflect.Select with one goroutine instead of n.
308 -func (s *Swarm) fanIn(conn *Conn) {
309 - for {
310 - select {
311 - case <-s.Chan.Close:
312 - // close Conn.
313 - conn.Close()
314 - goto out
315 -
316 - case <-conn.Closed:
317 - goto out
318 -
319 - case data, ok := <-conn.secIn:
320 - if !ok {
321 - e := fmt.Errorf("Error retrieving from conn: %v", conn.Peer.Key().Pretty())
322 - s.Chan.Errors <- e
323 - goto out
324 - }
325 -
326 - msg := &Message{Peer: conn.Peer, Data: data}
327 - s.toFilter <- msg
328 - }
329 - }
330 -out:
331 -
332 - s.connsLock.Lock()
333 - delete(s.conns, conn.Peer.Key())
334 - s.connsLock.Unlock()
335 -}
336 -
337 -type newFilterInfo struct {
338 - Type PBWrapper_MessageType
339 - resp chan *Chan
340 -}
341 -
342 -func (s *Swarm) routeMessages() {
343 - for {
344 - select {
345 - case mes, ok := <-s.toFilter:
346 - if !ok {
347 - return
348 - }
349 - wrapper, err := Unwrap(mes.Data)
350 - if err != nil {
351 - u.PErr("error in route messages: %s\n", err)
352 - }
353 -
354 - ch, ok := s.filterChans[PBWrapper_MessageType(wrapper.GetType())]
355 - if !ok {
356 - u.PErr("Received message with invalid type: %d\n", wrapper.GetType())
357 - continue
358 - }
359 -
360 - mes.Data = wrapper.GetMessage()
361 - ch.Incoming <- mes
362 - case gchan := <-s.newFilters:
363 - nch, ok := s.filterChans[gchan.Type]
364 - if !ok {
365 - nch = NewChan(16)
366 - s.filterChans[gchan.Type] = nch
367 - go s.muxChan(nch, gchan.Type)
368 - }
369 - gchan.resp <- nch
370 - case <-s.haltroute:
371 - return
372 - }
373 - }
374 -}
375 -
376 -func (s *Swarm) muxChan(ch *Chan, typ PBWrapper_MessageType) {
377 - for {
378 - select {
379 - case <-ch.Close:
380 - return
381 - case mes := <-ch.Outgoing:
382 - data, err := Wrap(mes.Data, typ)
383 - if err != nil {
384 - u.PErr("muxChan error: %s\n", err)
385 - continue
386 - }
387 - mes.Data = data
388 - s.Chan.Outgoing <- mes
389 - }
390 - }
391 -}
392 -
393 -// GetPeer returns the peer in the swarm with given key id.
394 -func (s *Swarm) GetPeer(key u.Key) *peer.Peer {
395 - s.connsLock.RLock()
396 - defer s.connsLock.RUnlock()
397 - conn, found := s.conns[key]
398 - if !found {
399 - return nil
400 - }
401 - return conn.Peer
402 -}
403 -
404 -// GetConnection will check if we are already connected to the peer in question
405 -// and only open a new connection if we arent already
406 -func (s *Swarm) GetConnection(id peer.ID, addr *ma.Multiaddr) (*peer.Peer, error) {
407 - p := &peer.Peer{
408 - ID: id,
409 - Addresses: []*ma.Multiaddr{addr},
410 - }
411 -
412 - if id.Equal(s.local.ID) {
413 - return nil, errors.New("Attempted connection to self!")
414 - }
415 -
416 - conn, err, reused := s.Dial(p)
417 - if err != nil {
418 - return nil, err
419 - }
420 -
421 - if reused {
422 - return p, nil
423 - }
424 -
425 - err = s.handleDialedCon(conn)
426 - return conn.Peer, err
427 -}
428 -
429 -// Handle performing a handshake on a new connection and ensuring proper forward communication
430 -func (s *Swarm) handleDialedCon(conn *Conn) error {
431 - sin, sout, err := ident.Handshake(s.local, conn.Peer, conn.Incoming.MsgChan, conn.Outgoing.MsgChan)
432 - if err != nil {
433 - return err
434 - }
435 -
436 - // Send node an address that you can be reached on
437 - myaddr := s.local.NetAddress("tcp")
438 - mastr, err := myaddr.String()
439 - if err != nil {
440 - return errors.New("No local address to send to peer.")
441 - }
442 -
443 - sout <- []byte(mastr)
444 -
445 - conn.secIn = sin
446 - conn.secOut = sout
447 -
448 - s.StartConn(conn)
449 -
450 - return nil
451 -}
452 -
453 -// ConnectNew is for connecting to a peer when you dont know their ID,
454 -// Should only be used when you are sure that you arent already connected to peer in question
455 -func (s *Swarm) ConnectNew(addr *ma.Multiaddr) (*peer.Peer, error) {
456 - if addr == nil {
457 - return nil, errors.New("nil Multiaddr passed to swarm.Connect()")
458 - }
459 - npeer := new(peer.Peer)
460 - npeer.AddAddress(addr)
461 -
462 - conn, err := Dial("tcp", npeer)
463 - if err != nil {
464 - return nil, err
465 - }
466 -
467 - err = s.handleDialedCon(conn)
468 - return npeer, err
469 -}
470 -
471 -// CloseConnection removes a given peer from swarm + closes the connection
472 -func (s *Swarm) CloseConnection(p *peer.Peer) error {
473 - u.DOut("Dropping peer: [%s]\n", p.ID.Pretty())
474 - s.connsLock.RLock()
475 - conn, found := s.conns[u.Key(p.ID)]
476 - s.connsLock.RUnlock()
477 - if !found {
478 - return u.ErrNotFound
479 - }
480 -
481 - s.connsLock.Lock()
482 - delete(s.conns, u.Key(p.ID))
483 - s.connsLock.Unlock()
484 -
485 - return conn.Close()
486 -}
487 -
488 -func (s *Swarm) Error(e error) {
489 - s.Chan.Errors <- e
490 -}
491 -
492 -func (s *Swarm) GetErrChan() chan error {
493 - return s.Chan.Errors
494 -}
495 -
496 -func (s *Swarm) GetChannel(typ PBWrapper_MessageType) *Chan {
497 - nfi := &newFilterInfo{
498 - Type: typ,
499 - resp: make(chan *Chan),
500 - }
501 - s.newFilters <- nfi
502 -
503 - return <-nfi.resp
504 -}
505 -
506 -// Temporary to ensure that the Swarm always matches the Network interface as we are changing it
507 -var _ Network = &Swarm{}
swarm/swarm_test.go deleted
-136
@@ -1,136 +0,0 @@
1 -package swarm
2 -
3 -import (
4 - "fmt"
5 - "net"
6 - "testing"
7 -
8 - msgio "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-msgio"
9 - peer "github.com/jbenet/go-ipfs/peer"
10 - u "github.com/jbenet/go-ipfs/util"
11 -)
12 -
13 -func pingListen(listener *net.TCPListener, peer *peer.Peer) {
14 - for {
15 - c, err := listener.Accept()
16 - if err == nil {
17 - fmt.Println("accepted")
18 - go pong(c, peer)
19 - }
20 - }
21 -}
22 -
23 -func pong(c net.Conn, peer *peer.Peer) {
24 - mrw := msgio.NewReadWriter(c)
25 - for {
26 - data := make([]byte, 1024)
27 - n, err := mrw.ReadMsg(data)
28 - if err != nil {
29 - fmt.Printf("error %v\n", err)
30 - return
31 - }
32 - b, err := Unwrap(data[:n])
33 - if err != nil {
34 - fmt.Printf("error %v\n", err)
35 - return
36 - }
37 - if string(b.GetMessage()) != "ping" {
38 - fmt.Printf("error: didn't receive ping: '%v'\n", b.GetMessage())
39 - return
40 - }
41 -
42 - data, err = Wrap([]byte("pong"), PBWrapper_TEST)
43 - if err != nil {
44 - fmt.Printf("error %v\n", err)
45 - return
46 - }
47 - err = mrw.WriteMsg(data)
48 - if err != nil {
49 - fmt.Printf("error %v\n", err)
50 - return
51 - }
52 - }
53 -}
54 -
55 -func TestSwarm(t *testing.T) {
56 -
57 - swarm := NewSwarm(nil)
58 - var peers []*peer.Peer
59 - var listeners []net.Listener
60 - peerNames := map[string]string{
61 - "11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a30": "/ip4/127.0.0.1/tcp/1234",
62 - "11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a31": "/ip4/127.0.0.1/tcp/2345",
63 - "11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a32": "/ip4/127.0.0.1/tcp/3456",
64 - "11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33": "/ip4/127.0.0.1/tcp/4567",
65 - }
66 -
67 - recv := swarm.GetChannel(PBWrapper_TEST)
68 - for k, n := range peerNames {
69 - peer, err := setupPeer(k, n)
70 - if err != nil {
71 - t.Fatal("error setting up peer", err)
72 - }
73 - a := peer.NetAddress("tcp")
74 - if a == nil {
75 - t.Fatal("error setting up peer (addr is nil)", peer)
76 - }
77 - n, h, err := a.DialArgs()
78 - if err != nil {
79 - t.Fatal("error getting dial args from addr")
80 - }
81 - listener, err := net.Listen(n, h)
82 - if err != nil {
83 - t.Fatal("error setting up listener", err)
84 - }
85 - go pingListen(listener.(*net.TCPListener), peer)
86 -
87 - conn, err, _ := swarm.Dial(peer)
88 - if err != nil {
89 - t.Fatal("error swarm dialing to peer", err)
90 - }
91 -
92 - //Since we arent doing a handshake, set up 'secure' channels
93 - conn.secIn = conn.Incoming.MsgChan
94 - conn.secOut = conn.Outgoing.MsgChan
95 -
96 - swarm.StartConn(conn)
97 - // ok done, add it.
98 - peers = append(peers, peer)
99 - listeners = append(listeners, listener)
100 - }
101 -
102 - MsgNum := 1000
103 - for k := 0; k < MsgNum; k++ {
104 - for _, p := range peers {
105 - recv.Outgoing <- &Message{Peer: p, Data: []byte("ping")}
106 - }
107 - }
108 -
109 - got := map[u.Key]int{}
110 -
111 - for k := 0; k < (MsgNum * len(peers)); k++ {
112 - msg := <-recv.Incoming
113 - if string(msg.Data) != "pong" {
114 - t.Error("unexpected conn output", msg.Data)
115 - }
116 -
117 - n, _ := got[msg.Peer.Key()]
118 - got[msg.Peer.Key()] = n + 1
119 - }
120 -
121 - if len(peers) != len(got) {
122 - t.Error("got less messages than sent")
123 - }
124 -
125 - for p, n := range got {
126 - if n != MsgNum {
127 - t.Error("peer did not get all msgs", p, n, "/", MsgNum)
128 - }
129 - }
130 -
131 - fmt.Println("closing")
132 - swarm.Close()
133 - for _, listener := range listeners {
134 - listener.(*net.TCPListener).Close()
135 - }
136 -}
swarm/wrapper.go deleted
-24
@@ -1,24 +0,0 @@
1 -package swarm
2 -
3 -import "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
4 -
5 -func Wrap(data []byte, typ PBWrapper_MessageType) ([]byte, error) {
6 - wrapper := new(PBWrapper)
7 - wrapper.Message = data
8 - wrapper.Type = &typ
9 - b, err := proto.Marshal(wrapper)
10 - if err != nil {
11 - return nil, err
12 - }
13 - return b, nil
14 -}
15 -
16 -func Unwrap(data []byte) (*PBWrapper, error) {
17 - mes := new(PBWrapper)
18 - err := proto.Unmarshal(data, mes)
19 - if err != nil {
20 - return nil, err
21 - }
22 -
23 - return mes, nil
24 -}