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.

367 lines
10 KiB

9 years ago
8 years ago
9 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
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
8 years ago
7 years ago
8 years ago
9 years ago
7 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
prevent nil addr Error: ``` Error: runtime error: invalid memoryaddress or nil pointer dereference\nStack: goroutine 549 [running]:\nruntime/debug.Stack(0x0, 0x0, 0x0)\n\t/usr/local/go/src/runtime/debug/stack.go:24 +0x80\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*MConnection)._recover(0xc821723b00)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/connection.go:173 +0x53\npanic(0xbe1500, 0xc820012080)\n\t/usr/local/go/src/runtime/panic.go:443 +0x4e9\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*NetAddress).Valid(0x0, 0x0)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/netaddress.go:125 +0x1c\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*NetAddress).Routable(0x0, 0xc8217bb740)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/netaddress.go:117 +0x25\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*AddrBook).addAddress(0xc820108380, 0x0, 0xc821739590)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/addrbook.go:524 +0x45\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*AddrBook).AddAddress(0xc820108380, 0x0, 0xc821739590)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/addrbook.go:160 +0x286\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*PEXReactor).Receive(0xc82000be60, 0xc820149f00, 0xc8218163f0, 0xc82184e000, 0x5b, 0x1000)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/pex_reactor.go:109 +0x457\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.newPeer.func1(0xc82011d500, 0xc82184e000, 0x5b, 0x1000)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/peer.go:58 +0x202\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*MConnection).recvRoutine(0xc821723b00)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/connection.go:439 +0x1177\ncreated by github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*MConnection).OnStart\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/connection.go:138 +0x1a1\n ```
8 years ago
9 years ago
8 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
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
  1. package p2p
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/rand"
  6. "reflect"
  7. "time"
  8. wire "github.com/tendermint/go-wire"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. )
  11. const (
  12. // PexChannel is a channel for PEX messages
  13. PexChannel = byte(0x00)
  14. // period to ensure peers connected
  15. defaultEnsurePeersPeriod = 30 * time.Second
  16. minNumOutboundPeers = 10
  17. maxPexMessageSize = 1048576 // 1MB
  18. // maximum pex messages one peer can send to us during `msgCountByPeerFlushInterval`
  19. defaultMaxMsgCountByPeer = 1000
  20. msgCountByPeerFlushInterval = 1 * time.Hour
  21. )
  22. // PEXReactor handles PEX (peer exchange) and ensures that an
  23. // adequate number of peers are connected to the switch.
  24. //
  25. // It uses `AddrBook` (address book) to store `NetAddress`es of the peers.
  26. //
  27. // ## Preventing abuse
  28. //
  29. // For now, it just limits the number of messages from one peer to
  30. // `defaultMaxMsgCountByPeer` messages per `msgCountByPeerFlushInterval` (1000
  31. // msg/hour).
  32. //
  33. // NOTE [2017-01-17]:
  34. // Limiting is fine for now. Maybe down the road we want to keep track of the
  35. // quality of peer messages so if peerA keeps telling us about peers we can't
  36. // connect to then maybe we should care less about peerA. But I don't think
  37. // that kind of complexity is priority right now.
  38. type PEXReactor struct {
  39. BaseReactor
  40. book *AddrBook
  41. config *PEXReactorConfig
  42. ensurePeersPeriod time.Duration
  43. // tracks message count by peer, so we can prevent abuse
  44. msgCountByPeer *cmn.CMap
  45. maxMsgCountByPeer uint16
  46. }
  47. // PEXReactorConfig holds reactor specific configuration data.
  48. type PEXReactorConfig struct {
  49. // Seeds is a list of addresses reactor may use if it can't connect to peers
  50. // in the addrbook.
  51. Seeds []string
  52. }
  53. // NewPEXReactor creates new PEX reactor.
  54. func NewPEXReactor(b *AddrBook, config *PEXReactorConfig) *PEXReactor {
  55. r := &PEXReactor{
  56. book: b,
  57. config: config,
  58. ensurePeersPeriod: defaultEnsurePeersPeriod,
  59. msgCountByPeer: cmn.NewCMap(),
  60. maxMsgCountByPeer: defaultMaxMsgCountByPeer,
  61. }
  62. r.BaseReactor = *NewBaseReactor("PEXReactor", r)
  63. return r
  64. }
  65. // OnStart implements BaseService
  66. func (r *PEXReactor) OnStart() error {
  67. if err := r.BaseReactor.OnStart(); err != nil {
  68. return err
  69. }
  70. err := r.book.Start()
  71. if err != nil && err != cmn.ErrAlreadyStarted {
  72. return err
  73. }
  74. go r.ensurePeersRoutine()
  75. go r.flushMsgCountByPeer()
  76. return nil
  77. }
  78. // OnStop implements BaseService
  79. func (r *PEXReactor) OnStop() {
  80. r.BaseReactor.OnStop()
  81. r.book.Stop()
  82. }
  83. // GetChannels implements Reactor
  84. func (r *PEXReactor) GetChannels() []*ChannelDescriptor {
  85. return []*ChannelDescriptor{
  86. {
  87. ID: PexChannel,
  88. Priority: 1,
  89. SendQueueCapacity: 10,
  90. },
  91. }
  92. }
  93. // AddPeer implements Reactor by adding peer to the address book (if inbound)
  94. // or by requesting more addresses (if outbound).
  95. func (r *PEXReactor) AddPeer(p Peer) {
  96. if p.IsOutbound() {
  97. // For outbound peers, the address is already in the books.
  98. // Either it was added in DialPeersAsync or when we
  99. // received the peer's address in r.Receive
  100. if r.book.NeedMoreAddrs() {
  101. r.RequestPEX(p)
  102. }
  103. } else {
  104. // For inbound connections, the peer is its own source
  105. addr := p.NodeInfo().NetAddress()
  106. r.book.AddAddress(addr, addr)
  107. }
  108. }
  109. // RemovePeer implements Reactor.
  110. func (r *PEXReactor) RemovePeer(p Peer, reason interface{}) {
  111. // If we aren't keeping track of local temp data for each peer here, then we
  112. // don't have to do anything.
  113. }
  114. // Receive implements Reactor by handling incoming PEX messages.
  115. func (r *PEXReactor) Receive(chID byte, src Peer, msgBytes []byte) {
  116. srcAddrStr := src.NodeInfo().RemoteAddr
  117. srcAddr, err := NewNetAddressString(srcAddrStr)
  118. if err != nil {
  119. // this should never happen. TODO: cancel conn
  120. r.Logger.Error("Error in Receive: invalid peer address", "addr", srcAddrStr, "err", err)
  121. return
  122. }
  123. r.IncrementMsgCountForPeer(srcAddrStr)
  124. if r.ReachedMaxMsgCountForPeer(srcAddrStr) {
  125. r.Logger.Error("Maximum number of messages reached for peer", "peer", srcAddrStr)
  126. // TODO remove src from peers?
  127. return
  128. }
  129. _, msg, err := DecodeMessage(msgBytes)
  130. if err != nil {
  131. r.Logger.Error("Error decoding message", "err", err)
  132. return
  133. }
  134. r.Logger.Debug("Received message", "src", src, "chId", chID, "msg", msg)
  135. switch msg := msg.(type) {
  136. case *pexRequestMessage:
  137. // src requested some peers.
  138. // NOTE: we might send an empty selection
  139. r.SendAddrs(src, r.book.GetSelection())
  140. case *pexAddrsMessage:
  141. // We received some peer addresses from src.
  142. // TODO: (We don't want to get spammed with bad peers)
  143. for _, netAddr := range msg.Addrs {
  144. if netAddr != nil {
  145. r.book.AddAddress(netAddr, srcAddr)
  146. }
  147. }
  148. default:
  149. r.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  150. }
  151. }
  152. // RequestPEX asks peer for more addresses.
  153. func (r *PEXReactor) RequestPEX(p Peer) {
  154. p.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}})
  155. }
  156. // SendAddrs sends addrs to the peer.
  157. func (r *PEXReactor) SendAddrs(p Peer, netAddrs []*NetAddress) {
  158. p.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: netAddrs}})
  159. }
  160. // SetEnsurePeersPeriod sets period to ensure peers connected.
  161. func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) {
  162. r.ensurePeersPeriod = d
  163. }
  164. // SetMaxMsgCountByPeer sets maximum messages one peer can send to us during 'msgCountByPeerFlushInterval'.
  165. func (r *PEXReactor) SetMaxMsgCountByPeer(v uint16) {
  166. r.maxMsgCountByPeer = v
  167. }
  168. // ReachedMaxMsgCountForPeer returns true if we received too many
  169. // messages from peer with address `addr`.
  170. // NOTE: assumes the value in the CMap is non-nil
  171. func (r *PEXReactor) ReachedMaxMsgCountForPeer(addr string) bool {
  172. return r.msgCountByPeer.Get(addr).(uint16) >= r.maxMsgCountByPeer
  173. }
  174. // Increment or initialize the msg count for the peer in the CMap
  175. func (r *PEXReactor) IncrementMsgCountForPeer(addr string) {
  176. var count uint16
  177. countI := r.msgCountByPeer.Get(addr)
  178. if countI != nil {
  179. count = countI.(uint16)
  180. }
  181. count++
  182. r.msgCountByPeer.Set(addr, count)
  183. }
  184. // Ensures that sufficient peers are connected. (continuous)
  185. func (r *PEXReactor) ensurePeersRoutine() {
  186. // Randomize when routine starts
  187. ensurePeersPeriodMs := r.ensurePeersPeriod.Nanoseconds() / 1e6
  188. time.Sleep(time.Duration(rand.Int63n(ensurePeersPeriodMs)) * time.Millisecond)
  189. // fire once immediately.
  190. r.ensurePeers()
  191. // fire periodically
  192. ticker := time.NewTicker(r.ensurePeersPeriod)
  193. for {
  194. select {
  195. case <-ticker.C:
  196. r.ensurePeers()
  197. case <-r.Quit:
  198. ticker.Stop()
  199. return
  200. }
  201. }
  202. }
  203. // ensurePeers ensures that sufficient peers are connected. (once)
  204. //
  205. // Old bucket / New bucket are arbitrary categories to denote whether an
  206. // address is vetted or not, and this needs to be determined over time via a
  207. // heuristic that we haven't perfected yet, or, perhaps is manually edited by
  208. // the node operator. It should not be used to compute what addresses are
  209. // already connected or not.
  210. //
  211. // TODO Basically, we need to work harder on our good-peer/bad-peer marking.
  212. // What we're currently doing in terms of marking good/bad peers is just a
  213. // placeholder. It should not be the case that an address becomes old/vetted
  214. // upon a single successful connection.
  215. func (r *PEXReactor) ensurePeers() {
  216. numOutPeers, numInPeers, numDialing := r.Switch.NumPeers()
  217. numToDial := minNumOutboundPeers - (numOutPeers + numDialing)
  218. r.Logger.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial)
  219. if numToDial <= 0 {
  220. return
  221. }
  222. // bias to prefer more vetted peers when we have fewer connections.
  223. // not perfect, but somewhate ensures that we prioritize connecting to more-vetted
  224. // NOTE: range here is [10, 90]. Too high ?
  225. newBias := cmn.MinInt(numOutPeers, 8)*10 + 10
  226. toDial := make(map[ID]*NetAddress)
  227. // Try maxAttempts times to pick numToDial addresses to dial
  228. maxAttempts := numToDial * 3
  229. for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
  230. try := r.book.PickAddress(newBias)
  231. if try == nil {
  232. continue
  233. }
  234. if _, selected := toDial[try.ID]; selected {
  235. continue
  236. }
  237. if dialling := r.Switch.IsDialing(try.ID); dialling {
  238. continue
  239. }
  240. if connected := r.Switch.Peers().Has(try.ID); connected {
  241. continue
  242. }
  243. r.Logger.Info("Will dial address", "addr", try)
  244. toDial[try.ID] = try
  245. }
  246. // Dial picked addresses
  247. for _, item := range toDial {
  248. go func(picked *NetAddress) {
  249. _, err := r.Switch.DialPeerWithAddress(picked, false)
  250. if err != nil {
  251. r.book.MarkAttempt(picked)
  252. }
  253. }(item)
  254. }
  255. // If we need more addresses, pick a random peer and ask for more.
  256. if r.book.NeedMoreAddrs() {
  257. peers := r.Switch.Peers().List()
  258. peersCount := len(peers)
  259. if peersCount > 0 {
  260. peer := peers[rand.Int()%peersCount] // nolint: gas
  261. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  262. r.RequestPEX(peer)
  263. }
  264. }
  265. // If we are not connected to nor dialing anybody, fallback to dialing seeds.
  266. if numOutPeers+numInPeers+numDialing+len(toDial) == 0 {
  267. r.Logger.Info("No addresses to dial nor connected peers. Will dial seeds", "seeds", r.config.Seeds)
  268. r.Switch.DialPeersAsync(r.book, r.config.Seeds, false)
  269. }
  270. }
  271. func (r *PEXReactor) flushMsgCountByPeer() {
  272. ticker := time.NewTicker(msgCountByPeerFlushInterval)
  273. for {
  274. select {
  275. case <-ticker.C:
  276. r.msgCountByPeer.Clear()
  277. case <-r.Quit:
  278. ticker.Stop()
  279. return
  280. }
  281. }
  282. }
  283. //-----------------------------------------------------------------------------
  284. // Messages
  285. const (
  286. msgTypeRequest = byte(0x01)
  287. msgTypeAddrs = byte(0x02)
  288. )
  289. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  290. // either pexRequestMessage, or pexAddrsMessage messages.
  291. type PexMessage interface{}
  292. var _ = wire.RegisterInterface(
  293. struct{ PexMessage }{},
  294. wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest},
  295. wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs},
  296. )
  297. // DecodeMessage implements interface registered above.
  298. func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) {
  299. msgType = bz[0]
  300. n := new(int)
  301. r := bytes.NewReader(bz)
  302. msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage
  303. return
  304. }
  305. /*
  306. A pexRequestMessage requests additional peer addresses.
  307. */
  308. type pexRequestMessage struct {
  309. }
  310. func (m *pexRequestMessage) String() string {
  311. return "[pexRequest]"
  312. }
  313. /*
  314. A message with announced peer addresses.
  315. */
  316. type pexAddrsMessage struct {
  317. Addrs []*NetAddress
  318. }
  319. func (m *pexAddrsMessage) String() string {
  320. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  321. }