9 "github.com/btcsuite/go-socks/socks"
10 "github.com/pkg/errors"
11 log "github.com/sirupsen/logrus"
12 crypto "github.com/tendermint/go-crypto"
13 wire "github.com/tendermint/go-wire"
14 cmn "github.com/tendermint/tmlibs/common"
15 "github.com/tendermint/tmlibs/flowrate"
17 cfg "github.com/vapor/config"
18 "github.com/vapor/consensus"
19 "github.com/vapor/p2p/connection"
22 // peerConn contains the raw connection and its config.
23 type peerConn struct {
26 conn net.Conn // source connection
29 // PeerConfig is a Peer configuration.
30 type PeerConfig struct {
31 HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"` // times are in seconds
32 DialTimeout time.Duration `mapstructure:"dial_timeout"`
33 ProxyAddress string `mapstructure:"proxy_address"`
34 ProxyUsername string `mapstructure:"proxy_username"`
35 ProxyPassword string `mapstructure:"proxy_password"`
36 MConfig *connection.MConnConfig `mapstructure:"connection"`
39 // DefaultPeerConfig returns the default config.
40 func DefaultPeerConfig(config *cfg.P2PConfig) *PeerConfig {
42 HandshakeTimeout: time.Duration(config.HandshakeTimeout) * time.Second, // * time.Second,
43 DialTimeout: time.Duration(config.DialTimeout) * time.Second, // * time.Second,
44 ProxyAddress: config.ProxyAddress,
45 ProxyUsername: config.ProxyUsername,
46 ProxyPassword: config.ProxyPassword,
47 MConfig: connection.DefaultMConnConfig(),
51 // Peer represent a bytom network node
56 mconn *connection.MConnection // multiplex connection
60 // OnStart implements BaseService.
61 func (p *Peer) OnStart() error {
62 p.BaseService.OnStart()
63 _, err := p.mconn.Start()
67 // OnStop implements BaseService.
68 func (p *Peer) OnStop() {
69 p.BaseService.OnStop()
73 func newPeer(pc *peerConn, nodeInfo *NodeInfo, reactorsByCh map[byte]Reactor, chDescs []*connection.ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer {
74 // Key and NodeInfo are set after Handshake
78 Key: nodeInfo.PubKey.KeyString(),
80 p.mconn = createMConnection(pc.conn, p, reactorsByCh, chDescs, onPeerError, pc.config.MConfig)
81 p.BaseService = *cmn.NewBaseService(nil, "Peer", p)
85 func newOutboundPeerConn(addr *NetAddress, ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*peerConn, error) {
86 conn, err := dial(addr, config)
88 return nil, errors.Wrap(err, "Error dial peer")
91 pc, err := newPeerConn(conn, true, ourNodePrivKey, config)
99 func newInboundPeerConn(conn net.Conn, ourNodePrivKey crypto.PrivKeyEd25519, config *cfg.P2PConfig) (*peerConn, error) {
100 return newPeerConn(conn, false, ourNodePrivKey, DefaultPeerConfig(config))
103 func newPeerConn(rawConn net.Conn, outbound bool, ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*peerConn, error) {
104 rawConn.SetDeadline(time.Now().Add(config.HandshakeTimeout))
105 conn, err := connection.MakeSecretConnection(rawConn, ourNodePrivKey)
107 return nil, errors.Wrap(err, "Error creating peer")
117 // Addr returns peer's remote network address.
118 func (p *Peer) Addr() net.Addr {
119 return p.conn.RemoteAddr()
122 // CanSend returns true if the send queue is not full, false otherwise.
123 func (p *Peer) CanSend(chID byte) bool {
127 return p.mconn.CanSend(chID)
130 // CloseConn should be used when the peer was created, but never started.
131 func (pc *peerConn) CloseConn() {
135 // Equals reports whenever 2 peers are actually represent the same node.
136 func (p *Peer) Equals(other *Peer) bool {
137 return p.Key == other.Key
140 // HandshakeTimeout performs a handshake between a given node and the peer.
142 func (pc *peerConn) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) (*NodeInfo, error) {
143 // Set deadline for handshake so we don't block forever on conn.ReadFull
144 if err := pc.conn.SetDeadline(time.Now().Add(timeout)); err != nil {
148 var peerNodeInfo = new(NodeInfo)
153 wire.WriteBinary(ourNodeInfo, pc.conn, &n, &err1)
157 wire.ReadBinary(peerNodeInfo, pc.conn, maxNodeInfoSize, &n, &err2)
158 log.WithField("address", peerNodeInfo.ListenAddr).Info("Peer handshake")
161 return peerNodeInfo, errors.Wrap(err1, "Error during handshake/write")
164 return peerNodeInfo, errors.Wrap(err2, "Error during handshake/read")
168 if err := pc.conn.SetDeadline(time.Time{}); err != nil {
171 peerNodeInfo.RemoteAddr = pc.conn.RemoteAddr().String()
172 return peerNodeInfo, nil
175 // ID return the uuid of the peer
176 func (p *Peer) ID() string {
180 // IsOutbound returns true if the connection is outbound, false otherwise.
181 func (p *Peer) IsOutbound() bool {
185 // PubKey returns peer's public key.
186 func (p *Peer) PubKey() crypto.PubKeyEd25519 {
187 return p.conn.(*connection.SecretConnection).RemotePubKey()
190 // Send msg to the channel identified by chID byte. Returns false if the send
191 // queue is full after timeout, specified by MConnection.
192 func (p *Peer) Send(chID byte, msg interface{}) bool {
196 return p.mconn.Send(chID, msg)
199 // ServiceFlag return the ServiceFlag of this peer
200 func (p *Peer) ServiceFlag() consensus.ServiceFlag {
201 services := consensus.SFFullNode
202 if len(p.Other) == 0 {
206 if serviceFlag, err := strconv.ParseUint(p.Other[0], 10, 64); err == nil {
207 services = consensus.ServiceFlag(serviceFlag)
212 // String representation.
213 func (p *Peer) String() string {
215 return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12])
217 return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12])
220 // TrafficStatus return the in and out traffic status
221 func (p *Peer) TrafficStatus() (*flowrate.Status, *flowrate.Status) {
222 return p.mconn.TrafficStatus()
225 // TrySend msg to the channel identified by chID byte. Immediately returns
226 // false if the send queue is full.
227 func (p *Peer) TrySend(chID byte, msg interface{}) bool {
231 return p.mconn.TrySend(chID, msg)
234 func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, chDescs []*connection.ChannelDescriptor, onPeerError func(*Peer, interface{}), config *connection.MConnConfig) *connection.MConnection {
235 onReceive := func(chID byte, msgBytes []byte) {
236 reactor := reactorsByCh[chID]
238 cmn.PanicSanity(cmn.Fmt("Unknown channel %X", chID))
240 reactor.Receive(chID, p, msgBytes)
243 onError := func(r interface{}) {
246 return connection.NewMConnectionWithConfig(conn, chDescs, onReceive, onError, config)
249 func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) {
252 if config.ProxyAddress == "" {
253 conn, err = addr.DialTimeout(config.DialTimeout)
255 proxy := &socks.Proxy{
256 Addr: config.ProxyAddress,
257 Username: config.ProxyUsername,
258 Password: config.ProxyPassword,
261 conn, err = addr.DialTimeoutWithProxy(proxy, config.DialTimeout)