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.

683 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. defaultMinNumOutboundPeers = p2p.DefaultMinNumOutboundPeers
  28. // Seed/Crawler constants
  29. // We want seeds to only advertise good peers. Therefore they should wait at
  30. // least as long as we expect it to take for a peer to become good before
  31. // disconnecting.
  32. // see consensus/reactor.go: blocksToContributeToBecomeGoodPeer
  33. // 10000 blocks assuming 1s blocks ~ 2.7 hours.
  34. defaultSeedDisconnectWaitPeriod = 3 * time.Hour
  35. defaultCrawlPeerInterval = 2 * time.Minute // don't redial for this. TODO: back-off. what for?
  36. defaultCrawlPeersPeriod = 30 * time.Second // check some peers every this
  37. maxAttemptsToDial = 16 // ~ 35h in total (last attempt - 18h)
  38. // if node connects to seed, it does not have any trusted peers.
  39. // Especially in the beginning, node should have more trusted peers than
  40. // untrusted.
  41. biasToSelectNewPeers = 30 // 70 to select good peers
  42. )
  43. // PEXReactor handles PEX (peer exchange) and ensures that an
  44. // adequate number of peers are connected to the switch.
  45. //
  46. // It uses `AddrBook` (address book) to store `NetAddress`es of the peers.
  47. //
  48. // ## Preventing abuse
  49. //
  50. // Only accept pexAddrsMsg from peers we sent a corresponding pexRequestMsg too.
  51. // Only accept one pexRequestMsg every ~defaultEnsurePeersPeriod.
  52. type PEXReactor struct {
  53. p2p.BaseReactor
  54. book AddrBook
  55. config *PEXReactorConfig
  56. ensurePeersPeriod time.Duration // TODO: should go in the config
  57. // maps to prevent abuse
  58. requestsSent *cmn.CMap // ID->struct{}: unanswered send requests
  59. lastReceivedRequests *cmn.CMap // ID->time.Time: last time peer requested from us
  60. seedAddrs []*p2p.NetAddress
  61. attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)}
  62. }
  63. func (r *PEXReactor) minReceiveRequestInterval() time.Duration {
  64. // NOTE: must be less than ensurePeersPeriod, otherwise we'll request
  65. // peers too quickly from others and they'll think we're bad!
  66. return r.ensurePeersPeriod / 3
  67. }
  68. // PEXReactorConfig holds reactor specific configuration data.
  69. type PEXReactorConfig struct {
  70. // Seed/Crawler mode
  71. SeedMode bool
  72. // Seeds is a list of addresses reactor may use
  73. // if it can't connect to peers in the addrbook.
  74. Seeds []string
  75. }
  76. type _attemptsToDial struct {
  77. number int
  78. lastDialed time.Time
  79. }
  80. // NewPEXReactor creates new PEX reactor.
  81. func NewPEXReactor(b AddrBook, config *PEXReactorConfig) *PEXReactor {
  82. r := &PEXReactor{
  83. book: b,
  84. config: config,
  85. ensurePeersPeriod: defaultEnsurePeersPeriod,
  86. requestsSent: cmn.NewCMap(),
  87. lastReceivedRequests: cmn.NewCMap(),
  88. }
  89. r.BaseReactor = *p2p.NewBaseReactor("PEXReactor", r)
  90. return r
  91. }
  92. // OnStart implements BaseService
  93. func (r *PEXReactor) OnStart() error {
  94. err := r.book.Start()
  95. if err != nil && err != cmn.ErrAlreadyStarted {
  96. return err
  97. }
  98. numOnline, seedAddrs, err := r.checkSeeds()
  99. if err != nil {
  100. return err
  101. } else if numOnline == 0 && r.book.Empty() {
  102. return errors.New("Address book is empty, and could not connect to any seed nodes")
  103. }
  104. r.seedAddrs = seedAddrs
  105. // Check if this node should run
  106. // in seed/crawler mode
  107. if r.config.SeedMode {
  108. go r.crawlPeersRoutine()
  109. } else {
  110. go r.ensurePeersRoutine()
  111. }
  112. return nil
  113. }
  114. // OnStop implements BaseService
  115. func (r *PEXReactor) 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. // If this address came from a seed node, try to connect to it without waiting.
  261. for _, seedAddr := range r.seedAddrs {
  262. if seedAddr.Equals(srcAddr) {
  263. r.ensurePeers()
  264. }
  265. }
  266. }
  267. return nil
  268. }
  269. // SendAddrs sends addrs to the peer.
  270. func (r *PEXReactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) {
  271. p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: netAddrs}))
  272. }
  273. // SetEnsurePeersPeriod sets period to ensure peers connected.
  274. func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) {
  275. r.ensurePeersPeriod = d
  276. }
  277. // Ensures that sufficient peers are connected. (continuous)
  278. func (r *PEXReactor) ensurePeersRoutine() {
  279. var (
  280. seed = cmn.NewRand()
  281. jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds())
  282. )
  283. // Randomize first round of communication to avoid thundering herd.
  284. // If no potential peers are present directly start connecting so we guarantee
  285. // swift setup with the help of configured seeds.
  286. if r.hasPotentialPeers() {
  287. time.Sleep(time.Duration(jitter))
  288. }
  289. // fire once immediately.
  290. // ensures we dial the seeds right away if the book is empty
  291. r.ensurePeers()
  292. // fire periodically
  293. ticker := time.NewTicker(r.ensurePeersPeriod)
  294. for {
  295. select {
  296. case <-ticker.C:
  297. r.ensurePeers()
  298. case <-r.Quit():
  299. ticker.Stop()
  300. return
  301. }
  302. }
  303. }
  304. // ensurePeers ensures that sufficient peers are connected. (once)
  305. //
  306. // heuristic that we haven't perfected yet, or, perhaps is manually edited by
  307. // the node operator. It should not be used to compute what addresses are
  308. // already connected or not.
  309. func (r *PEXReactor) ensurePeers() {
  310. var (
  311. out, in, dial = r.Switch.NumPeers()
  312. numToDial = defaultMinNumOutboundPeers - (out + dial)
  313. )
  314. r.Logger.Info(
  315. "Ensure peers",
  316. "numOutPeers", out,
  317. "numInPeers", in,
  318. "numDialing", dial,
  319. "numToDial", numToDial,
  320. )
  321. if numToDial <= 0 {
  322. return
  323. }
  324. // bias to prefer more vetted peers when we have fewer connections.
  325. // not perfect, but somewhate ensures that we prioritize connecting to more-vetted
  326. // NOTE: range here is [10, 90]. Too high ?
  327. newBias := cmn.MinInt(out, 8)*10 + 10
  328. toDial := make(map[p2p.ID]*p2p.NetAddress)
  329. // Try maxAttempts times to pick numToDial addresses to dial
  330. maxAttempts := numToDial * 3
  331. for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
  332. try := r.book.PickAddress(newBias)
  333. if try == nil {
  334. continue
  335. }
  336. if _, selected := toDial[try.ID]; selected {
  337. continue
  338. }
  339. if dialling := r.Switch.IsDialing(try.ID); dialling {
  340. continue
  341. }
  342. if connected := r.Switch.Peers().Has(try.ID); connected {
  343. continue
  344. }
  345. // TODO: consider moving some checks from toDial into here
  346. // so we don't even consider dialing peers that we want to wait
  347. // before dialling again, or have dialed too many times already
  348. r.Logger.Info("Will dial address", "addr", try)
  349. toDial[try.ID] = try
  350. }
  351. // Dial picked addresses
  352. for _, addr := range toDial {
  353. go r.dialPeer(addr)
  354. }
  355. // If we need more addresses, pick a random peer and ask for more.
  356. if r.book.NeedMoreAddrs() {
  357. peers := r.Switch.Peers().List()
  358. peersCount := len(peers)
  359. if peersCount > 0 {
  360. peer := peers[cmn.RandInt()%peersCount] // nolint: gas
  361. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  362. r.RequestAddrs(peer)
  363. }
  364. }
  365. // If we are not connected to nor dialing anybody, fallback to dialing a seed.
  366. if out+in+dial+len(toDial) == 0 {
  367. r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
  368. r.dialSeeds()
  369. }
  370. }
  371. func (r *PEXReactor) dialAttemptsInfo(addr *p2p.NetAddress) (attempts int, lastDialed time.Time) {
  372. _attempts, ok := r.attemptsToDial.Load(addr.DialString())
  373. if !ok {
  374. return
  375. }
  376. atd := _attempts.(_attemptsToDial)
  377. return atd.number, atd.lastDialed
  378. }
  379. func (r *PEXReactor) dialPeer(addr *p2p.NetAddress) {
  380. attempts, lastDialed := r.dialAttemptsInfo(addr)
  381. if attempts > maxAttemptsToDial {
  382. r.Logger.Error("Reached max attempts to dial", "addr", addr, "attempts", attempts)
  383. r.book.MarkBad(addr)
  384. return
  385. }
  386. // exponential backoff if it's not our first attempt to dial given address
  387. if attempts > 0 {
  388. jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
  389. backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second)
  390. sinceLastDialed := time.Since(lastDialed)
  391. if sinceLastDialed < backoffDuration {
  392. r.Logger.Debug("Too early to dial", "addr", addr, "backoff_duration", backoffDuration, "last_dialed", lastDialed, "time_since", sinceLastDialed)
  393. return
  394. }
  395. }
  396. err := r.Switch.DialPeerWithAddress(addr, false)
  397. if err != nil {
  398. r.Logger.Error("Dialing failed", "addr", addr, "err", err, "attempts", attempts)
  399. // TODO: detect more "bad peer" scenarios
  400. if _, ok := err.(p2p.ErrSwitchAuthenticationFailure); ok {
  401. r.book.MarkBad(addr)
  402. r.attemptsToDial.Delete(addr.DialString())
  403. } else {
  404. r.book.MarkAttempt(addr)
  405. // FIXME: if the addr is going to be removed from the addrbook (hard to
  406. // tell at this point), we need to Delete it from attemptsToDial, not
  407. // record another attempt.
  408. // record attempt
  409. r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
  410. }
  411. } else {
  412. // cleanup any history
  413. r.attemptsToDial.Delete(addr.DialString())
  414. }
  415. }
  416. // checkSeeds checks that addresses are well formed.
  417. // Returns number of seeds we can connect to, along with all seeds addrs.
  418. // return err if user provided any badly formatted seed addresses.
  419. // Doesn't error if the seed node can't be reached.
  420. // numOnline returns -1 if no seed nodes were in the initial configuration.
  421. func (r *PEXReactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err error) {
  422. lSeeds := len(r.config.Seeds)
  423. if lSeeds == 0 {
  424. return -1, nil, nil
  425. }
  426. netAddrs, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  427. numOnline = lSeeds - len(errs)
  428. for _, err := range errs {
  429. switch e := err.(type) {
  430. case p2p.ErrNetAddressLookup:
  431. r.Logger.Error("Connecting to seed failed", "err", e)
  432. default:
  433. return 0, nil, errors.Wrap(e, "seed node configuration has error")
  434. }
  435. }
  436. return
  437. }
  438. // randomly dial seeds until we connect to one or exhaust them
  439. func (r *PEXReactor) dialSeeds() {
  440. perm := cmn.RandPerm(len(r.seedAddrs))
  441. // perm := r.Switch.rng.Perm(lSeeds)
  442. for _, i := range perm {
  443. // dial a random seed
  444. seedAddr := r.seedAddrs[i]
  445. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  446. if err == nil {
  447. return
  448. }
  449. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  450. }
  451. r.Switch.Logger.Error("Couldn't connect to any seeds")
  452. }
  453. // AttemptsToDial returns the number of attempts to dial specific address. It
  454. // returns 0 if never attempted or successfully connected.
  455. func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
  456. lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
  457. if attempted {
  458. return lAttempts.(_attemptsToDial).number
  459. }
  460. return 0
  461. }
  462. //----------------------------------------------------------
  463. // Explores the network searching for more peers. (continuous)
  464. // Seed/Crawler Mode causes this node to quickly disconnect
  465. // from peers, except other seed nodes.
  466. func (r *PEXReactor) crawlPeersRoutine() {
  467. // Do an initial crawl
  468. r.crawlPeers()
  469. // Fire periodically
  470. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  471. for {
  472. select {
  473. case <-ticker.C:
  474. r.attemptDisconnects()
  475. r.crawlPeers()
  476. case <-r.Quit():
  477. return
  478. }
  479. }
  480. }
  481. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  482. // consulting the Switch as well as the AddrBook.
  483. func (r *PEXReactor) hasPotentialPeers() bool {
  484. out, in, dial := r.Switch.NumPeers()
  485. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  486. }
  487. // crawlPeerInfo handles temporary data needed for the
  488. // network crawling performed during seed/crawler mode.
  489. type crawlPeerInfo struct {
  490. // The listening address of a potential peer we learned about
  491. Addr *p2p.NetAddress
  492. // The last time we attempt to reach this address
  493. LastAttempt time.Time
  494. // The last time we successfully reached this address
  495. LastSuccess time.Time
  496. }
  497. // oldestFirst implements sort.Interface for []crawlPeerInfo
  498. // based on the LastAttempt field.
  499. type oldestFirst []crawlPeerInfo
  500. func (of oldestFirst) Len() int { return len(of) }
  501. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  502. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  503. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  504. // NOTE: The status information is ordered as described above.
  505. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  506. var of oldestFirst
  507. // TODO: be more selective
  508. addrs := r.book.ListOfKnownAddresses()
  509. for _, addr := range addrs {
  510. if len(addr.ID()) == 0 {
  511. continue // dont use peers without id
  512. }
  513. of = append(of, crawlPeerInfo{
  514. Addr: addr.Addr,
  515. LastAttempt: addr.LastAttempt,
  516. LastSuccess: addr.LastSuccess,
  517. })
  518. }
  519. sort.Sort(of)
  520. return of
  521. }
  522. // crawlPeers will crawl the network looking for new peer addresses. (once)
  523. func (r *PEXReactor) crawlPeers() {
  524. peerInfos := r.getPeersToCrawl()
  525. now := time.Now()
  526. // Use addresses we know of to reach additional peers
  527. for _, pi := range peerInfos {
  528. // Do not attempt to connect with peers we recently dialed
  529. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  530. continue
  531. }
  532. // Otherwise, attempt to connect with the known address
  533. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  534. if err != nil {
  535. r.book.MarkAttempt(pi.Addr)
  536. continue
  537. }
  538. // Ask for more addresses
  539. peer := r.Switch.Peers().Get(pi.Addr.ID)
  540. if peer != nil {
  541. r.RequestAddrs(peer)
  542. }
  543. }
  544. }
  545. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  546. func (r *PEXReactor) attemptDisconnects() {
  547. for _, peer := range r.Switch.Peers().List() {
  548. if peer.Status().Duration < defaultSeedDisconnectWaitPeriod {
  549. continue
  550. }
  551. if peer.IsPersistent() {
  552. continue
  553. }
  554. r.Switch.StopPeerGracefully(peer)
  555. }
  556. }
  557. //-----------------------------------------------------------------------------
  558. // Messages
  559. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  560. // either pexRequestMessage, or pexAddrsMessage messages.
  561. type PexMessage interface{}
  562. func RegisterPexMessage(cdc *amino.Codec) {
  563. cdc.RegisterInterface((*PexMessage)(nil), nil)
  564. cdc.RegisterConcrete(&pexRequestMessage{}, "tendermint/p2p/PexRequestMessage", nil)
  565. cdc.RegisterConcrete(&pexAddrsMessage{}, "tendermint/p2p/PexAddrsMessage", nil)
  566. }
  567. func decodeMsg(bz []byte) (msg PexMessage, err error) {
  568. if len(bz) > maxMsgSize {
  569. return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  570. }
  571. err = cdc.UnmarshalBinaryBare(bz, &msg)
  572. return
  573. }
  574. /*
  575. A pexRequestMessage requests additional peer addresses.
  576. */
  577. type pexRequestMessage struct {
  578. }
  579. func (m *pexRequestMessage) String() string {
  580. return "[pexRequest]"
  581. }
  582. /*
  583. A message with announced peer addresses.
  584. */
  585. type pexAddrsMessage struct {
  586. Addrs []*p2p.NetAddress
  587. }
  588. func (m *pexAddrsMessage) String() string {
  589. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  590. }