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.

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