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.

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