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.

271 lines
6.0 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package p2p
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "sync/atomic"
  7. "time"
  8. "github.com/tendermint/tendermint/binary"
  9. . "github.com/tendermint/tendermint/common"
  10. )
  11. var pexErrInvalidMessage = errors.New("Invalid PEX message")
  12. const (
  13. PexCh = byte(0x00)
  14. ensurePeersPeriodSeconds = 30
  15. minNumOutboundPeers = 10
  16. maxNumPeers = 50
  17. )
  18. /*
  19. PEXReactor handles PEX (peer exchange) and ensures that an
  20. adequate number of peers are connected to the switch.
  21. */
  22. type PEXReactor struct {
  23. sw *Switch
  24. quit chan struct{}
  25. started uint32
  26. stopped uint32
  27. book *AddrBook
  28. }
  29. func NewPEXReactor(book *AddrBook) *PEXReactor {
  30. pexR := &PEXReactor{
  31. quit: make(chan struct{}),
  32. book: book,
  33. }
  34. return pexR
  35. }
  36. // Implements Reactor
  37. func (pexR *PEXReactor) Start(sw *Switch) {
  38. if atomic.CompareAndSwapUint32(&pexR.started, 0, 1) {
  39. log.Info("Starting PEXReactor")
  40. pexR.sw = sw
  41. go pexR.ensurePeersRoutine()
  42. }
  43. }
  44. // Implements Reactor
  45. func (pexR *PEXReactor) Stop() {
  46. if atomic.CompareAndSwapUint32(&pexR.stopped, 0, 1) {
  47. log.Info("Stopping PEXReactor")
  48. close(pexR.quit)
  49. }
  50. }
  51. // Implements Reactor
  52. func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor {
  53. return []*ChannelDescriptor{
  54. &ChannelDescriptor{
  55. Id: PexCh,
  56. Priority: 1,
  57. },
  58. }
  59. }
  60. // Implements Reactor
  61. func (pexR *PEXReactor) AddPeer(peer *Peer) {
  62. if peer.IsOutbound() {
  63. pexR.SendAddrs(peer, pexR.book.OurAddresses())
  64. if pexR.book.NeedMoreAddrs() {
  65. pexR.RequestPEX(peer)
  66. }
  67. }
  68. }
  69. // Implements Reactor
  70. func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{}) {
  71. // TODO
  72. }
  73. // Implements Reactor
  74. // Handles incoming PEX messages.
  75. func (pexR *PEXReactor) Receive(chId byte, src *Peer, msgBytes []byte) {
  76. // decode message
  77. msg, err := DecodeMessage(msgBytes)
  78. if err != nil {
  79. log.Warn("Error decoding message", "error", err)
  80. return
  81. }
  82. log.Info("Received message", "msg", msg)
  83. switch msg.(type) {
  84. case *pexHandshakeMessage:
  85. chainId := msg.(*pexHandshakeMessage).ChainId
  86. if chainId != pexR.sw.chainId {
  87. err := fmt.Sprintf("Peer is on a different chain/network. Got %s, expected %s", chainId, pexR.sw.chainId)
  88. pexR.sw.StopPeerForError(src, err)
  89. }
  90. case *pexRequestMessage:
  91. // src requested some peers.
  92. // TODO: prevent abuse.
  93. addrs := pexR.book.GetSelection()
  94. msg := &pexAddrsMessage{Addrs: addrs}
  95. queued := src.TrySend(PexCh, msg)
  96. if !queued {
  97. // ignore
  98. }
  99. case *pexAddrsMessage:
  100. // We received some peer addresses from src.
  101. // TODO: prevent abuse.
  102. // (We don't want to get spammed with bad peers)
  103. srcAddr := src.Connection().RemoteAddress
  104. for _, addr := range msg.(*pexAddrsMessage).Addrs {
  105. pexR.book.AddAddress(addr, srcAddr)
  106. }
  107. default:
  108. // Ignore unknown message.
  109. }
  110. }
  111. // Asks peer for more addresses.
  112. func (pexR *PEXReactor) RequestPEX(peer *Peer) {
  113. peer.TrySend(PexCh, &pexRequestMessage{})
  114. }
  115. func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) {
  116. peer.Send(PexCh, &pexAddrsMessage{Addrs: addrs})
  117. }
  118. // Ensures that sufficient peers are connected. (continuous)
  119. func (pexR *PEXReactor) ensurePeersRoutine() {
  120. // fire once immediately.
  121. pexR.ensurePeers()
  122. // fire periodically
  123. timer := NewRepeatTimer("pex", ensurePeersPeriodSeconds*time.Second)
  124. FOR_LOOP:
  125. for {
  126. select {
  127. case <-timer.Ch:
  128. pexR.ensurePeers()
  129. case <-pexR.quit:
  130. break FOR_LOOP
  131. }
  132. }
  133. // Cleanup
  134. timer.Stop()
  135. }
  136. // Ensures that sufficient peers are connected. (once)
  137. func (pexR *PEXReactor) ensurePeers() {
  138. numOutPeers, _, numDialing := pexR.sw.NumPeers()
  139. numToDial := minNumOutboundPeers - (numOutPeers + numDialing)
  140. log.Debug("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial)
  141. if numToDial <= 0 {
  142. return
  143. }
  144. toDial := NewCMap()
  145. // Try to pick numToDial addresses to dial.
  146. // TODO: improve logic.
  147. for i := 0; i < numToDial; i++ {
  148. newBias := MinInt(numOutPeers, 8)*10 + 10
  149. var picked *NetAddress
  150. // Try to fetch a new peer 3 times.
  151. // This caps the maximum number of tries to 3 * numToDial.
  152. for j := 0; j < 3; j++ {
  153. try := pexR.book.PickAddress(newBias)
  154. if try == nil {
  155. break
  156. }
  157. if toDial.Has(try.String()) ||
  158. pexR.sw.IsDialing(try) ||
  159. pexR.sw.Peers().Has(try.String()) {
  160. continue
  161. } else {
  162. picked = try
  163. break
  164. }
  165. }
  166. if picked == nil {
  167. continue
  168. }
  169. toDial.Set(picked.String(), picked)
  170. }
  171. // Dial picked addresses
  172. for _, item := range toDial.Values() {
  173. picked := item.(*NetAddress)
  174. go func() {
  175. _, err := pexR.sw.DialPeerWithAddress(picked)
  176. if err != nil {
  177. pexR.book.MarkAttempt(picked)
  178. }
  179. }()
  180. }
  181. }
  182. //-----------------------------------------------------------------------------
  183. // Messages
  184. const (
  185. msgTypeUnknown = byte(0x00)
  186. msgTypeRequest = byte(0x01)
  187. msgTypeAddrs = byte(0x02)
  188. msgTypeHandshake = byte(0x03)
  189. )
  190. // TODO: check for unnecessary extra bytes at the end.
  191. func DecodeMessage(bz []byte) (msg interface{}, err error) {
  192. n := new(int64)
  193. msgType := bz[0]
  194. r := bytes.NewReader(bz)
  195. // log.Debug(Fmt("decoding msg bytes: %X", bz))
  196. switch msgType {
  197. case msgTypeHandshake:
  198. msg = binary.ReadBinary(&pexHandshakeMessage{}, r, n, &err)
  199. case msgTypeRequest:
  200. msg = &pexRequestMessage{}
  201. case msgTypeAddrs:
  202. msg = binary.ReadBinary(&pexAddrsMessage{}, r, n, &err)
  203. default:
  204. msg = nil
  205. }
  206. return
  207. }
  208. /*
  209. A pexHandshakeMessage contains the peer's chainId
  210. */
  211. type pexHandshakeMessage struct {
  212. ChainId string
  213. }
  214. func (m *pexHandshakeMessage) TypeByte() byte { return msgTypeHandshake }
  215. func (m *pexHandshakeMessage) String() string {
  216. return "[pexHandshake]"
  217. }
  218. /*
  219. A pexRequestMessage requests additional peer addresses.
  220. */
  221. type pexRequestMessage struct {
  222. }
  223. func (m *pexRequestMessage) TypeByte() byte { return msgTypeRequest }
  224. func (m *pexRequestMessage) String() string {
  225. return "[pexRequest]"
  226. }
  227. /*
  228. A message with announced peer addresses.
  229. */
  230. type pexAddrsMessage struct {
  231. Addrs []*NetAddress
  232. }
  233. func (m *pexAddrsMessage) TypeByte() byte { return msgTypeAddrs }
  234. func (m *pexAddrsMessage) String() string {
  235. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  236. }