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
// verack is true if this node has sended it's version.
verack bool
// whether we or him made the initial connection.
initiator bool
}
// NewPeer returns a (TCP) Peer.
func NewPeer(conn net.Conn) *Peer {
func NewPeer(conn net.Conn, init bool) *Peer {
return &Peer{
conn: conn,
send: make(chan *Message),
conn: conn,
send: make(chan *Message),
initiator: init,
}
}
@ -35,6 +38,7 @@ func (p *Peer) writeLoop() {
for {
msg := <-p.send
rpcLogger.Printf("OUT :: %+v", msg)
if err := msg.encode(p.conn); err != nil {
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())
// only respond with the version mesage if the peer initiated the connection.
if peer.initiater {
if peer.initiator {
resp, err := s.handlePeerConnected()
if err != nil {
s.logger.Fatalf("handling initial peer connection failed: %s", err)

View file

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