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.

645 lines
18 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
9 years ago
  1. package pex
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/rand"
  6. "reflect"
  7. "sort"
  8. "sync"
  9. "time"
  10. "github.com/pkg/errors"
  11. wire "github.com/tendermint/go-wire"
  12. cmn "github.com/tendermint/tmlibs/common"
  13. "github.com/tendermint/tendermint/p2p"
  14. "github.com/tendermint/tendermint/p2p/conn"
  15. )
  16. type Peer = p2p.Peer
  17. const (
  18. // PexChannel is a channel for PEX messages
  19. PexChannel = byte(0x00)
  20. maxPexMessageSize = 1048576 // 1MB
  21. // ensure we have enough peers
  22. defaultEnsurePeersPeriod = 30 * time.Second
  23. defaultMinNumOutboundPeers = 10
  24. // Seed/Crawler constants
  25. // TODO:
  26. // We want seeds to only advertise good peers.
  27. // Peers are marked by external mechanisms.
  28. // We need a config value that can be set to be
  29. // on the order of how long it would take before a good
  30. // peer is marked good.
  31. defaultSeedDisconnectWaitPeriod = 2 * time.Minute // disconnect after this
  32. defaultCrawlPeerInterval = 2 * time.Minute // dont redial for this. TODO: back-off
  33. defaultCrawlPeersPeriod = 30 * time.Second // check some peers every this
  34. maxAttemptsToDial = 16 // ~ 35h in total (last attempt - 18h)
  35. )
  36. // PEXReactor handles PEX (peer exchange) and ensures that an
  37. // adequate number of peers are connected to the switch.
  38. //
  39. // It uses `AddrBook` (address book) to store `NetAddress`es of the peers.
  40. //
  41. // ## Preventing abuse
  42. //
  43. // Only accept pexAddrsMsg from peers we sent a corresponding pexRequestMsg too.
  44. // Only accept one pexRequestMsg every ~defaultEnsurePeersPeriod.
  45. type PEXReactor struct {
  46. p2p.BaseReactor
  47. book AddrBook
  48. config *PEXReactorConfig
  49. ensurePeersPeriod time.Duration
  50. // maps to prevent abuse
  51. requestsSent *cmn.CMap // ID->struct{}: unanswered send requests
  52. lastReceivedRequests *cmn.CMap // ID->time.Time: last time peer requested from us
  53. attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)}
  54. }
  55. // PEXReactorConfig holds reactor specific configuration data.
  56. type PEXReactorConfig struct {
  57. // Seed/Crawler mode
  58. SeedMode bool
  59. // Seeds is a list of addresses reactor may use
  60. // if it can't connect to peers in the addrbook.
  61. Seeds []string
  62. // PrivatePeerIDs is a list of peer IDs, which must not be gossiped to other
  63. // peers.
  64. PrivatePeerIDs []string
  65. }
  66. type _attemptsToDial struct {
  67. number int
  68. lastDialed time.Time
  69. }
  70. // NewPEXReactor creates new PEX reactor.
  71. func NewPEXReactor(b AddrBook, config *PEXReactorConfig) *PEXReactor {
  72. r := &PEXReactor{
  73. book: b,
  74. config: config,
  75. ensurePeersPeriod: defaultEnsurePeersPeriod,
  76. requestsSent: cmn.NewCMap(),
  77. lastReceivedRequests: cmn.NewCMap(),
  78. }
  79. r.BaseReactor = *p2p.NewBaseReactor("PEXReactor", r)
  80. return r
  81. }
  82. // OnStart implements BaseService
  83. func (r *PEXReactor) OnStart() error {
  84. if err := r.BaseReactor.OnStart(); err != nil {
  85. return err
  86. }
  87. err := r.book.Start()
  88. if err != nil && err != cmn.ErrAlreadyStarted {
  89. return err
  90. }
  91. // return err if user provided a bad seed address
  92. if err := r.checkSeeds(); err != nil {
  93. return err
  94. }
  95. // Check if this node should run
  96. // in seed/crawler mode
  97. if r.config.SeedMode {
  98. go r.crawlPeersRoutine()
  99. } else {
  100. go r.ensurePeersRoutine()
  101. }
  102. return nil
  103. }
  104. // OnStop implements BaseService
  105. func (r *PEXReactor) OnStop() {
  106. r.BaseReactor.OnStop()
  107. r.book.Stop()
  108. }
  109. // GetChannels implements Reactor
  110. func (r *PEXReactor) GetChannels() []*conn.ChannelDescriptor {
  111. return []*conn.ChannelDescriptor{
  112. {
  113. ID: PexChannel,
  114. Priority: 1,
  115. SendQueueCapacity: 10,
  116. },
  117. }
  118. }
  119. // AddPeer implements Reactor by adding peer to the address book (if inbound)
  120. // or by requesting more addresses (if outbound).
  121. func (r *PEXReactor) AddPeer(p Peer) {
  122. if p.IsOutbound() {
  123. // For outbound peers, the address is already in the books -
  124. // either via DialPeersAsync or r.Receive.
  125. // Ask it for more peers if we need.
  126. if r.book.NeedMoreAddrs() {
  127. r.RequestAddrs(p)
  128. }
  129. } else {
  130. // For inbound peers, the peer is its own source,
  131. // and its NodeInfo has already been validated.
  132. // Let the ensurePeersRoutine handle asking for more
  133. // peers when we need - we don't trust inbound peers as much.
  134. addr := p.NodeInfo().NetAddress()
  135. if !isAddrPrivate(addr, r.config.PrivatePeerIDs) {
  136. r.book.AddAddress(addr, addr)
  137. }
  138. }
  139. }
  140. // RemovePeer implements Reactor.
  141. func (r *PEXReactor) RemovePeer(p Peer, reason interface{}) {
  142. id := string(p.ID())
  143. r.requestsSent.Delete(id)
  144. r.lastReceivedRequests.Delete(id)
  145. }
  146. // Receive implements Reactor by handling incoming PEX messages.
  147. func (r *PEXReactor) Receive(chID byte, src Peer, msgBytes []byte) {
  148. _, msg, err := DecodeMessage(msgBytes)
  149. if err != nil {
  150. r.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  151. r.Switch.StopPeerForError(src, err)
  152. return
  153. }
  154. r.Logger.Debug("Received message", "src", src, "chId", chID, "msg", msg)
  155. switch msg := msg.(type) {
  156. case *pexRequestMessage:
  157. // Check we're not receiving too many requests
  158. if err := r.receiveRequest(src); err != nil {
  159. r.Switch.StopPeerForError(src, err)
  160. return
  161. }
  162. // Seeds disconnect after sending a batch of addrs
  163. if r.config.SeedMode {
  164. // TODO: should we be more selective ?
  165. r.SendAddrs(src, r.book.GetSelection())
  166. r.Switch.StopPeerGracefully(src)
  167. } else {
  168. r.SendAddrs(src, r.book.GetSelection())
  169. }
  170. case *pexAddrsMessage:
  171. // If we asked for addresses, add them to the book
  172. if err := r.ReceiveAddrs(msg.Addrs, src); err != nil {
  173. r.Switch.StopPeerForError(src, err)
  174. return
  175. }
  176. default:
  177. r.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  178. }
  179. }
  180. func (r *PEXReactor) receiveRequest(src Peer) error {
  181. id := string(src.ID())
  182. v := r.lastReceivedRequests.Get(id)
  183. if v == nil {
  184. // initialize with empty time
  185. lastReceived := time.Time{}
  186. r.lastReceivedRequests.Set(id, lastReceived)
  187. return nil
  188. }
  189. lastReceived := v.(time.Time)
  190. if lastReceived.Equal(time.Time{}) {
  191. // first time gets a free pass. then we start tracking the time
  192. lastReceived = time.Now()
  193. r.lastReceivedRequests.Set(id, lastReceived)
  194. return nil
  195. }
  196. now := time.Now()
  197. if now.Sub(lastReceived) < r.ensurePeersPeriod/3 {
  198. return fmt.Errorf("Peer (%v) is sending too many PEX requests. Disconnecting", src.ID())
  199. }
  200. r.lastReceivedRequests.Set(id, now)
  201. return nil
  202. }
  203. // RequestAddrs asks peer for more addresses if we do not already
  204. // have a request out for this peer.
  205. func (r *PEXReactor) RequestAddrs(p Peer) {
  206. id := string(p.ID())
  207. if r.requestsSent.Has(id) {
  208. return
  209. }
  210. r.requestsSent.Set(id, struct{}{})
  211. p.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}})
  212. }
  213. // ReceiveAddrs adds the given addrs to the addrbook if theres an open
  214. // request for this peer and deletes the open request.
  215. // If there's no open request for the src peer, it returns an error.
  216. func (r *PEXReactor) ReceiveAddrs(addrs []*p2p.NetAddress, src Peer) error {
  217. id := string(src.ID())
  218. if !r.requestsSent.Has(id) {
  219. return errors.New("Received unsolicited pexAddrsMessage")
  220. }
  221. r.requestsSent.Delete(id)
  222. srcAddr := src.NodeInfo().NetAddress()
  223. for _, netAddr := range addrs {
  224. if netAddr != nil && !isAddrPrivate(netAddr, r.config.PrivatePeerIDs) {
  225. r.book.AddAddress(netAddr, srcAddr)
  226. }
  227. }
  228. return nil
  229. }
  230. // SendAddrs sends addrs to the peer.
  231. func (r *PEXReactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) {
  232. p.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: netAddrs}})
  233. }
  234. // SetEnsurePeersPeriod sets period to ensure peers connected.
  235. func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) {
  236. r.ensurePeersPeriod = d
  237. }
  238. // Ensures that sufficient peers are connected. (continuous)
  239. func (r *PEXReactor) ensurePeersRoutine() {
  240. var (
  241. seed = rand.New(rand.NewSource(time.Now().UnixNano()))
  242. jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds())
  243. )
  244. // Randomize first round of communication to avoid thundering herd.
  245. // If no potential peers are present directly start connecting so we guarantee
  246. // swift setup with the help of configured seeds.
  247. if r.hasPotentialPeers() {
  248. time.Sleep(time.Duration(jitter))
  249. }
  250. // fire once immediately.
  251. // ensures we dial the seeds right away if the book is empty
  252. r.ensurePeers()
  253. // fire periodically
  254. ticker := time.NewTicker(r.ensurePeersPeriod)
  255. for {
  256. select {
  257. case <-ticker.C:
  258. r.ensurePeers()
  259. case <-r.Quit():
  260. ticker.Stop()
  261. return
  262. }
  263. }
  264. }
  265. // ensurePeers ensures that sufficient peers are connected. (once)
  266. //
  267. // heuristic that we haven't perfected yet, or, perhaps is manually edited by
  268. // the node operator. It should not be used to compute what addresses are
  269. // already connected or not.
  270. func (r *PEXReactor) ensurePeers() {
  271. var (
  272. out, in, dial = r.Switch.NumPeers()
  273. numToDial = defaultMinNumOutboundPeers - (out + dial)
  274. )
  275. r.Logger.Info(
  276. "Ensure peers",
  277. "numOutPeers", out,
  278. "numInPeers", in,
  279. "numDialing", dial,
  280. "numToDial", numToDial,
  281. )
  282. if numToDial <= 0 {
  283. return
  284. }
  285. // bias to prefer more vetted peers when we have fewer connections.
  286. // not perfect, but somewhate ensures that we prioritize connecting to more-vetted
  287. // NOTE: range here is [10, 90]. Too high ?
  288. newBias := cmn.MinInt(out, 8)*10 + 10
  289. toDial := make(map[p2p.ID]*p2p.NetAddress)
  290. // Try maxAttempts times to pick numToDial addresses to dial
  291. maxAttempts := numToDial * 3
  292. for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
  293. try := r.book.PickAddress(newBias)
  294. if try == nil {
  295. continue
  296. }
  297. if _, selected := toDial[try.ID]; selected {
  298. continue
  299. }
  300. if dialling := r.Switch.IsDialing(try.ID); dialling {
  301. continue
  302. }
  303. if connected := r.Switch.Peers().Has(try.ID); connected {
  304. continue
  305. }
  306. r.Logger.Info("Will dial address", "addr", try)
  307. toDial[try.ID] = try
  308. }
  309. // Dial picked addresses
  310. for _, addr := range toDial {
  311. go r.dialPeer(addr)
  312. }
  313. // If we need more addresses, pick a random peer and ask for more.
  314. if r.book.NeedMoreAddrs() {
  315. peers := r.Switch.Peers().List()
  316. peersCount := len(peers)
  317. if peersCount > 0 {
  318. peer := peers[rand.Int()%peersCount] // nolint: gas
  319. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  320. r.RequestAddrs(peer)
  321. }
  322. }
  323. // If we are not connected to nor dialing anybody, fallback to dialing a seed.
  324. if out+in+dial+len(toDial) == 0 {
  325. r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
  326. r.dialSeeds()
  327. }
  328. }
  329. func (r *PEXReactor) dialPeer(addr *p2p.NetAddress) {
  330. var attempts int
  331. var lastDialed time.Time
  332. if lAttempts, attempted := r.attemptsToDial.Load(addr.DialString()); attempted {
  333. attempts = lAttempts.(_attemptsToDial).number
  334. lastDialed = lAttempts.(_attemptsToDial).lastDialed
  335. }
  336. if attempts > maxAttemptsToDial {
  337. r.Logger.Error("Reached max attempts to dial", "addr", addr, "attempts", attempts)
  338. r.book.MarkBad(addr)
  339. return
  340. }
  341. // exponential backoff if it's not our first attempt to dial given address
  342. if attempts > 0 {
  343. jitterSeconds := time.Duration(rand.Float64() * float64(time.Second)) // 1s == (1e9 ns)
  344. backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second)
  345. sinceLastDialed := time.Since(lastDialed)
  346. if sinceLastDialed < backoffDuration {
  347. r.Logger.Debug("Too early to dial", "addr", addr, "backoff_duration", backoffDuration, "last_dialed", lastDialed, "time_since", sinceLastDialed)
  348. return
  349. }
  350. }
  351. err := r.Switch.DialPeerWithAddress(addr, false)
  352. if err != nil {
  353. r.Logger.Error("Dialing failed", "addr", addr, "err", err, "attempts", attempts)
  354. // TODO: detect more "bad peer" scenarios
  355. if _, ok := err.(p2p.ErrSwitchAuthenticationFailure); ok {
  356. r.book.MarkBad(addr)
  357. } else {
  358. r.book.MarkAttempt(addr)
  359. }
  360. // record attempt
  361. r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
  362. } else {
  363. // cleanup any history
  364. r.attemptsToDial.Delete(addr.DialString())
  365. }
  366. }
  367. // check seed addresses are well formed
  368. func (r *PEXReactor) checkSeeds() error {
  369. lSeeds := len(r.config.Seeds)
  370. if lSeeds == 0 {
  371. return nil
  372. }
  373. _, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  374. for _, err := range errs {
  375. if err != nil {
  376. return err
  377. }
  378. }
  379. return nil
  380. }
  381. // randomly dial seeds until we connect to one or exhaust them
  382. func (r *PEXReactor) dialSeeds() {
  383. lSeeds := len(r.config.Seeds)
  384. if lSeeds == 0 {
  385. return
  386. }
  387. seedAddrs, _ := p2p.NewNetAddressStrings(r.config.Seeds)
  388. perm := rand.Perm(lSeeds)
  389. // perm := r.Switch.rng.Perm(lSeeds)
  390. for _, i := range perm {
  391. // dial a random seed
  392. seedAddr := seedAddrs[i]
  393. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  394. if err == nil {
  395. return
  396. }
  397. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  398. }
  399. r.Switch.Logger.Error("Couldn't connect to any seeds")
  400. }
  401. // AttemptsToDial returns the number of attempts to dial specific address. It
  402. // returns 0 if never attempted or successfully connected.
  403. func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
  404. lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
  405. if attempted {
  406. return lAttempts.(_attemptsToDial).number
  407. } else {
  408. return 0
  409. }
  410. }
  411. //----------------------------------------------------------
  412. // Explores the network searching for more peers. (continuous)
  413. // Seed/Crawler Mode causes this node to quickly disconnect
  414. // from peers, except other seed nodes.
  415. func (r *PEXReactor) crawlPeersRoutine() {
  416. // Do an initial crawl
  417. r.crawlPeers()
  418. // Fire periodically
  419. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  420. for {
  421. select {
  422. case <-ticker.C:
  423. r.attemptDisconnects()
  424. r.crawlPeers()
  425. case <-r.Quit():
  426. return
  427. }
  428. }
  429. }
  430. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  431. // consulting the Switch as well as the AddrBook.
  432. func (r *PEXReactor) hasPotentialPeers() bool {
  433. out, in, dial := r.Switch.NumPeers()
  434. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  435. }
  436. // crawlPeerInfo handles temporary data needed for the
  437. // network crawling performed during seed/crawler mode.
  438. type crawlPeerInfo struct {
  439. // The listening address of a potential peer we learned about
  440. Addr *p2p.NetAddress
  441. // The last time we attempt to reach this address
  442. LastAttempt time.Time
  443. // The last time we successfully reached this address
  444. LastSuccess time.Time
  445. }
  446. // oldestFirst implements sort.Interface for []crawlPeerInfo
  447. // based on the LastAttempt field.
  448. type oldestFirst []crawlPeerInfo
  449. func (of oldestFirst) Len() int { return len(of) }
  450. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  451. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  452. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  453. // NOTE: The status information is ordered as described above.
  454. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  455. var of oldestFirst
  456. // TODO: be more selective
  457. addrs := r.book.ListOfKnownAddresses()
  458. for _, addr := range addrs {
  459. if len(addr.ID()) == 0 {
  460. continue // dont use peers without id
  461. }
  462. of = append(of, crawlPeerInfo{
  463. Addr: addr.Addr,
  464. LastAttempt: addr.LastAttempt,
  465. LastSuccess: addr.LastSuccess,
  466. })
  467. }
  468. sort.Sort(of)
  469. return of
  470. }
  471. // crawlPeers will crawl the network looking for new peer addresses. (once)
  472. func (r *PEXReactor) crawlPeers() {
  473. peerInfos := r.getPeersToCrawl()
  474. now := time.Now()
  475. // Use addresses we know of to reach additional peers
  476. for _, pi := range peerInfos {
  477. // Do not attempt to connect with peers we recently dialed
  478. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  479. continue
  480. }
  481. // Otherwise, attempt to connect with the known address
  482. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  483. if err != nil {
  484. r.book.MarkAttempt(pi.Addr)
  485. continue
  486. }
  487. }
  488. // Crawl the connected peers asking for more addresses
  489. for _, pi := range peerInfos {
  490. // We will wait a minimum period of time before crawling peers again
  491. if now.Sub(pi.LastAttempt) >= defaultCrawlPeerInterval {
  492. peer := r.Switch.Peers().Get(pi.Addr.ID)
  493. if peer != nil {
  494. r.RequestAddrs(peer)
  495. }
  496. }
  497. }
  498. }
  499. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  500. func (r *PEXReactor) attemptDisconnects() {
  501. for _, peer := range r.Switch.Peers().List() {
  502. status := peer.Status()
  503. if status.Duration < defaultSeedDisconnectWaitPeriod {
  504. continue
  505. }
  506. if peer.IsPersistent() {
  507. continue
  508. }
  509. r.Switch.StopPeerGracefully(peer)
  510. }
  511. }
  512. // isAddrPrivate returns true if addr is private.
  513. func isAddrPrivate(addr *p2p.NetAddress, privatePeerIDs []string) bool {
  514. for _, id := range privatePeerIDs {
  515. if string(addr.ID) == id {
  516. return true
  517. }
  518. }
  519. return false
  520. }
  521. //-----------------------------------------------------------------------------
  522. // Messages
  523. const (
  524. msgTypeRequest = byte(0x01)
  525. msgTypeAddrs = byte(0x02)
  526. )
  527. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  528. // either pexRequestMessage, or pexAddrsMessage messages.
  529. type PexMessage interface{}
  530. var _ = wire.RegisterInterface(
  531. struct{ PexMessage }{},
  532. wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest},
  533. wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs},
  534. )
  535. // DecodeMessage implements interface registered above.
  536. func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) {
  537. msgType = bz[0]
  538. n := new(int)
  539. r := bytes.NewReader(bz)
  540. msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage
  541. return
  542. }
  543. /*
  544. A pexRequestMessage requests additional peer addresses.
  545. */
  546. type pexRequestMessage struct {
  547. }
  548. func (m *pexRequestMessage) String() string {
  549. return "[pexRequest]"
  550. }
  551. /*
  552. A message with announced peer addresses.
  553. */
  554. type pexAddrsMessage struct {
  555. Addrs []*p2p.NetAddress
  556. }
  557. func (m *pexAddrsMessage) String() string {
  558. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  559. }