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.

305 lines
8.6 KiB

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