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.

655 lines
18 KiB

  1. package p2p
  2. import (
  3. "fmt"
  4. "math"
  5. "sync"
  6. "time"
  7. "github.com/tendermint/tendermint/config"
  8. cmn "github.com/tendermint/tendermint/libs/common"
  9. "github.com/tendermint/tendermint/p2p/conn"
  10. )
  11. const (
  12. // wait a random amount of time from this interval
  13. // before dialing peers or reconnecting to help prevent DoS
  14. dialRandomizerIntervalMilliseconds = 3000
  15. // repeatedly try to reconnect for a few minutes
  16. // ie. 5 * 20 = 100s
  17. reconnectAttempts = 20
  18. reconnectInterval = 5 * time.Second
  19. // then move into exponential backoff mode for ~1day
  20. // ie. 3**10 = 16hrs
  21. reconnectBackOffAttempts = 10
  22. reconnectBackOffBaseSeconds = 3
  23. )
  24. //-----------------------------------------------------------------------------
  25. // An AddrBook represents an address book from the pex package, which is used
  26. // to store peer addresses.
  27. type AddrBook interface {
  28. AddAddress(addr *NetAddress, src *NetAddress) error
  29. AddOurAddress(*NetAddress)
  30. OurAddress(*NetAddress) bool
  31. MarkGood(*NetAddress)
  32. RemoveAddress(*NetAddress)
  33. HasAddress(*NetAddress) bool
  34. Save()
  35. }
  36. // PeerFilterFunc to be implemented by filter hooks after a new Peer has been
  37. // fully setup.
  38. type PeerFilterFunc func(IPeerSet, Peer) error
  39. //-----------------------------------------------------------------------------
  40. // Switch handles peer connections and exposes an API to receive incoming messages
  41. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  42. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  43. // incoming messages are received on the reactor.
  44. type Switch struct {
  45. cmn.BaseService
  46. config *config.P2PConfig
  47. reactors map[string]Reactor
  48. chDescs []*conn.ChannelDescriptor
  49. reactorsByCh map[byte]Reactor
  50. peers *PeerSet
  51. dialing *cmn.CMap
  52. reconnecting *cmn.CMap
  53. nodeInfo NodeInfo // our node info
  54. nodeKey *NodeKey // our node privkey
  55. addrBook AddrBook
  56. transport Transport
  57. filterTimeout time.Duration
  58. peerFilters []PeerFilterFunc
  59. mConfig conn.MConnConfig
  60. rng *cmn.Rand // seed for randomizing dial times and orders
  61. metrics *Metrics
  62. }
  63. // SwitchOption sets an optional parameter on the Switch.
  64. type SwitchOption func(*Switch)
  65. // NewSwitch creates a new Switch with the given config.
  66. func NewSwitch(
  67. cfg *config.P2PConfig,
  68. transport Transport,
  69. options ...SwitchOption,
  70. ) *Switch {
  71. sw := &Switch{
  72. config: cfg,
  73. reactors: make(map[string]Reactor),
  74. chDescs: make([]*conn.ChannelDescriptor, 0),
  75. reactorsByCh: make(map[byte]Reactor),
  76. peers: NewPeerSet(),
  77. dialing: cmn.NewCMap(),
  78. reconnecting: cmn.NewCMap(),
  79. metrics: NopMetrics(),
  80. transport: transport,
  81. filterTimeout: defaultFilterTimeout,
  82. }
  83. // Ensure we have a completely undeterministic PRNG.
  84. sw.rng = cmn.NewRand()
  85. mConfig := conn.DefaultMConnConfig()
  86. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  87. mConfig.SendRate = cfg.SendRate
  88. mConfig.RecvRate = cfg.RecvRate
  89. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  90. sw.mConfig = mConfig
  91. sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw)
  92. for _, option := range options {
  93. option(sw)
  94. }
  95. return sw
  96. }
  97. // SwitchFilterTimeout sets the timeout used for peer filters.
  98. func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
  99. return func(sw *Switch) { sw.filterTimeout = timeout }
  100. }
  101. // SwitchPeerFilters sets the filters for rejection of new peers.
  102. func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
  103. return func(sw *Switch) { sw.peerFilters = filters }
  104. }
  105. // WithMetrics sets the metrics.
  106. func WithMetrics(metrics *Metrics) SwitchOption {
  107. return func(sw *Switch) { sw.metrics = metrics }
  108. }
  109. //---------------------------------------------------------------------
  110. // Switch setup
  111. // AddReactor adds the given reactor to the switch.
  112. // NOTE: Not goroutine safe.
  113. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  114. // Validate the reactor.
  115. // No two reactors can share the same channel.
  116. reactorChannels := reactor.GetChannels()
  117. for _, chDesc := range reactorChannels {
  118. chID := chDesc.ID
  119. if sw.reactorsByCh[chID] != nil {
  120. cmn.PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  121. }
  122. sw.chDescs = append(sw.chDescs, chDesc)
  123. sw.reactorsByCh[chID] = reactor
  124. }
  125. sw.reactors[name] = reactor
  126. reactor.SetSwitch(sw)
  127. return reactor
  128. }
  129. // Reactors returns a map of reactors registered on the switch.
  130. // NOTE: Not goroutine safe.
  131. func (sw *Switch) Reactors() map[string]Reactor {
  132. return sw.reactors
  133. }
  134. // Reactor returns the reactor with the given name.
  135. // NOTE: Not goroutine safe.
  136. func (sw *Switch) Reactor(name string) Reactor {
  137. return sw.reactors[name]
  138. }
  139. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  140. // NOTE: Not goroutine safe.
  141. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  142. sw.nodeInfo = nodeInfo
  143. }
  144. // NodeInfo returns the switch's NodeInfo.
  145. // NOTE: Not goroutine safe.
  146. func (sw *Switch) NodeInfo() NodeInfo {
  147. return sw.nodeInfo
  148. }
  149. // SetNodeKey sets the switch's private key for authenticated encryption.
  150. // NOTE: Not goroutine safe.
  151. func (sw *Switch) SetNodeKey(nodeKey *NodeKey) {
  152. sw.nodeKey = nodeKey
  153. }
  154. //---------------------------------------------------------------------
  155. // Service start/stop
  156. // OnStart implements BaseService. It starts all the reactors and peers.
  157. func (sw *Switch) OnStart() error {
  158. // Start reactors
  159. for _, reactor := range sw.reactors {
  160. err := reactor.Start()
  161. if err != nil {
  162. return cmn.ErrorWrap(err, "failed to start %v", reactor)
  163. }
  164. }
  165. // Start accepting Peers.
  166. go sw.acceptRoutine()
  167. return nil
  168. }
  169. // OnStop implements BaseService. It stops all peers and reactors.
  170. func (sw *Switch) OnStop() {
  171. // Stop peers
  172. for _, p := range sw.peers.List() {
  173. p.Stop()
  174. sw.peers.Remove(p)
  175. }
  176. // Stop reactors
  177. sw.Logger.Debug("Switch: Stopping reactors")
  178. for _, reactor := range sw.reactors {
  179. reactor.Stop()
  180. }
  181. }
  182. //---------------------------------------------------------------------
  183. // Peers
  184. // Broadcast runs a go routine for each attempted send, which will block trying
  185. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  186. // success values for each attempted send (false if times out). Channel will be
  187. // closed once msg bytes are sent to all peers (or time out).
  188. //
  189. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  190. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  191. successChan := make(chan bool, len(sw.peers.List()))
  192. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", fmt.Sprintf("%X", msgBytes))
  193. var wg sync.WaitGroup
  194. for _, peer := range sw.peers.List() {
  195. wg.Add(1)
  196. go func(peer Peer) {
  197. defer wg.Done()
  198. success := peer.Send(chID, msgBytes)
  199. successChan <- success
  200. }(peer)
  201. }
  202. go func() {
  203. wg.Wait()
  204. close(successChan)
  205. }()
  206. return successChan
  207. }
  208. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  209. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  210. peers := sw.peers.List()
  211. for _, peer := range peers {
  212. if peer.IsOutbound() {
  213. outbound++
  214. } else {
  215. inbound++
  216. }
  217. }
  218. dialing = sw.dialing.Size()
  219. return
  220. }
  221. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  222. func (sw *Switch) MaxNumOutboundPeers() int {
  223. return sw.config.MaxNumOutboundPeers
  224. }
  225. // Peers returns the set of peers that are connected to the switch.
  226. func (sw *Switch) Peers() IPeerSet {
  227. return sw.peers
  228. }
  229. // StopPeerForError disconnects from a peer due to external error.
  230. // If the peer is persistent, it will attempt to reconnect.
  231. // TODO: make record depending on reason.
  232. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  233. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  234. sw.stopAndRemovePeer(peer, reason)
  235. if peer.IsPersistent() {
  236. // TODO: use the original address dialed, not the self reported one
  237. // See #2618.
  238. addr := peer.NodeInfo().NetAddress()
  239. go sw.reconnectToPeer(addr)
  240. }
  241. }
  242. // StopPeerGracefully disconnects from a peer gracefully.
  243. // TODO: handle graceful disconnects.
  244. func (sw *Switch) StopPeerGracefully(peer Peer) {
  245. sw.Logger.Info("Stopping peer gracefully")
  246. sw.stopAndRemovePeer(peer, nil)
  247. }
  248. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  249. sw.peers.Remove(peer)
  250. sw.metrics.Peers.Add(float64(-1))
  251. peer.Stop()
  252. for _, reactor := range sw.reactors {
  253. reactor.RemovePeer(peer, reason)
  254. }
  255. }
  256. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  257. // with a fixed interval, then with exponential backoff.
  258. // If no success after all that, it stops trying, and leaves it
  259. // to the PEX/Addrbook to find the peer with the addr again
  260. // NOTE: this will keep trying even if the handshake or auth fails.
  261. // TODO: be more explicit with error types so we only retry on certain failures
  262. // - ie. if we're getting ErrDuplicatePeer we can stop
  263. // because the addrbook got us the peer back already
  264. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  265. if sw.reconnecting.Has(string(addr.ID)) {
  266. return
  267. }
  268. sw.reconnecting.Set(string(addr.ID), addr)
  269. defer sw.reconnecting.Delete(string(addr.ID))
  270. start := time.Now()
  271. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  272. for i := 0; i < reconnectAttempts; i++ {
  273. if !sw.IsRunning() {
  274. return
  275. }
  276. err := sw.DialPeerWithAddress(addr, true)
  277. if err == nil {
  278. return // success
  279. }
  280. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  281. // sleep a set amount
  282. sw.randomSleep(reconnectInterval)
  283. continue
  284. }
  285. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  286. "addr", addr, "elapsed", time.Since(start))
  287. for i := 0; i < reconnectBackOffAttempts; i++ {
  288. if !sw.IsRunning() {
  289. return
  290. }
  291. // sleep an exponentially increasing amount
  292. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  293. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  294. err := sw.DialPeerWithAddress(addr, true)
  295. if err == nil {
  296. return // success
  297. }
  298. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  299. }
  300. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  301. }
  302. // SetAddrBook allows to set address book on Switch.
  303. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  304. sw.addrBook = addrBook
  305. }
  306. // MarkPeerAsGood marks the given peer as good when it did something useful
  307. // like contributed to consensus.
  308. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  309. if sw.addrBook != nil {
  310. sw.addrBook.MarkGood(peer.NodeInfo().NetAddress())
  311. }
  312. }
  313. //---------------------------------------------------------------------
  314. // Dialing
  315. // DialPeersAsync dials a list of peers asynchronously in random order (optionally, making them persistent).
  316. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  317. // TODO: remove addrBook arg since it's now set on the switch
  318. func (sw *Switch) DialPeersAsync(addrBook AddrBook, peers []string, persistent bool) error {
  319. netAddrs, errs := NewNetAddressStrings(peers)
  320. // only log errors, dial correct addresses
  321. for _, err := range errs {
  322. sw.Logger.Error("Error in peer's address", "err", err)
  323. }
  324. ourAddr := sw.nodeInfo.NetAddress()
  325. // TODO: this code feels like it's in the wrong place.
  326. // The integration tests depend on the addrBook being saved
  327. // right away but maybe we can change that. Recall that
  328. // the addrBook is only written to disk every 2min
  329. if addrBook != nil {
  330. // add peers to `addrBook`
  331. for _, netAddr := range netAddrs {
  332. // do not add our address or ID
  333. if !netAddr.Same(ourAddr) {
  334. if err := addrBook.AddAddress(netAddr, ourAddr); err != nil {
  335. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  336. }
  337. }
  338. }
  339. // Persist some peers to disk right away.
  340. // NOTE: integration tests depend on this
  341. addrBook.Save()
  342. }
  343. // permute the list, dial them in random order.
  344. perm := sw.rng.Perm(len(netAddrs))
  345. for i := 0; i < len(perm); i++ {
  346. go func(i int) {
  347. j := perm[i]
  348. addr := netAddrs[j]
  349. if addr.Same(ourAddr) {
  350. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  351. return
  352. } else if sw.IsDialingOrExistingAddress(addr) {
  353. sw.Logger.Debug("Ignore attempt to connect to an existing peer", "addr", addr)
  354. return
  355. }
  356. sw.randomSleep(0)
  357. err := sw.DialPeerWithAddress(addr, persistent)
  358. if err != nil {
  359. switch err.(type) {
  360. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID:
  361. sw.Logger.Debug("Error dialing peer", "err", err)
  362. default:
  363. sw.Logger.Error("Error dialing peer", "err", err)
  364. }
  365. }
  366. }(i)
  367. }
  368. return nil
  369. }
  370. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects and authenticates successfully.
  371. // If `persistent == true`, the switch will always try to reconnect to this peer if the connection ever fails.
  372. func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) error {
  373. sw.dialing.Set(string(addr.ID), addr)
  374. defer sw.dialing.Delete(string(addr.ID))
  375. return sw.addOutboundPeerWithConfig(addr, sw.config, persistent)
  376. }
  377. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  378. func (sw *Switch) randomSleep(interval time.Duration) {
  379. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  380. time.Sleep(r + interval)
  381. }
  382. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  383. // address or dialing it at the moment.
  384. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  385. return sw.dialing.Has(string(addr.ID)) ||
  386. sw.peers.Has(addr.ID) ||
  387. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  388. }
  389. func (sw *Switch) acceptRoutine() {
  390. for {
  391. p, err := sw.transport.Accept(peerConfig{
  392. chDescs: sw.chDescs,
  393. onPeerError: sw.StopPeerForError,
  394. reactorsByCh: sw.reactorsByCh,
  395. metrics: sw.metrics,
  396. })
  397. if err != nil {
  398. switch err.(type) {
  399. case ErrRejected:
  400. rErr := err.(ErrRejected)
  401. if rErr.IsSelf() {
  402. // Remove the given address from the address book and add to our addresses
  403. // to avoid dialing in the future.
  404. addr := rErr.Addr()
  405. sw.addrBook.RemoveAddress(&addr)
  406. sw.addrBook.AddOurAddress(&addr)
  407. }
  408. sw.Logger.Info(
  409. "Inbound Peer rejected",
  410. "err", err,
  411. "numPeers", sw.peers.Size(),
  412. )
  413. continue
  414. case *ErrTransportClosed:
  415. sw.Logger.Error(
  416. "Stopped accept routine, as transport is closed",
  417. "numPeers", sw.peers.Size(),
  418. )
  419. default:
  420. sw.Logger.Error(
  421. "Accept on transport errored",
  422. "err", err,
  423. "numPeers", sw.peers.Size(),
  424. )
  425. }
  426. break
  427. }
  428. // Ignore connection if we already have enough peers.
  429. _, in, _ := sw.NumPeers()
  430. if in >= sw.config.MaxNumInboundPeers {
  431. sw.Logger.Info(
  432. "Ignoring inbound connection: already have enough inbound peers",
  433. "address", p.NodeInfo().NetAddress().String(),
  434. "have", in,
  435. "max", sw.config.MaxNumInboundPeers,
  436. )
  437. _ = p.Stop()
  438. continue
  439. }
  440. if err := sw.addPeer(p); err != nil {
  441. _ = p.Stop()
  442. sw.Logger.Info(
  443. "Ignoring inbound connection: error while adding peer",
  444. "err", err,
  445. "id", p.ID(),
  446. )
  447. }
  448. }
  449. }
  450. // dial the peer; make secret connection; authenticate against the dialed ID;
  451. // add the peer.
  452. // if dialing fails, start the reconnect loop. If handhsake fails, its over.
  453. // If peer is started succesffuly, reconnectLoop will start when
  454. // StopPeerForError is called
  455. func (sw *Switch) addOutboundPeerWithConfig(
  456. addr *NetAddress,
  457. cfg *config.P2PConfig,
  458. persistent bool,
  459. ) error {
  460. sw.Logger.Info("Dialing peer", "address", addr)
  461. // XXX(xla): Remove the leakage of test concerns in implementation.
  462. if cfg.TestDialFail {
  463. go sw.reconnectToPeer(addr)
  464. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  465. }
  466. p, err := sw.transport.Dial(*addr, peerConfig{
  467. chDescs: sw.chDescs,
  468. onPeerError: sw.StopPeerForError,
  469. persistent: persistent,
  470. reactorsByCh: sw.reactorsByCh,
  471. metrics: sw.metrics,
  472. })
  473. if err != nil {
  474. switch e := err.(type) {
  475. case ErrRejected:
  476. if e.IsSelf() {
  477. // Remove the given address from the address book and add to our addresses
  478. // to avoid dialing in the future.
  479. sw.addrBook.RemoveAddress(addr)
  480. sw.addrBook.AddOurAddress(addr)
  481. return err
  482. }
  483. }
  484. // retry persistent peers after
  485. // any dial error besides IsSelf()
  486. if persistent {
  487. go sw.reconnectToPeer(addr)
  488. }
  489. return err
  490. }
  491. if err := sw.addPeer(p); err != nil {
  492. _ = p.Stop()
  493. return err
  494. }
  495. return nil
  496. }
  497. func (sw *Switch) filterPeer(p Peer) error {
  498. // Avoid duplicate
  499. if sw.peers.Has(p.ID()) {
  500. return ErrRejected{id: p.ID(), isDuplicate: true}
  501. }
  502. errc := make(chan error, len(sw.peerFilters))
  503. for _, f := range sw.peerFilters {
  504. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  505. errc <- f(sw.peers, p)
  506. }(f, p, errc)
  507. }
  508. for i := 0; i < cap(errc); i++ {
  509. select {
  510. case err := <-errc:
  511. if err != nil {
  512. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  513. }
  514. case <-time.After(sw.filterTimeout):
  515. return ErrFilterTimeout{}
  516. }
  517. }
  518. return nil
  519. }
  520. // addPeer starts up the Peer and adds it to the Switch.
  521. func (sw *Switch) addPeer(p Peer) error {
  522. if err := sw.filterPeer(p); err != nil {
  523. return err
  524. }
  525. p.SetLogger(sw.Logger.With("peer", p.NodeInfo().NetAddress().String))
  526. // All good. Start peer
  527. if sw.IsRunning() {
  528. if err := sw.startInitPeer(p); err != nil {
  529. return err
  530. }
  531. }
  532. // Add the peer to .peers.
  533. // We start it first so that a peer in the list is safe to Stop.
  534. // It should not err since we already checked peers.Has().
  535. if err := sw.peers.Add(p); err != nil {
  536. return err
  537. }
  538. sw.Logger.Info("Added peer", "peer", p)
  539. sw.metrics.Peers.Add(float64(1))
  540. return nil
  541. }
  542. func (sw *Switch) startInitPeer(p Peer) error {
  543. err := p.Start() // spawn send/recv routines
  544. if err != nil {
  545. // Should never happen
  546. sw.Logger.Error(
  547. "Error starting peer",
  548. "err", err,
  549. "peer", p,
  550. )
  551. return err
  552. }
  553. for _, reactor := range sw.reactors {
  554. reactor.AddPeer(p)
  555. }
  556. return nil
  557. }