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.

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