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.

679 lines
19 KiB

9 years ago
9 years ago
7 years ago
9 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
7 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
9 years ago
7 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
9 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
7 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package pex
  2. import (
  3. "fmt"
  4. "reflect"
  5. "sort"
  6. "sync"
  7. "time"
  8. amino "github.com/tendermint/go-amino"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  10. "github.com/tendermint/tendermint/p2p"
  11. "github.com/tendermint/tendermint/p2p/conn"
  12. )
  13. type Peer = p2p.Peer
  14. const (
  15. // PexChannel is a channel for PEX messages
  16. PexChannel = byte(0x00)
  17. // over-estimate of max NetAddress size
  18. // hexID (40) + IP (16) + Port (2) + Name (100) ...
  19. // NOTE: dont use massive DNS name ..
  20. maxAddressSize = 256
  21. // NOTE: amplificaiton factor!
  22. // small request results in up to maxMsgSize response
  23. maxMsgSize = maxAddressSize * maxGetSelection
  24. // ensure we have enough peers
  25. defaultEnsurePeersPeriod = 30 * time.Second
  26. defaultMinNumOutboundPeers = p2p.DefaultMinNumOutboundPeers
  27. // Seed/Crawler constants
  28. // We want seeds to only advertise good peers. Therefore they should wait at
  29. // least as long as we expect it to take for a peer to become good before
  30. // disconnecting.
  31. // see consensus/reactor.go: blocksToContributeToBecomeGoodPeer
  32. // 10000 blocks assuming 1s blocks ~ 2.7 hours.
  33. defaultSeedDisconnectWaitPeriod = 3 * time.Hour
  34. defaultCrawlPeerInterval = 2 * time.Minute // don't redial for this. TODO: back-off. what for?
  35. defaultCrawlPeersPeriod = 30 * time.Second // check some peers every this
  36. maxAttemptsToDial = 16 // ~ 35h in total (last attempt - 18h)
  37. // if node connects to seed, it does not have any trusted peers.
  38. // Especially in the beginning, node should have more trusted peers than
  39. // untrusted.
  40. biasToSelectNewPeers = 30 // 70 to select good peers
  41. )
  42. // PEXReactor handles PEX (peer exchange) and ensures that an
  43. // adequate number of peers are connected to the switch.
  44. //
  45. // It uses `AddrBook` (address book) to store `NetAddress`es of the peers.
  46. //
  47. // ## Preventing abuse
  48. //
  49. // Only accept pexAddrsMsg from peers we sent a corresponding pexRequestMsg too.
  50. // Only accept one pexRequestMsg every ~defaultEnsurePeersPeriod.
  51. type PEXReactor struct {
  52. p2p.BaseReactor
  53. book AddrBook
  54. config *PEXReactorConfig
  55. ensurePeersPeriod time.Duration // TODO: should go in the config
  56. // maps to prevent abuse
  57. requestsSent *cmn.CMap // ID->struct{}: unanswered send requests
  58. lastReceivedRequests *cmn.CMap // ID->time.Time: last time peer requested from us
  59. seedAddrs []*p2p.NetAddress
  60. attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)}
  61. }
  62. func (r *PEXReactor) minReceiveRequestInterval() time.Duration {
  63. // NOTE: must be less than ensurePeersPeriod, otherwise we'll request
  64. // peers too quickly from others and they'll think we're bad!
  65. return r.ensurePeersPeriod / 3
  66. }
  67. // PEXReactorConfig holds reactor specific configuration data.
  68. type PEXReactorConfig struct {
  69. // Seed/Crawler mode
  70. SeedMode bool
  71. // Seeds is a list of addresses reactor may use
  72. // if it can't connect to peers in the addrbook.
  73. Seeds []string
  74. }
  75. type _attemptsToDial struct {
  76. number int
  77. lastDialed time.Time
  78. }
  79. // NewPEXReactor creates new PEX reactor.
  80. func NewPEXReactor(b AddrBook, config *PEXReactorConfig) *PEXReactor {
  81. r := &PEXReactor{
  82. book: b,
  83. config: config,
  84. ensurePeersPeriod: defaultEnsurePeersPeriod,
  85. requestsSent: cmn.NewCMap(),
  86. lastReceivedRequests: cmn.NewCMap(),
  87. }
  88. r.BaseReactor = *p2p.NewBaseReactor("PEXReactor", r)
  89. return r
  90. }
  91. // OnStart implements BaseService
  92. func (r *PEXReactor) OnStart() error {
  93. err := r.book.Start()
  94. if err != nil && err != cmn.ErrAlreadyStarted {
  95. return err
  96. }
  97. // return err if user provided a bad seed address
  98. // or a host name that we cant resolve
  99. seedAddrs, err := r.checkSeeds()
  100. if err != nil {
  101. return err
  102. }
  103. r.seedAddrs = seedAddrs
  104. // Check if this node should run
  105. // in seed/crawler mode
  106. if r.config.SeedMode {
  107. go r.crawlPeersRoutine()
  108. } else {
  109. go r.ensurePeersRoutine()
  110. }
  111. return nil
  112. }
  113. // OnStop implements BaseService
  114. func (r *PEXReactor) OnStop() {
  115. r.book.Stop()
  116. }
  117. // GetChannels implements Reactor
  118. func (r *PEXReactor) GetChannels() []*conn.ChannelDescriptor {
  119. return []*conn.ChannelDescriptor{
  120. {
  121. ID: PexChannel,
  122. Priority: 1,
  123. SendQueueCapacity: 10,
  124. },
  125. }
  126. }
  127. // AddPeer implements Reactor by adding peer to the address book (if inbound)
  128. // or by requesting more addresses (if outbound).
  129. func (r *PEXReactor) AddPeer(p Peer) {
  130. if p.IsOutbound() {
  131. // For outbound peers, the address is already in the books -
  132. // either via DialPeersAsync or r.Receive.
  133. // Ask it for more peers if we need.
  134. if r.book.NeedMoreAddrs() {
  135. r.RequestAddrs(p)
  136. }
  137. } else {
  138. // inbound peer is its own source
  139. addr := p.NodeInfo().NetAddress()
  140. src := addr
  141. // add to book. dont RequestAddrs right away because
  142. // we don't trust inbound as much - let ensurePeersRoutine handle it.
  143. err := r.book.AddAddress(addr, src)
  144. r.logErrAddrBook(err)
  145. }
  146. }
  147. func (r *PEXReactor) logErrAddrBook(err error) {
  148. if err != nil {
  149. switch err.(type) {
  150. case ErrAddrBookNilAddr:
  151. r.Logger.Error("Failed to add new address", "err", err)
  152. default:
  153. // non-routable, self, full book, private, etc.
  154. r.Logger.Debug("Failed to add new address", "err", err)
  155. }
  156. }
  157. }
  158. // RemovePeer implements Reactor.
  159. func (r *PEXReactor) RemovePeer(p Peer, reason interface{}) {
  160. id := string(p.ID())
  161. r.requestsSent.Delete(id)
  162. r.lastReceivedRequests.Delete(id)
  163. }
  164. // Receive implements Reactor by handling incoming PEX messages.
  165. func (r *PEXReactor) Receive(chID byte, src Peer, msgBytes []byte) {
  166. msg, err := decodeMsg(msgBytes)
  167. if err != nil {
  168. r.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  169. r.Switch.StopPeerForError(src, err)
  170. return
  171. }
  172. r.Logger.Debug("Received message", "src", src, "chId", chID, "msg", msg)
  173. switch msg := msg.(type) {
  174. case *pexRequestMessage:
  175. // Check we're not receiving too many requests
  176. if err := r.receiveRequest(src); err != nil {
  177. r.Switch.StopPeerForError(src, err)
  178. return
  179. }
  180. // Seeds disconnect after sending a batch of addrs
  181. // NOTE: this is a prime candidate for amplification attacks
  182. // so it's important we
  183. // 1) restrict how frequently peers can request
  184. // 2) limit the output size
  185. if r.config.SeedMode {
  186. r.SendAddrs(src, r.book.GetSelectionWithBias(biasToSelectNewPeers))
  187. r.Switch.StopPeerGracefully(src)
  188. } else {
  189. r.SendAddrs(src, r.book.GetSelection())
  190. }
  191. case *pexAddrsMessage:
  192. // If we asked for addresses, add them to the book
  193. if err := r.ReceiveAddrs(msg.Addrs, src); err != nil {
  194. r.Switch.StopPeerForError(src, err)
  195. return
  196. }
  197. default:
  198. r.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  199. }
  200. }
  201. // enforces a minimum amount of time between requests
  202. func (r *PEXReactor) receiveRequest(src Peer) error {
  203. id := string(src.ID())
  204. v := r.lastReceivedRequests.Get(id)
  205. if v == nil {
  206. // initialize with empty time
  207. lastReceived := time.Time{}
  208. r.lastReceivedRequests.Set(id, lastReceived)
  209. return nil
  210. }
  211. lastReceived := v.(time.Time)
  212. if lastReceived.Equal(time.Time{}) {
  213. // first time gets a free pass. then we start tracking the time
  214. lastReceived = time.Now()
  215. r.lastReceivedRequests.Set(id, lastReceived)
  216. return nil
  217. }
  218. now := time.Now()
  219. minInterval := r.minReceiveRequestInterval()
  220. if now.Sub(lastReceived) < minInterval {
  221. return fmt.Errorf("Peer (%v) sent next PEX request too soon. lastReceived: %v, now: %v, minInterval: %v. Disconnecting",
  222. src.ID(),
  223. lastReceived,
  224. now,
  225. minInterval,
  226. )
  227. }
  228. r.lastReceivedRequests.Set(id, now)
  229. return nil
  230. }
  231. // RequestAddrs asks peer for more addresses if we do not already
  232. // have a request out for this peer.
  233. func (r *PEXReactor) RequestAddrs(p Peer) {
  234. r.Logger.Debug("Request addrs", "from", p)
  235. id := string(p.ID())
  236. if r.requestsSent.Has(id) {
  237. return
  238. }
  239. r.requestsSent.Set(id, struct{}{})
  240. p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexRequestMessage{}))
  241. }
  242. // ReceiveAddrs adds the given addrs to the addrbook if theres an open
  243. // request for this peer and deletes the open request.
  244. // If there's no open request for the src peer, it returns an error.
  245. func (r *PEXReactor) ReceiveAddrs(addrs []*p2p.NetAddress, src Peer) error {
  246. id := string(src.ID())
  247. if !r.requestsSent.Has(id) {
  248. return cmn.NewError("Received unsolicited pexAddrsMessage")
  249. }
  250. r.requestsSent.Delete(id)
  251. srcAddr := src.NodeInfo().NetAddress()
  252. for _, netAddr := range addrs {
  253. // NOTE: GetSelection methods should never return nil addrs
  254. if netAddr == nil {
  255. return cmn.NewError("received nil addr")
  256. }
  257. err := r.book.AddAddress(netAddr, srcAddr)
  258. r.logErrAddrBook(err)
  259. // If this address came from a seed node, try to connect to it without waiting.
  260. for _, seedAddr := range r.seedAddrs {
  261. if seedAddr.Equals(srcAddr) {
  262. r.ensurePeers()
  263. }
  264. }
  265. }
  266. return nil
  267. }
  268. // SendAddrs sends addrs to the peer.
  269. func (r *PEXReactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) {
  270. p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: netAddrs}))
  271. }
  272. // SetEnsurePeersPeriod sets period to ensure peers connected.
  273. func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) {
  274. r.ensurePeersPeriod = d
  275. }
  276. // Ensures that sufficient peers are connected. (continuous)
  277. func (r *PEXReactor) ensurePeersRoutine() {
  278. var (
  279. seed = cmn.NewRand()
  280. jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds())
  281. )
  282. // Randomize first round of communication to avoid thundering herd.
  283. // If no potential peers are present directly start connecting so we guarantee
  284. // swift setup with the help of configured seeds.
  285. if r.hasPotentialPeers() {
  286. time.Sleep(time.Duration(jitter))
  287. }
  288. // fire once immediately.
  289. // ensures we dial the seeds right away if the book is empty
  290. r.ensurePeers()
  291. // fire periodically
  292. ticker := time.NewTicker(r.ensurePeersPeriod)
  293. for {
  294. select {
  295. case <-ticker.C:
  296. r.ensurePeers()
  297. case <-r.Quit():
  298. ticker.Stop()
  299. return
  300. }
  301. }
  302. }
  303. // ensurePeers ensures that sufficient peers are connected. (once)
  304. //
  305. // heuristic that we haven't perfected yet, or, perhaps is manually edited by
  306. // the node operator. It should not be used to compute what addresses are
  307. // already connected or not.
  308. func (r *PEXReactor) ensurePeers() {
  309. var (
  310. out, in, dial = r.Switch.NumPeers()
  311. numToDial = defaultMinNumOutboundPeers - (out + dial)
  312. )
  313. r.Logger.Info(
  314. "Ensure peers",
  315. "numOutPeers", out,
  316. "numInPeers", in,
  317. "numDialing", dial,
  318. "numToDial", numToDial,
  319. )
  320. if numToDial <= 0 {
  321. return
  322. }
  323. // bias to prefer more vetted peers when we have fewer connections.
  324. // not perfect, but somewhate ensures that we prioritize connecting to more-vetted
  325. // NOTE: range here is [10, 90]. Too high ?
  326. newBias := cmn.MinInt(out, 8)*10 + 10
  327. toDial := make(map[p2p.ID]*p2p.NetAddress)
  328. // Try maxAttempts times to pick numToDial addresses to dial
  329. maxAttempts := numToDial * 3
  330. for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
  331. try := r.book.PickAddress(newBias)
  332. if try == nil {
  333. continue
  334. }
  335. if _, selected := toDial[try.ID]; selected {
  336. continue
  337. }
  338. if dialling := r.Switch.IsDialing(try.ID); dialling {
  339. continue
  340. }
  341. if connected := r.Switch.Peers().Has(try.ID); connected {
  342. continue
  343. }
  344. // TODO: consider moving some checks from toDial into here
  345. // so we don't even consider dialing peers that we want to wait
  346. // before dialling again, or have dialed too many times already
  347. r.Logger.Info("Will dial address", "addr", try)
  348. toDial[try.ID] = try
  349. }
  350. // Dial picked addresses
  351. for _, addr := range toDial {
  352. go r.dialPeer(addr)
  353. }
  354. // If we need more addresses, pick a random peer and ask for more.
  355. if r.book.NeedMoreAddrs() {
  356. peers := r.Switch.Peers().List()
  357. peersCount := len(peers)
  358. if peersCount > 0 {
  359. peer := peers[cmn.RandInt()%peersCount] // nolint: gas
  360. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  361. r.RequestAddrs(peer)
  362. }
  363. }
  364. // If we are not connected to nor dialing anybody, fallback to dialing a seed.
  365. if out+in+dial+len(toDial) == 0 {
  366. r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
  367. r.dialSeeds()
  368. }
  369. }
  370. func (r *PEXReactor) dialAttemptsInfo(addr *p2p.NetAddress) (attempts int, lastDialed time.Time) {
  371. _attempts, ok := r.attemptsToDial.Load(addr.DialString())
  372. if !ok {
  373. return
  374. }
  375. atd := _attempts.(_attemptsToDial)
  376. return atd.number, atd.lastDialed
  377. }
  378. func (r *PEXReactor) dialPeer(addr *p2p.NetAddress) {
  379. attempts, lastDialed := r.dialAttemptsInfo(addr)
  380. if attempts > maxAttemptsToDial {
  381. r.Logger.Error("Reached max attempts to dial", "addr", addr, "attempts", attempts)
  382. r.book.MarkBad(addr)
  383. return
  384. }
  385. // exponential backoff if it's not our first attempt to dial given address
  386. if attempts > 0 {
  387. jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
  388. backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second)
  389. sinceLastDialed := time.Since(lastDialed)
  390. if sinceLastDialed < backoffDuration {
  391. r.Logger.Debug("Too early to dial", "addr", addr, "backoff_duration", backoffDuration, "last_dialed", lastDialed, "time_since", sinceLastDialed)
  392. return
  393. }
  394. }
  395. err := r.Switch.DialPeerWithAddress(addr, false)
  396. if err != nil {
  397. r.Logger.Error("Dialing failed", "addr", addr, "err", err, "attempts", attempts)
  398. // TODO: detect more "bad peer" scenarios
  399. if _, ok := err.(p2p.ErrSwitchAuthenticationFailure); ok {
  400. r.book.MarkBad(addr)
  401. r.attemptsToDial.Delete(addr.DialString())
  402. } else {
  403. r.book.MarkAttempt(addr)
  404. // FIXME: if the addr is going to be removed from the addrbook (hard to
  405. // tell at this point), we need to Delete it from attemptsToDial, not
  406. // record another attempt.
  407. // record attempt
  408. r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
  409. }
  410. } else {
  411. // cleanup any history
  412. r.attemptsToDial.Delete(addr.DialString())
  413. }
  414. }
  415. // check seed addresses are well formed
  416. func (r *PEXReactor) checkSeeds() ([]*p2p.NetAddress, error) {
  417. lSeeds := len(r.config.Seeds)
  418. if lSeeds == 0 {
  419. return nil, nil
  420. }
  421. netAddrs, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  422. for _, err := range errs {
  423. if err != nil {
  424. return nil, err
  425. }
  426. }
  427. return netAddrs, nil
  428. }
  429. // randomly dial seeds until we connect to one or exhaust them
  430. func (r *PEXReactor) dialSeeds() {
  431. lSeeds := len(r.config.Seeds)
  432. if lSeeds == 0 {
  433. return
  434. }
  435. perm := cmn.RandPerm(lSeeds)
  436. // perm := r.Switch.rng.Perm(lSeeds)
  437. for _, i := range perm {
  438. // dial a random seed
  439. seedAddr := r.seedAddrs[i]
  440. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  441. if err == nil {
  442. return
  443. }
  444. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  445. }
  446. r.Switch.Logger.Error("Couldn't connect to any seeds")
  447. }
  448. // AttemptsToDial returns the number of attempts to dial specific address. It
  449. // returns 0 if never attempted or successfully connected.
  450. func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
  451. lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
  452. if attempted {
  453. return lAttempts.(_attemptsToDial).number
  454. }
  455. return 0
  456. }
  457. //----------------------------------------------------------
  458. // Explores the network searching for more peers. (continuous)
  459. // Seed/Crawler Mode causes this node to quickly disconnect
  460. // from peers, except other seed nodes.
  461. func (r *PEXReactor) crawlPeersRoutine() {
  462. // Do an initial crawl
  463. r.crawlPeers()
  464. // Fire periodically
  465. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  466. for {
  467. select {
  468. case <-ticker.C:
  469. r.attemptDisconnects()
  470. r.crawlPeers()
  471. case <-r.Quit():
  472. return
  473. }
  474. }
  475. }
  476. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  477. // consulting the Switch as well as the AddrBook.
  478. func (r *PEXReactor) hasPotentialPeers() bool {
  479. out, in, dial := r.Switch.NumPeers()
  480. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  481. }
  482. // crawlPeerInfo handles temporary data needed for the
  483. // network crawling performed during seed/crawler mode.
  484. type crawlPeerInfo struct {
  485. // The listening address of a potential peer we learned about
  486. Addr *p2p.NetAddress
  487. // The last time we attempt to reach this address
  488. LastAttempt time.Time
  489. // The last time we successfully reached this address
  490. LastSuccess time.Time
  491. }
  492. // oldestFirst implements sort.Interface for []crawlPeerInfo
  493. // based on the LastAttempt field.
  494. type oldestFirst []crawlPeerInfo
  495. func (of oldestFirst) Len() int { return len(of) }
  496. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  497. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  498. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  499. // NOTE: The status information is ordered as described above.
  500. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  501. var of oldestFirst
  502. // TODO: be more selective
  503. addrs := r.book.ListOfKnownAddresses()
  504. for _, addr := range addrs {
  505. if len(addr.ID()) == 0 {
  506. continue // dont use peers without id
  507. }
  508. of = append(of, crawlPeerInfo{
  509. Addr: addr.Addr,
  510. LastAttempt: addr.LastAttempt,
  511. LastSuccess: addr.LastSuccess,
  512. })
  513. }
  514. sort.Sort(of)
  515. return of
  516. }
  517. // crawlPeers will crawl the network looking for new peer addresses. (once)
  518. func (r *PEXReactor) crawlPeers() {
  519. peerInfos := r.getPeersToCrawl()
  520. now := time.Now()
  521. // Use addresses we know of to reach additional peers
  522. for _, pi := range peerInfos {
  523. // Do not attempt to connect with peers we recently dialed
  524. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  525. continue
  526. }
  527. // Otherwise, attempt to connect with the known address
  528. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  529. if err != nil {
  530. r.book.MarkAttempt(pi.Addr)
  531. continue
  532. }
  533. // Ask for more addresses
  534. peer := r.Switch.Peers().Get(pi.Addr.ID)
  535. if peer != nil {
  536. r.RequestAddrs(peer)
  537. }
  538. }
  539. }
  540. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  541. func (r *PEXReactor) attemptDisconnects() {
  542. for _, peer := range r.Switch.Peers().List() {
  543. if peer.Status().Duration < defaultSeedDisconnectWaitPeriod {
  544. continue
  545. }
  546. if peer.IsPersistent() {
  547. continue
  548. }
  549. r.Switch.StopPeerGracefully(peer)
  550. }
  551. }
  552. //-----------------------------------------------------------------------------
  553. // Messages
  554. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  555. // either pexRequestMessage, or pexAddrsMessage messages.
  556. type PexMessage interface{}
  557. func RegisterPexMessage(cdc *amino.Codec) {
  558. cdc.RegisterInterface((*PexMessage)(nil), nil)
  559. cdc.RegisterConcrete(&pexRequestMessage{}, "tendermint/p2p/PexRequestMessage", nil)
  560. cdc.RegisterConcrete(&pexAddrsMessage{}, "tendermint/p2p/PexAddrsMessage", nil)
  561. }
  562. func decodeMsg(bz []byte) (msg PexMessage, err error) {
  563. if len(bz) > maxMsgSize {
  564. return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  565. }
  566. err = cdc.UnmarshalBinaryBare(bz, &msg)
  567. return
  568. }
  569. /*
  570. A pexRequestMessage requests additional peer addresses.
  571. */
  572. type pexRequestMessage struct {
  573. }
  574. func (m *pexRequestMessage) String() string {
  575. return "[pexRequest]"
  576. }
  577. /*
  578. A message with announced peer addresses.
  579. */
  580. type pexAddrsMessage struct {
  581. Addrs []*p2p.NetAddress
  582. }
  583. func (m *pexAddrsMessage) String() string {
  584. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  585. }