Added initiator field to peer to detect in the peer initiated the connected.

This commit is contained in:
anthdm 2018-01-26 21:42:43 +01:00
parent 95a7ac1d22
commit 058459c65d
3 changed files with 12 additions and 10 deletions

View file

@ -13,13 +13,16 @@ type Peer struct {
send chan *Message send chan *Message
// verack is true if this node has sended it's version. // verack is true if this node has sended it's version.
verack bool verack bool
// whether we or him made the initial connection.
initiator bool
} }
// NewPeer returns a (TCP) Peer. // NewPeer returns a (TCP) Peer.
func NewPeer(conn net.Conn) *Peer { func NewPeer(conn net.Conn, init bool) *Peer {
return &Peer{ return &Peer{
conn: conn, conn: conn,
send: make(chan *Message), send: make(chan *Message),
initiator: init,
} }
} }
@ -35,6 +38,7 @@ func (p *Peer) writeLoop() {
for { for {
msg := <-p.send msg := <-p.send
rpcLogger.Printf("OUT :: %+v", msg)
if err := msg.encode(p.conn); err != nil { if err := msg.encode(p.conn); err != nil {
log.Printf("encode error: %s", err) log.Printf("encode error: %s", err)
} }

View file

@ -125,7 +125,7 @@ func (s *Server) loop() {
s.logger.Printf("peer registered from address %s", peer.conn.RemoteAddr()) s.logger.Printf("peer registered from address %s", peer.conn.RemoteAddr())
// only respond with the version mesage if the peer initiated the connection. // only respond with the version mesage if the peer initiated the connection.
if peer.initiater { if peer.initiator {
resp, err := s.handlePeerConnected() resp, err := s.handlePeerConnected()
if err != nil { if err != nil {
s.logger.Fatalf("handling initial peer connection failed: %s", err) s.logger.Fatalf("handling initial peer connection failed: %s", err)

View file

@ -1,7 +1,6 @@
package network package network
import ( import (
"fmt"
"io" "io"
"log" "log"
"net" "net"
@ -18,12 +17,11 @@ func listenTCP(s *Server, port string) error {
if err != nil { if err != nil {
return err return err
} }
go handleConnection(s, conn) go handleConnection(s, conn, true)
} }
} }
func connectToSeeds(s *Server, addrs []string) { func connectToSeeds(s *Server, addrs []string) {
fmt.Println(len(addrs))
for _, addr := range addrs { for _, addr := range addrs {
go func(addr string) { go func(addr string) {
conn, err := net.Dial("tcp", addr) conn, err := net.Dial("tcp", addr)
@ -34,13 +32,13 @@ func connectToSeeds(s *Server, addrs []string) {
} }
return return
} }
go handleConnection(s, conn) go handleConnection(s, conn, false)
}(addr) }(addr)
} }
} }
func handleConnection(s *Server, conn net.Conn) { func handleConnection(s *Server, conn net.Conn, initiated bool) {
peer := NewPeer(conn) peer := NewPeer(conn, initiated)
s.register <- peer s.register <- peer
// remove the peer from connected peers and cleanup the connection. // remove the peer from connected peers and cleanup the connection.