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.

682 lines
19 KiB

9 years ago
9 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
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. "github.com/pkg/errors"
  9. amino "github.com/tendermint/go-amino"
  10. cmn "github.com/tendermint/tendermint/libs/common"
  11. "github.com/tendermint/tendermint/p2p"
  12. "github.com/tendermint/tendermint/p2p/conn"
  13. )
  14. type Peer = p2p.Peer
  15. const (
  16. // PexChannel is a channel for PEX messages
  17. PexChannel = byte(0x00)
  18. // over-estimate of max NetAddress size
  19. // hexID (40) + IP (16) + Port (2) + Name (100) ...
  20. // NOTE: dont use massive DNS name ..
  21. maxAddressSize = 256
  22. // NOTE: amplificaiton factor!
  23. // small request results in up to maxMsgSize response
  24. maxMsgSize = maxAddressSize * maxGetSelection
  25. // ensure we have enough peers
  26. defaultEnsurePeersPeriod = 30 * time.Second
  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. numOnline, seedAddrs, err := r.checkSeeds()
  98. if err != nil {
  99. return err
  100. } else if numOnline == 0 && r.book.Empty() {
  101. return errors.New("Address book is empty, and could not connect to any seed nodes")
  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 = r.Switch.MaxNumOutboundPeers() - (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. // checkSeeds checks that addresses are well formed.
  416. // Returns number of seeds we can connect to, along with all seeds addrs.
  417. // return err if user provided any badly formatted seed addresses.
  418. // Doesn't error if the seed node can't be reached.
  419. // numOnline returns -1 if no seed nodes were in the initial configuration.
  420. func (r *PEXReactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err error) {
  421. lSeeds := len(r.config.Seeds)
  422. if lSeeds == 0 {
  423. return -1, nil, nil
  424. }
  425. netAddrs, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  426. numOnline = lSeeds - len(errs)
  427. for _, err := range errs {
  428. switch e := err.(type) {
  429. case p2p.ErrNetAddressLookup:
  430. r.Logger.Error("Connecting to seed failed", "err", e)
  431. default:
  432. return 0, nil, errors.Wrap(e, "seed node configuration has error")
  433. }
  434. }
  435. return
  436. }
  437. // randomly dial seeds until we connect to one or exhaust them
  438. func (r *PEXReactor) dialSeeds() {
  439. perm := cmn.RandPerm(len(r.seedAddrs))
  440. // perm := r.Switch.rng.Perm(lSeeds)
  441. for _, i := range perm {
  442. // dial a random seed
  443. seedAddr := r.seedAddrs[i]
  444. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  445. if err == nil {
  446. return
  447. }
  448. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  449. }
  450. r.Switch.Logger.Error("Couldn't connect to any seeds")
  451. }
  452. // AttemptsToDial returns the number of attempts to dial specific address. It
  453. // returns 0 if never attempted or successfully connected.
  454. func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
  455. lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
  456. if attempted {
  457. return lAttempts.(_attemptsToDial).number
  458. }
  459. return 0
  460. }
  461. //----------------------------------------------------------
  462. // Explores the network searching for more peers. (continuous)
  463. // Seed/Crawler Mode causes this node to quickly disconnect
  464. // from peers, except other seed nodes.
  465. func (r *PEXReactor) crawlPeersRoutine() {
  466. // Do an initial crawl
  467. r.crawlPeers()
  468. // Fire periodically
  469. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  470. for {
  471. select {
  472. case <-ticker.C:
  473. r.attemptDisconnects()
  474. r.crawlPeers()
  475. case <-r.Quit():
  476. return
  477. }
  478. }
  479. }
  480. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  481. // consulting the Switch as well as the AddrBook.
  482. func (r *PEXReactor) hasPotentialPeers() bool {
  483. out, in, dial := r.Switch.NumPeers()
  484. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  485. }
  486. // crawlPeerInfo handles temporary data needed for the
  487. // network crawling performed during seed/crawler mode.
  488. type crawlPeerInfo struct {
  489. // The listening address of a potential peer we learned about
  490. Addr *p2p.NetAddress
  491. // The last time we attempt to reach this address
  492. LastAttempt time.Time
  493. // The last time we successfully reached this address
  494. LastSuccess time.Time
  495. }
  496. // oldestFirst implements sort.Interface for []crawlPeerInfo
  497. // based on the LastAttempt field.
  498. type oldestFirst []crawlPeerInfo
  499. func (of oldestFirst) Len() int { return len(of) }
  500. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  501. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  502. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  503. // NOTE: The status information is ordered as described above.
  504. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  505. var of oldestFirst
  506. // TODO: be more selective
  507. addrs := r.book.ListOfKnownAddresses()
  508. for _, addr := range addrs {
  509. if len(addr.ID()) == 0 {
  510. continue // dont use peers without id
  511. }
  512. of = append(of, crawlPeerInfo{
  513. Addr: addr.Addr,
  514. LastAttempt: addr.LastAttempt,
  515. LastSuccess: addr.LastSuccess,
  516. })
  517. }
  518. sort.Sort(of)
  519. return of
  520. }
  521. // crawlPeers will crawl the network looking for new peer addresses. (once)
  522. func (r *PEXReactor) crawlPeers() {
  523. peerInfos := r.getPeersToCrawl()
  524. now := time.Now()
  525. // Use addresses we know of to reach additional peers
  526. for _, pi := range peerInfos {
  527. // Do not attempt to connect with peers we recently dialed
  528. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  529. continue
  530. }
  531. // Otherwise, attempt to connect with the known address
  532. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  533. if err != nil {
  534. r.book.MarkAttempt(pi.Addr)
  535. continue
  536. }
  537. // Ask for more addresses
  538. peer := r.Switch.Peers().Get(pi.Addr.ID)
  539. if peer != nil {
  540. r.RequestAddrs(peer)
  541. }
  542. }
  543. }
  544. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  545. func (r *PEXReactor) attemptDisconnects() {
  546. for _, peer := range r.Switch.Peers().List() {
  547. if peer.Status().Duration < defaultSeedDisconnectWaitPeriod {
  548. continue
  549. }
  550. if peer.IsPersistent() {
  551. continue
  552. }
  553. r.Switch.StopPeerGracefully(peer)
  554. }
  555. }
  556. //-----------------------------------------------------------------------------
  557. // Messages
  558. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  559. // either pexRequestMessage, or pexAddrsMessage messages.
  560. type PexMessage interface{}
  561. func RegisterPexMessage(cdc *amino.Codec) {
  562. cdc.RegisterInterface((*PexMessage)(nil), nil)
  563. cdc.RegisterConcrete(&pexRequestMessage{}, "tendermint/p2p/PexRequestMessage", nil)
  564. cdc.RegisterConcrete(&pexAddrsMessage{}, "tendermint/p2p/PexAddrsMessage", nil)
  565. }
  566. func decodeMsg(bz []byte) (msg PexMessage, err error) {
  567. if len(bz) > maxMsgSize {
  568. return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  569. }
  570. err = cdc.UnmarshalBinaryBare(bz, &msg)
  571. return
  572. }
  573. /*
  574. A pexRequestMessage requests additional peer addresses.
  575. */
  576. type pexRequestMessage struct {
  577. }
  578. func (m *pexRequestMessage) String() string {
  579. return "[pexRequest]"
  580. }
  581. /*
  582. A message with announced peer addresses.
  583. */
  584. type pexAddrsMessage struct {
  585. Addrs []*p2p.NetAddress
  586. }
  587. func (m *pexAddrsMessage) String() string {
  588. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  589. }