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.

275 lines
6.3 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. PexChannel = 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: PexChannel,
  56. Priority: 1,
  57. SendQueueCapacity: 10,
  58. },
  59. }
  60. }
  61. // Implements Reactor
  62. func (pexR *PEXReactor) AddPeer(peer *Peer) {
  63. if peer.IsOutbound() {
  64. pexR.SendAddrs(peer, pexR.book.OurAddresses())
  65. if pexR.book.NeedMoreAddrs() {
  66. pexR.RequestPEX(peer)
  67. }
  68. }
  69. }
  70. // Implements Reactor
  71. func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{}) {
  72. // TODO
  73. }
  74. // Implements Reactor
  75. // Handles incoming PEX messages.
  76. func (pexR *PEXReactor) Receive(chId byte, src *Peer, msgBytes []byte) {
  77. // decode message
  78. msg, err := DecodeMessage(msgBytes)
  79. if err != nil {
  80. log.Warn("Error decoding message", "error", err)
  81. return
  82. }
  83. log.Info("Received message", "msg", msg)
  84. switch msg.(type) {
  85. case *pexHandshakeMessage:
  86. network := msg.(*pexHandshakeMessage).Network
  87. if network != pexR.sw.network {
  88. err := fmt.Sprintf("Peer is on a different chain/network. Got %s, expected %s", network, pexR.sw.network)
  89. pexR.sw.StopPeerForError(src, err)
  90. }
  91. case *pexRequestMessage:
  92. // src requested some peers.
  93. // TODO: prevent abuse.
  94. pexR.SendAddrs(src, pexR.book.GetSelection())
  95. case *pexAddrsMessage:
  96. // We received some peer addresses from src.
  97. // TODO: prevent abuse.
  98. // (We don't want to get spammed with bad peers)
  99. srcAddr := src.Connection().RemoteAddress
  100. for _, addr := range msg.(*pexAddrsMessage).Addrs {
  101. pexR.book.AddAddress(addr, srcAddr)
  102. }
  103. default:
  104. // Ignore unknown message.
  105. }
  106. }
  107. // Asks peer for more addresses.
  108. func (pexR *PEXReactor) RequestPEX(peer *Peer) {
  109. peer.Send(PexChannel, &pexRequestMessage{})
  110. }
  111. func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) {
  112. peer.Send(PexChannel, &pexAddrsMessage{Addrs: addrs})
  113. }
  114. // Ensures that sufficient peers are connected. (continuous)
  115. func (pexR *PEXReactor) ensurePeersRoutine() {
  116. // fire once immediately.
  117. pexR.ensurePeers()
  118. // fire periodically
  119. timer := NewRepeatTimer("pex", ensurePeersPeriodSeconds*time.Second)
  120. FOR_LOOP:
  121. for {
  122. select {
  123. case <-timer.Ch:
  124. pexR.ensurePeers()
  125. case <-pexR.quit:
  126. break FOR_LOOP
  127. }
  128. }
  129. // Cleanup
  130. timer.Stop()
  131. }
  132. // Ensures that sufficient peers are connected. (once)
  133. func (pexR *PEXReactor) ensurePeers() {
  134. numOutPeers, _, numDialing := pexR.sw.NumPeers()
  135. numToDial := minNumOutboundPeers - (numOutPeers + numDialing)
  136. log.Debug("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial)
  137. if numToDial <= 0 {
  138. return
  139. }
  140. toDial := NewCMap()
  141. // Try to pick numToDial addresses to dial.
  142. // TODO: improve logic.
  143. for i := 0; i < numToDial; i++ {
  144. newBias := MinInt(numOutPeers, 8)*10 + 10
  145. var picked *NetAddress
  146. // Try to fetch a new peer 3 times.
  147. // This caps the maximum number of tries to 3 * numToDial.
  148. for j := 0; j < 3; j++ {
  149. try := pexR.book.PickAddress(newBias)
  150. if try == nil {
  151. break
  152. }
  153. alreadySelected := toDial.Has(try.String())
  154. alreadyDialing := pexR.sw.IsDialing(try)
  155. alreadyConnected := pexR.sw.Peers().Has(try.String())
  156. if alreadySelected || alreadyDialing || alreadyConnected {
  157. /*
  158. log.Debug("Cannot dial address", "addr", try,
  159. "alreadySelected", alreadySelected,
  160. "alreadyDialing", alreadyDialing,
  161. "alreadyConnected", alreadyConnected)
  162. */
  163. continue
  164. } else {
  165. log.Debug("Will dial address", "addr", try)
  166. picked = try
  167. break
  168. }
  169. }
  170. if picked == nil {
  171. continue
  172. }
  173. toDial.Set(picked.String(), picked)
  174. }
  175. // Dial picked addresses
  176. for _, item := range toDial.Values() {
  177. picked := item.(*NetAddress)
  178. go func() {
  179. _, err := pexR.sw.DialPeerWithAddress(picked)
  180. if err != nil {
  181. pexR.book.MarkAttempt(picked)
  182. }
  183. }()
  184. }
  185. }
  186. //-----------------------------------------------------------------------------
  187. // Messages
  188. const (
  189. msgTypeUnknown = byte(0x00)
  190. msgTypeRequest = byte(0x01)
  191. msgTypeAddrs = byte(0x02)
  192. msgTypeHandshake = byte(0x03)
  193. )
  194. // TODO: check for unnecessary extra bytes at the end.
  195. func DecodeMessage(bz []byte) (msg interface{}, err error) {
  196. n := new(int64)
  197. msgType := bz[0]
  198. r := bytes.NewReader(bz)
  199. // log.Debug(Fmt("decoding msg bytes: %X", bz))
  200. switch msgType {
  201. case msgTypeHandshake:
  202. msg = binary.ReadBinary(&pexHandshakeMessage{}, r, n, &err)
  203. case msgTypeRequest:
  204. msg = &pexRequestMessage{}
  205. case msgTypeAddrs:
  206. msg = binary.ReadBinary(&pexAddrsMessage{}, r, n, &err)
  207. default:
  208. msg = nil
  209. }
  210. return
  211. }
  212. /*
  213. A pexHandshakeMessage contains the network identifier.
  214. */
  215. type pexHandshakeMessage struct {
  216. Network string
  217. }
  218. func (m *pexHandshakeMessage) TypeByte() byte { return msgTypeHandshake }
  219. func (m *pexHandshakeMessage) String() string {
  220. return "[pexHandshake]"
  221. }
  222. /*
  223. A pexRequestMessage requests additional peer addresses.
  224. */
  225. type pexRequestMessage struct {
  226. }
  227. func (m *pexRequestMessage) TypeByte() byte { return msgTypeRequest }
  228. func (m *pexRequestMessage) String() string {
  229. return "[pexRequest]"
  230. }
  231. /*
  232. A message with announced peer addresses.
  233. */
  234. type pexAddrsMessage struct {
  235. Addrs []*NetAddress
  236. }
  237. func (m *pexAddrsMessage) TypeByte() byte { return msgTypeAddrs }
  238. func (m *pexAddrsMessage) String() string {
  239. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  240. }