You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

304 lines
8.4 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package p2p
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "time"
  7. "github.com/pkg/errors"
  8. crypto "github.com/tendermint/go-crypto"
  9. wire "github.com/tendermint/go-wire"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. )
  12. // Peer could be marked as persistent, in which case you can use
  13. // Redial function to reconnect. Note that inbound peers can't be
  14. // made persistent. They should be made persistent on the other end.
  15. //
  16. // Before using a peer, you will need to perform a handshake on connection.
  17. type Peer struct {
  18. cmn.BaseService
  19. outbound bool
  20. conn net.Conn // source connection
  21. mconn *MConnection // multiplex connection
  22. persistent bool
  23. config *PeerConfig
  24. *NodeInfo
  25. Key string
  26. Data *cmn.CMap // User data.
  27. }
  28. // PeerConfig is a Peer configuration.
  29. type PeerConfig struct {
  30. AuthEnc bool // authenticated encryption
  31. HandshakeTimeout time.Duration
  32. DialTimeout time.Duration
  33. MConfig *MConnConfig
  34. Fuzz bool // fuzz connection (for testing)
  35. FuzzConfig *FuzzConnConfig
  36. }
  37. // DefaultPeerConfig returns the default config.
  38. func DefaultPeerConfig() *PeerConfig {
  39. return &PeerConfig{
  40. AuthEnc: true,
  41. HandshakeTimeout: 2 * time.Second,
  42. DialTimeout: 3 * time.Second,
  43. MConfig: DefaultMConnConfig(),
  44. Fuzz: false,
  45. FuzzConfig: DefaultFuzzConnConfig(),
  46. }
  47. }
  48. func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) {
  49. return newOutboundPeerWithConfig(addr, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, DefaultPeerConfig())
  50. }
  51. func newOutboundPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) {
  52. conn, err := dial(addr, config)
  53. if err != nil {
  54. return nil, errors.Wrap(err, "Error creating peer")
  55. }
  56. peer, err := newPeerFromConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
  57. if err != nil {
  58. conn.Close()
  59. return nil, err
  60. }
  61. return peer, nil
  62. }
  63. func newInboundPeer(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) {
  64. return newInboundPeerWithConfig(conn, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, DefaultPeerConfig())
  65. }
  66. func newInboundPeerWithConfig(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) {
  67. return newPeerFromConnAndConfig(conn, false, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config)
  68. }
  69. func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) {
  70. conn := rawConn
  71. // Fuzz connection
  72. if config.Fuzz {
  73. // so we have time to do peer handshakes and get set up
  74. conn = FuzzConnAfterFromConfig(conn, 10*time.Second, config.FuzzConfig)
  75. }
  76. // Encrypt connection
  77. if config.AuthEnc {
  78. conn.SetDeadline(time.Now().Add(config.HandshakeTimeout))
  79. var err error
  80. conn, err = MakeSecretConnection(conn, ourNodePrivKey)
  81. if err != nil {
  82. return nil, errors.Wrap(err, "Error creating peer")
  83. }
  84. }
  85. // Key and NodeInfo are set after Handshake
  86. p := &Peer{
  87. outbound: outbound,
  88. conn: conn,
  89. config: config,
  90. Data: cmn.NewCMap(),
  91. }
  92. p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config.MConfig)
  93. p.BaseService = *cmn.NewBaseService(log, "Peer", p)
  94. return p, nil
  95. }
  96. // CloseConn should be used when the peer was created, but never started.
  97. func (p *Peer) CloseConn() {
  98. p.conn.Close()
  99. }
  100. // makePersistent marks the peer as persistent.
  101. func (p *Peer) makePersistent() {
  102. if !p.outbound {
  103. panic("inbound peers can't be made persistent")
  104. }
  105. p.persistent = true
  106. }
  107. // IsPersistent returns true if the peer is persitent, false otherwise.
  108. func (p *Peer) IsPersistent() bool {
  109. return p.persistent
  110. }
  111. // HandshakeTimeout performs a handshake between a given node and the peer.
  112. // NOTE: blocking
  113. func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) error {
  114. // Set deadline for handshake so we don't block forever on conn.ReadFull
  115. p.conn.SetDeadline(time.Now().Add(timeout))
  116. var peerNodeInfo = new(NodeInfo)
  117. var err1 error
  118. var err2 error
  119. cmn.Parallel(
  120. func() {
  121. var n int
  122. wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1)
  123. },
  124. func() {
  125. var n int
  126. wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2)
  127. log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo)
  128. })
  129. if err1 != nil {
  130. return errors.Wrap(err1, "Error during handshake/write")
  131. }
  132. if err2 != nil {
  133. return errors.Wrap(err2, "Error during handshake/read")
  134. }
  135. if p.config.AuthEnc {
  136. // Check that the professed PubKey matches the sconn's.
  137. if !peerNodeInfo.PubKey.Equals(p.PubKey().Wrap()) {
  138. return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v",
  139. peerNodeInfo.PubKey, p.PubKey())
  140. }
  141. }
  142. // Remove deadline
  143. p.conn.SetDeadline(time.Time{})
  144. peerNodeInfo.RemoteAddr = p.Addr().String()
  145. p.NodeInfo = peerNodeInfo
  146. p.Key = peerNodeInfo.PubKey.KeyString()
  147. return nil
  148. }
  149. // Addr returns peer's network address.
  150. func (p *Peer) Addr() net.Addr {
  151. return p.conn.RemoteAddr()
  152. }
  153. // PubKey returns peer's public key.
  154. func (p *Peer) PubKey() crypto.PubKeyEd25519 {
  155. if p.config.AuthEnc {
  156. return p.conn.(*SecretConnection).RemotePubKey()
  157. }
  158. if p.NodeInfo == nil {
  159. panic("Attempt to get peer's PubKey before calling Handshake")
  160. }
  161. return p.PubKey()
  162. }
  163. // OnStart implements BaseService.
  164. func (p *Peer) OnStart() error {
  165. p.BaseService.OnStart()
  166. _, err := p.mconn.Start()
  167. return err
  168. }
  169. // OnStop implements BaseService.
  170. func (p *Peer) OnStop() {
  171. p.BaseService.OnStop()
  172. p.mconn.Stop()
  173. }
  174. // Connection returns underlying MConnection.
  175. func (p *Peer) Connection() *MConnection {
  176. return p.mconn
  177. }
  178. // IsOutbound returns true if the connection is outbound, false otherwise.
  179. func (p *Peer) IsOutbound() bool {
  180. return p.outbound
  181. }
  182. // Send msg to the channel identified by chID byte. Returns false if the send
  183. // queue is full after timeout, specified by MConnection.
  184. func (p *Peer) Send(chID byte, msg interface{}) bool {
  185. if !p.IsRunning() {
  186. // see Switch#Broadcast, where we fetch the list of peers and loop over
  187. // them - while we're looping, one peer may be removed and stopped.
  188. return false
  189. }
  190. return p.mconn.Send(chID, msg)
  191. }
  192. // TrySend msg to the channel identified by chID byte. Immediately returns
  193. // false if the send queue is full.
  194. func (p *Peer) TrySend(chID byte, msg interface{}) bool {
  195. if !p.IsRunning() {
  196. return false
  197. }
  198. return p.mconn.TrySend(chID, msg)
  199. }
  200. // CanSend returns true if the send queue is not full, false otherwise.
  201. func (p *Peer) CanSend(chID byte) bool {
  202. if !p.IsRunning() {
  203. return false
  204. }
  205. return p.mconn.CanSend(chID)
  206. }
  207. // WriteTo writes the peer's public key to w.
  208. func (p *Peer) WriteTo(w io.Writer) (n int64, err error) {
  209. var n_ int
  210. wire.WriteString(p.Key, w, &n_, &err)
  211. n += int64(n_)
  212. return
  213. }
  214. // String representation.
  215. func (p *Peer) String() string {
  216. if p.outbound {
  217. return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12])
  218. }
  219. return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12])
  220. }
  221. // Equals reports whenever 2 peers are actually represent the same node.
  222. func (p *Peer) Equals(other *Peer) bool {
  223. return p.Key == other.Key
  224. }
  225. // Get the data for a given key.
  226. func (p *Peer) Get(key string) interface{} {
  227. return p.Data.Get(key)
  228. }
  229. func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) {
  230. log.Info("Dialing address", "address", addr)
  231. conn, err := addr.DialTimeout(config.DialTimeout)
  232. if err != nil {
  233. log.Info("Failed dialing address", "address", addr, "error", err)
  234. return nil, err
  235. }
  236. return conn, nil
  237. }
  238. func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config *MConnConfig) *MConnection {
  239. onReceive := func(chID byte, msgBytes []byte) {
  240. reactor := reactorsByCh[chID]
  241. if reactor == nil {
  242. cmn.PanicSanity(cmn.Fmt("Unknown channel %X", chID))
  243. }
  244. reactor.Receive(chID, p, msgBytes)
  245. }
  246. onError := func(r interface{}) {
  247. onPeerError(p, r)
  248. }
  249. return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, config)
  250. }