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.

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