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.

649 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. r.attemptsToDial.Delete(addr.DialString())
  358. } else {
  359. r.book.MarkAttempt(addr)
  360. // FIXME: if the addr is going to be removed from the addrbook (hard to
  361. // tell at this point), we need to Delete it from attemptsToDial, not
  362. // record another attempt.
  363. // record attempt
  364. r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
  365. }
  366. } else {
  367. // cleanup any history
  368. r.attemptsToDial.Delete(addr.DialString())
  369. }
  370. }
  371. // check seed addresses are well formed
  372. func (r *PEXReactor) checkSeeds() error {
  373. lSeeds := len(r.config.Seeds)
  374. if lSeeds == 0 {
  375. return nil
  376. }
  377. _, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  378. for _, err := range errs {
  379. if err != nil {
  380. return err
  381. }
  382. }
  383. return nil
  384. }
  385. // randomly dial seeds until we connect to one or exhaust them
  386. func (r *PEXReactor) dialSeeds() {
  387. lSeeds := len(r.config.Seeds)
  388. if lSeeds == 0 {
  389. return
  390. }
  391. seedAddrs, _ := p2p.NewNetAddressStrings(r.config.Seeds)
  392. perm := rand.Perm(lSeeds)
  393. // perm := r.Switch.rng.Perm(lSeeds)
  394. for _, i := range perm {
  395. // dial a random seed
  396. seedAddr := seedAddrs[i]
  397. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  398. if err == nil {
  399. return
  400. }
  401. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  402. }
  403. r.Switch.Logger.Error("Couldn't connect to any seeds")
  404. }
  405. // AttemptsToDial returns the number of attempts to dial specific address. It
  406. // returns 0 if never attempted or successfully connected.
  407. func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
  408. lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
  409. if attempted {
  410. return lAttempts.(_attemptsToDial).number
  411. } else {
  412. return 0
  413. }
  414. }
  415. //----------------------------------------------------------
  416. // Explores the network searching for more peers. (continuous)
  417. // Seed/Crawler Mode causes this node to quickly disconnect
  418. // from peers, except other seed nodes.
  419. func (r *PEXReactor) crawlPeersRoutine() {
  420. // Do an initial crawl
  421. r.crawlPeers()
  422. // Fire periodically
  423. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  424. for {
  425. select {
  426. case <-ticker.C:
  427. r.attemptDisconnects()
  428. r.crawlPeers()
  429. case <-r.Quit():
  430. return
  431. }
  432. }
  433. }
  434. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  435. // consulting the Switch as well as the AddrBook.
  436. func (r *PEXReactor) hasPotentialPeers() bool {
  437. out, in, dial := r.Switch.NumPeers()
  438. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  439. }
  440. // crawlPeerInfo handles temporary data needed for the
  441. // network crawling performed during seed/crawler mode.
  442. type crawlPeerInfo struct {
  443. // The listening address of a potential peer we learned about
  444. Addr *p2p.NetAddress
  445. // The last time we attempt to reach this address
  446. LastAttempt time.Time
  447. // The last time we successfully reached this address
  448. LastSuccess time.Time
  449. }
  450. // oldestFirst implements sort.Interface for []crawlPeerInfo
  451. // based on the LastAttempt field.
  452. type oldestFirst []crawlPeerInfo
  453. func (of oldestFirst) Len() int { return len(of) }
  454. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  455. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  456. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  457. // NOTE: The status information is ordered as described above.
  458. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  459. var of oldestFirst
  460. // TODO: be more selective
  461. addrs := r.book.ListOfKnownAddresses()
  462. for _, addr := range addrs {
  463. if len(addr.ID()) == 0 {
  464. continue // dont use peers without id
  465. }
  466. of = append(of, crawlPeerInfo{
  467. Addr: addr.Addr,
  468. LastAttempt: addr.LastAttempt,
  469. LastSuccess: addr.LastSuccess,
  470. })
  471. }
  472. sort.Sort(of)
  473. return of
  474. }
  475. // crawlPeers will crawl the network looking for new peer addresses. (once)
  476. func (r *PEXReactor) crawlPeers() {
  477. peerInfos := r.getPeersToCrawl()
  478. now := time.Now()
  479. // Use addresses we know of to reach additional peers
  480. for _, pi := range peerInfos {
  481. // Do not attempt to connect with peers we recently dialed
  482. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  483. continue
  484. }
  485. // Otherwise, attempt to connect with the known address
  486. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  487. if err != nil {
  488. r.book.MarkAttempt(pi.Addr)
  489. continue
  490. }
  491. }
  492. // Crawl the connected peers asking for more addresses
  493. for _, pi := range peerInfos {
  494. // We will wait a minimum period of time before crawling peers again
  495. if now.Sub(pi.LastAttempt) >= defaultCrawlPeerInterval {
  496. peer := r.Switch.Peers().Get(pi.Addr.ID)
  497. if peer != nil {
  498. r.RequestAddrs(peer)
  499. }
  500. }
  501. }
  502. }
  503. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  504. func (r *PEXReactor) attemptDisconnects() {
  505. for _, peer := range r.Switch.Peers().List() {
  506. status := peer.Status()
  507. if status.Duration < defaultSeedDisconnectWaitPeriod {
  508. continue
  509. }
  510. if peer.IsPersistent() {
  511. continue
  512. }
  513. r.Switch.StopPeerGracefully(peer)
  514. }
  515. }
  516. // isAddrPrivate returns true if addr is private.
  517. func isAddrPrivate(addr *p2p.NetAddress, privatePeerIDs []string) bool {
  518. for _, id := range privatePeerIDs {
  519. if string(addr.ID) == id {
  520. return true
  521. }
  522. }
  523. return false
  524. }
  525. //-----------------------------------------------------------------------------
  526. // Messages
  527. const (
  528. msgTypeRequest = byte(0x01)
  529. msgTypeAddrs = byte(0x02)
  530. )
  531. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  532. // either pexRequestMessage, or pexAddrsMessage messages.
  533. type PexMessage interface{}
  534. var _ = wire.RegisterInterface(
  535. struct{ PexMessage }{},
  536. wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest},
  537. wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs},
  538. )
  539. // DecodeMessage implements interface registered above.
  540. func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) {
  541. msgType = bz[0]
  542. n := new(int)
  543. r := bytes.NewReader(bz)
  544. msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage
  545. return
  546. }
  547. /*
  548. A pexRequestMessage requests additional peer addresses.
  549. */
  550. type pexRequestMessage struct {
  551. }
  552. func (m *pexRequestMessage) String() string {
  553. return "[pexRequest]"
  554. }
  555. /*
  556. A message with announced peer addresses.
  557. */
  558. type pexAddrsMessage struct {
  559. Addrs []*p2p.NetAddress
  560. }
  561. func (m *pexAddrsMessage) String() string {
  562. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  563. }