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.

695 lines
20 KiB

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