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.

274 lines
7.1 KiB

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