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.

709 lines
20 KiB

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