2018-03-09 15:55:25 +00:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2018-03-10 12:04:06 +00:00
|
|
|
"sync"
|
2018-03-09 15:55:25 +00:00
|
|
|
|
|
|
|
"github.com/CityOfZion/neo-go/pkg/network/payload"
|
|
|
|
"github.com/CityOfZion/neo-go/pkg/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TCPPeer represents a connected remote node in the
|
|
|
|
// network over TCP.
|
|
|
|
type TCPPeer struct {
|
2018-03-14 09:36:59 +00:00
|
|
|
// underlying TCP connection.
|
|
|
|
conn net.Conn
|
2018-03-09 15:55:25 +00:00
|
|
|
endpoint util.Endpoint
|
|
|
|
|
2018-03-14 09:36:59 +00:00
|
|
|
// The version of the peer.
|
2018-03-09 15:55:25 +00:00
|
|
|
version *payload.Version
|
|
|
|
|
2018-04-13 10:14:08 +00:00
|
|
|
done chan error
|
2018-03-09 15:55:25 +00:00
|
|
|
|
2018-03-14 09:36:59 +00:00
|
|
|
wg sync.WaitGroup
|
2018-03-09 15:55:25 +00:00
|
|
|
}
|
|
|
|
|
2019-09-03 14:51:37 +00:00
|
|
|
// NewTCPPeer returns a TCPPeer structure based on the given connection.
|
2018-04-13 10:14:08 +00:00
|
|
|
func NewTCPPeer(conn net.Conn) *TCPPeer {
|
2018-03-09 15:55:25 +00:00
|
|
|
return &TCPPeer{
|
2018-03-14 09:36:59 +00:00
|
|
|
conn: conn,
|
2018-04-13 10:14:08 +00:00
|
|
|
done: make(chan error, 1),
|
2018-03-14 09:36:59 +00:00
|
|
|
endpoint: util.NewEndpoint(conn.RemoteAddr().String()),
|
2018-03-09 15:55:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-13 10:14:08 +00:00
|
|
|
// WriteMsg implements the Peer interface. This will write/encode the message
|
2018-03-14 09:36:59 +00:00
|
|
|
// to the underlying connection.
|
2018-04-13 10:14:08 +00:00
|
|
|
func (p *TCPPeer) WriteMsg(msg *Message) error {
|
|
|
|
select {
|
|
|
|
case err := <-p.done:
|
|
|
|
return err
|
|
|
|
default:
|
|
|
|
return msg.Encode(p.conn)
|
2018-03-14 09:36:59 +00:00
|
|
|
}
|
2018-03-09 15:55:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Endpoint implements the Peer interface.
|
|
|
|
func (p *TCPPeer) Endpoint() util.Endpoint {
|
|
|
|
return p.endpoint
|
|
|
|
}
|
|
|
|
|
2018-03-14 09:36:59 +00:00
|
|
|
// Done implements the Peer interface and notifies
|
|
|
|
// all other resources operating on it that this peer
|
|
|
|
// is no longer running.
|
|
|
|
func (p *TCPPeer) Done() chan error {
|
2018-03-09 15:55:25 +00:00
|
|
|
return p.done
|
|
|
|
}
|
|
|
|
|
2018-04-13 10:14:08 +00:00
|
|
|
// Disconnect will fill the peer's done channel with the given error.
|
|
|
|
func (p *TCPPeer) Disconnect(err error) {
|
|
|
|
p.done <- err
|
|
|
|
}
|
|
|
|
|
2018-03-14 09:36:59 +00:00
|
|
|
// Version implements the Peer interface.
|
|
|
|
func (p *TCPPeer) Version() *payload.Version {
|
|
|
|
return p.version
|
2018-03-10 12:04:06 +00:00
|
|
|
}
|
2018-03-09 15:55:25 +00:00
|
|
|
|
2018-04-13 10:14:08 +00:00
|
|
|
// SetVersion implements the Peer interface.
|
|
|
|
func (p *TCPPeer) SetVersion(v *payload.Version) {
|
|
|
|
p.version = v
|
2018-03-09 15:55:25 +00:00
|
|
|
}
|