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.

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