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.

341 lines
8.7 KiB

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