9 "github.com/pkg/errors"
10 log "github.com/sirupsen/logrus"
11 crypto "github.com/tendermint/go-crypto"
12 wire "github.com/tendermint/go-wire"
13 cmn "github.com/tendermint/tmlibs/common"
16 // Peer could be marked as persistent, in which case you can use
17 // Redial function to reconnect. Note that inbound peers can't be
18 // made persistent. They should be made persistent on the other end.
20 // Before using a peer, you will need to perform a handshake on connection.
26 conn net.Conn // source connection
27 mconn *MConnection // multiplex connection
34 Data *cmn.CMap // User data.
37 // PeerConfig is a Peer configuration.
38 type PeerConfig struct {
39 AuthEnc bool `mapstructure:"auth_enc"` // authenticated encryption
41 // times are in seconds
42 HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
43 DialTimeout time.Duration `mapstructure:"dial_timeout"`
45 MConfig *MConnConfig `mapstructure:"connection"`
47 Fuzz bool `mapstructure:"fuzz"` // fuzz connection (for testing)
48 FuzzConfig *FuzzConnConfig `mapstructure:"fuzz_config"`
51 // DefaultPeerConfig returns the default config.
52 func DefaultPeerConfig() *PeerConfig {
55 HandshakeTimeout: 20, // * time.Second,
56 DialTimeout: 3, // * time.Second,
57 MConfig: DefaultMConnConfig(),
59 FuzzConfig: DefaultFuzzConnConfig(),
63 func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) {
64 return newOutboundPeerWithConfig(addr, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, DefaultPeerConfig())
67 func newOutboundPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) {
68 conn, err := dial(addr, config)
70 return nil, errors.Wrap(err, "Error creating peer")
73 peer, err := newPeerFromConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
81 func newInboundPeer(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) {
82 return newInboundPeerWithConfig(conn, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, DefaultPeerConfig())
85 func newInboundPeerWithConfig(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) {
86 return newPeerFromConnAndConfig(conn, false, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
89 func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) {
94 // so we have time to do peer handshakes and get set up
95 conn = FuzzConnAfterFromConfig(conn, 10*time.Second, config.FuzzConfig)
100 conn.SetDeadline(time.Now().Add(config.HandshakeTimeout * time.Second))
103 conn, err = MakeSecretConnection(conn, ourNodePrivKey)
105 return nil, errors.Wrap(err, "Error creating peer")
109 // Key and NodeInfo are set after Handshake
117 p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config.MConfig)
119 p.BaseService = *cmn.NewBaseService(nil, "Peer", p)
124 // CloseConn should be used when the peer was created, but never started.
125 func (p *Peer) CloseConn() {
129 // makePersistent marks the peer as persistent.
130 func (p *Peer) makePersistent() {
132 panic("inbound peers can't be made persistent")
138 // IsPersistent returns true if the peer is persitent, false otherwise.
139 func (p *Peer) IsPersistent() bool {
143 // HandshakeTimeout performs a handshake between a given node and the peer.
145 func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) error {
146 // Set deadline for handshake so we don't block forever on conn.ReadFull
147 p.conn.SetDeadline(time.Now().Add(timeout))
149 var peerNodeInfo = new(NodeInfo)
155 wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1)
159 wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2)
160 log.WithField("peerNodeInfo", peerNodeInfo).Info("Peer handshake")
163 return errors.Wrap(err1, "Error during handshake/write")
166 return errors.Wrap(err2, "Error during handshake/read")
169 if p.config.AuthEnc {
170 // Check that the professed PubKey matches the sconn's.
171 if !peerNodeInfo.PubKey.Equals(p.PubKey().Wrap()) {
172 return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v",
173 peerNodeInfo.PubKey, p.PubKey())
178 p.conn.SetDeadline(time.Time{})
180 peerNodeInfo.RemoteAddr = p.Addr().String()
182 p.NodeInfo = peerNodeInfo
183 p.Key = peerNodeInfo.PubKey.KeyString()
188 // Addr returns peer's remote network address.
189 func (p *Peer) Addr() net.Addr {
190 return p.conn.RemoteAddr()
193 // PubKey returns peer's public key.
194 func (p *Peer) PubKey() crypto.PubKeyEd25519 {
195 if p.config.AuthEnc {
196 return p.conn.(*SecretConnection).RemotePubKey()
198 if p.NodeInfo == nil {
199 panic("Attempt to get peer's PubKey before calling Handshake")
204 // OnStart implements BaseService.
205 func (p *Peer) OnStart() error {
206 p.BaseService.OnStart()
207 _, err := p.mconn.Start()
211 // OnStop implements BaseService.
212 func (p *Peer) OnStop() {
213 p.BaseService.OnStop()
217 // Connection returns underlying MConnection.
218 func (p *Peer) Connection() *MConnection {
222 // IsOutbound returns true if the connection is outbound, false otherwise.
223 func (p *Peer) IsOutbound() bool {
227 // Send msg to the channel identified by chID byte. Returns false if the send
228 // queue is full after timeout, specified by MConnection.
229 func (p *Peer) Send(chID byte, msg interface{}) bool {
231 // see Switch#Broadcast, where we fetch the list of peers and loop over
232 // them - while we're looping, one peer may be removed and stopped.
235 return p.mconn.Send(chID, msg)
238 // TrySend msg to the channel identified by chID byte. Immediately returns
239 // false if the send queue is full.
240 func (p *Peer) TrySend(chID byte, msg interface{}) bool {
244 return p.mconn.TrySend(chID, msg)
247 // CanSend returns true if the send queue is not full, false otherwise.
248 func (p *Peer) CanSend(chID byte) bool {
252 return p.mconn.CanSend(chID)
255 // WriteTo writes the peer's public key to w.
256 func (p *Peer) WriteTo(w io.Writer) (n int64, err error) {
258 wire.WriteString(p.Key, w, &n_, &err)
263 // String representation.
264 func (p *Peer) String() string {
266 return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12])
269 return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12])
272 // Equals reports whenever 2 peers are actually represent the same node.
273 func (p *Peer) Equals(other *Peer) bool {
274 return p.Key == other.Key
277 // Get the data for a given key.
278 func (p *Peer) Get(key string) interface{} {
279 return p.Data.Get(key)
282 func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) {
283 conn, err := addr.DialTimeout(config.DialTimeout * time.Second)
290 func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config *MConnConfig) *MConnection {
291 onReceive := func(chID byte, msgBytes []byte) {
292 reactor := reactorsByCh[chID]
294 cmn.PanicSanity(cmn.Fmt("Unknown channel %X", chID))
296 reactor.Receive(chID, p, msgBytes)
299 onError := func(r interface{}) {
303 return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, config)