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
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 r.Switch.IsDialingOrExistingAddress(try) {
  339. continue
  340. }
  341. // TODO: consider moving some checks from toDial into here
  342. // so we don't even consider dialing peers that we want to wait
  343. // before dialling again, or have dialed too many times already
  344. r.Logger.Info("Will dial address", "addr", try)
  345. toDial[try.ID] = try
  346. }
  347. // Dial picked addresses
  348. for _, addr := range toDial {
  349. go r.dialPeer(addr)
  350. }
  351. // If we need more addresses, pick a random peer and ask for more.
  352. if r.book.NeedMoreAddrs() {
  353. peers := r.Switch.Peers().List()
  354. peersCount := len(peers)
  355. if peersCount > 0 {
  356. peer := peers[cmn.RandInt()%peersCount] // nolint: gas
  357. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  358. r.RequestAddrs(peer)
  359. }
  360. }
  361. // If we are not connected to nor dialing anybody, fallback to dialing a seed.
  362. if out+in+dial+len(toDial) == 0 {
  363. r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
  364. r.dialSeeds()
  365. }
  366. }
  367. func (r *PEXReactor) dialAttemptsInfo(addr *p2p.NetAddress) (attempts int, lastDialed time.Time) {
  368. _attempts, ok := r.attemptsToDial.Load(addr.DialString())
  369. if !ok {
  370. return
  371. }
  372. atd := _attempts.(_attemptsToDial)
  373. return atd.number, atd.lastDialed
  374. }
  375. func (r *PEXReactor) dialPeer(addr *p2p.NetAddress) {
  376. attempts, lastDialed := r.dialAttemptsInfo(addr)
  377. if attempts > maxAttemptsToDial {
  378. r.Logger.Error("Reached max attempts to dial", "addr", addr, "attempts", attempts)
  379. r.book.MarkBad(addr)
  380. return
  381. }
  382. // exponential backoff if it's not our first attempt to dial given address
  383. if attempts > 0 {
  384. jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
  385. backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second)
  386. sinceLastDialed := time.Since(lastDialed)
  387. if sinceLastDialed < backoffDuration {
  388. r.Logger.Debug("Too early to dial", "addr", addr, "backoff_duration", backoffDuration, "last_dialed", lastDialed, "time_since", sinceLastDialed)
  389. return
  390. }
  391. }
  392. err := r.Switch.DialPeerWithAddress(addr, false)
  393. if err != nil {
  394. r.Logger.Error("Dialing failed", "addr", addr, "err", err, "attempts", attempts)
  395. // TODO: detect more "bad peer" scenarios
  396. if _, ok := err.(p2p.ErrSwitchAuthenticationFailure); ok {
  397. r.book.MarkBad(addr)
  398. r.attemptsToDial.Delete(addr.DialString())
  399. } else {
  400. r.book.MarkAttempt(addr)
  401. // FIXME: if the addr is going to be removed from the addrbook (hard to
  402. // tell at this point), we need to Delete it from attemptsToDial, not
  403. // record another attempt.
  404. // record attempt
  405. r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
  406. }
  407. } else {
  408. // cleanup any history
  409. r.attemptsToDial.Delete(addr.DialString())
  410. }
  411. }
  412. // checkSeeds checks that addresses are well formed.
  413. // Returns number of seeds we can connect to, along with all seeds addrs.
  414. // return err if user provided any badly formatted seed addresses.
  415. // Doesn't error if the seed node can't be reached.
  416. // numOnline returns -1 if no seed nodes were in the initial configuration.
  417. func (r *PEXReactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err error) {
  418. lSeeds := len(r.config.Seeds)
  419. if lSeeds == 0 {
  420. return -1, nil, nil
  421. }
  422. netAddrs, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  423. numOnline = lSeeds - len(errs)
  424. for _, err := range errs {
  425. switch e := err.(type) {
  426. case p2p.ErrNetAddressLookup:
  427. r.Logger.Error("Connecting to seed failed", "err", e)
  428. default:
  429. return 0, nil, errors.Wrap(e, "seed node configuration has error")
  430. }
  431. }
  432. return
  433. }
  434. // randomly dial seeds until we connect to one or exhaust them
  435. func (r *PEXReactor) dialSeeds() {
  436. perm := cmn.RandPerm(len(r.seedAddrs))
  437. // perm := r.Switch.rng.Perm(lSeeds)
  438. for _, i := range perm {
  439. // dial a random seed
  440. seedAddr := r.seedAddrs[i]
  441. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  442. if err == nil {
  443. return
  444. }
  445. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  446. }
  447. r.Switch.Logger.Error("Couldn't connect to any seeds")
  448. }
  449. // AttemptsToDial returns the number of attempts to dial specific address. It
  450. // returns 0 if never attempted or successfully connected.
  451. func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
  452. lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
  453. if attempted {
  454. return lAttempts.(_attemptsToDial).number
  455. }
  456. return 0
  457. }
  458. //----------------------------------------------------------
  459. // Explores the network searching for more peers. (continuous)
  460. // Seed/Crawler Mode causes this node to quickly disconnect
  461. // from peers, except other seed nodes.
  462. func (r *PEXReactor) crawlPeersRoutine() {
  463. // Do an initial crawl
  464. r.crawlPeers()
  465. // Fire periodically
  466. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  467. for {
  468. select {
  469. case <-ticker.C:
  470. r.attemptDisconnects()
  471. r.crawlPeers()
  472. case <-r.Quit():
  473. return
  474. }
  475. }
  476. }
  477. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  478. // consulting the Switch as well as the AddrBook.
  479. func (r *PEXReactor) hasPotentialPeers() bool {
  480. out, in, dial := r.Switch.NumPeers()
  481. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  482. }
  483. // crawlPeerInfo handles temporary data needed for the
  484. // network crawling performed during seed/crawler mode.
  485. type crawlPeerInfo struct {
  486. // The listening address of a potential peer we learned about
  487. Addr *p2p.NetAddress
  488. // The last time we attempt to reach this address
  489. LastAttempt time.Time
  490. // The last time we successfully reached this address
  491. LastSuccess time.Time
  492. }
  493. // oldestFirst implements sort.Interface for []crawlPeerInfo
  494. // based on the LastAttempt field.
  495. type oldestFirst []crawlPeerInfo
  496. func (of oldestFirst) Len() int { return len(of) }
  497. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  498. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  499. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  500. // NOTE: The status information is ordered as described above.
  501. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  502. var of oldestFirst
  503. // TODO: be more selective
  504. addrs := r.book.ListOfKnownAddresses()
  505. for _, addr := range addrs {
  506. if len(addr.ID()) == 0 {
  507. continue // dont use peers without id
  508. }
  509. of = append(of, crawlPeerInfo{
  510. Addr: addr.Addr,
  511. LastAttempt: addr.LastAttempt,
  512. LastSuccess: addr.LastSuccess,
  513. })
  514. }
  515. sort.Sort(of)
  516. return of
  517. }
  518. // crawlPeers will crawl the network looking for new peer addresses. (once)
  519. func (r *PEXReactor) crawlPeers() {
  520. peerInfos := r.getPeersToCrawl()
  521. now := time.Now()
  522. // Use addresses we know of to reach additional peers
  523. for _, pi := range peerInfos {
  524. // Do not attempt to connect with peers we recently dialed
  525. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  526. continue
  527. }
  528. // Otherwise, attempt to connect with the known address
  529. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  530. if err != nil {
  531. r.book.MarkAttempt(pi.Addr)
  532. continue
  533. }
  534. // Ask for more addresses
  535. peer := r.Switch.Peers().Get(pi.Addr.ID)
  536. if peer != nil {
  537. r.RequestAddrs(peer)
  538. }
  539. }
  540. }
  541. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  542. func (r *PEXReactor) attemptDisconnects() {
  543. for _, peer := range r.Switch.Peers().List() {
  544. if peer.Status().Duration < defaultSeedDisconnectWaitPeriod {
  545. continue
  546. }
  547. if peer.IsPersistent() {
  548. continue
  549. }
  550. r.Switch.StopPeerGracefully(peer)
  551. }
  552. }
  553. //-----------------------------------------------------------------------------
  554. // Messages
  555. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  556. // either pexRequestMessage, or pexAddrsMessage messages.
  557. type PexMessage interface{}
  558. func RegisterPexMessage(cdc *amino.Codec) {
  559. cdc.RegisterInterface((*PexMessage)(nil), nil)
  560. cdc.RegisterConcrete(&pexRequestMessage{}, "tendermint/p2p/PexRequestMessage", nil)
  561. cdc.RegisterConcrete(&pexAddrsMessage{}, "tendermint/p2p/PexAddrsMessage", nil)
  562. }
  563. func decodeMsg(bz []byte) (msg PexMessage, err error) {
  564. if len(bz) > maxMsgSize {
  565. return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  566. }
  567. err = cdc.UnmarshalBinaryBare(bz, &msg)
  568. return
  569. }
  570. /*
  571. A pexRequestMessage requests additional peer addresses.
  572. */
  573. type pexRequestMessage struct {
  574. }
  575. func (m *pexRequestMessage) String() string {
  576. return "[pexRequest]"
  577. }
  578. /*
  579. A message with announced peer addresses.
  580. */
  581. type pexAddrsMessage struct {
  582. Addrs []*p2p.NetAddress
  583. }
  584. func (m *pexAddrsMessage) String() string {
  585. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  586. }