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.

669 lines
19 KiB

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