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.

658 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. addr := peer.OriginalAddr()
  237. if addr == nil {
  238. // FIXME: persistent peers can't be inbound right now.
  239. // self-reported address for inbound persistent peers
  240. addr = peer.NodeInfo().NetAddress()
  241. }
  242. go sw.reconnectToPeer(addr)
  243. }
  244. }
  245. // StopPeerGracefully disconnects from a peer gracefully.
  246. // TODO: handle graceful disconnects.
  247. func (sw *Switch) StopPeerGracefully(peer Peer) {
  248. sw.Logger.Info("Stopping peer gracefully")
  249. sw.stopAndRemovePeer(peer, nil)
  250. }
  251. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  252. sw.peers.Remove(peer)
  253. sw.metrics.Peers.Add(float64(-1))
  254. peer.Stop()
  255. for _, reactor := range sw.reactors {
  256. reactor.RemovePeer(peer, reason)
  257. }
  258. }
  259. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  260. // with a fixed interval, then with exponential backoff.
  261. // If no success after all that, it stops trying, and leaves it
  262. // to the PEX/Addrbook to find the peer with the addr again
  263. // NOTE: this will keep trying even if the handshake or auth fails.
  264. // TODO: be more explicit with error types so we only retry on certain failures
  265. // - ie. if we're getting ErrDuplicatePeer we can stop
  266. // because the addrbook got us the peer back already
  267. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  268. if sw.reconnecting.Has(string(addr.ID)) {
  269. return
  270. }
  271. sw.reconnecting.Set(string(addr.ID), addr)
  272. defer sw.reconnecting.Delete(string(addr.ID))
  273. start := time.Now()
  274. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  275. for i := 0; i < reconnectAttempts; i++ {
  276. if !sw.IsRunning() {
  277. return
  278. }
  279. err := sw.DialPeerWithAddress(addr, true)
  280. if err == nil {
  281. return // success
  282. }
  283. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  284. // sleep a set amount
  285. sw.randomSleep(reconnectInterval)
  286. continue
  287. }
  288. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  289. "addr", addr, "elapsed", time.Since(start))
  290. for i := 0; i < reconnectBackOffAttempts; i++ {
  291. if !sw.IsRunning() {
  292. return
  293. }
  294. // sleep an exponentially increasing amount
  295. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  296. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  297. err := sw.DialPeerWithAddress(addr, true)
  298. if err == nil {
  299. return // success
  300. }
  301. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  302. }
  303. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  304. }
  305. // SetAddrBook allows to set address book on Switch.
  306. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  307. sw.addrBook = addrBook
  308. }
  309. // MarkPeerAsGood marks the given peer as good when it did something useful
  310. // like contributed to consensus.
  311. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  312. if sw.addrBook != nil {
  313. sw.addrBook.MarkGood(peer.NodeInfo().NetAddress())
  314. }
  315. }
  316. //---------------------------------------------------------------------
  317. // Dialing
  318. // DialPeersAsync dials a list of peers asynchronously in random order (optionally, making them persistent).
  319. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  320. // TODO: remove addrBook arg since it's now set on the switch
  321. func (sw *Switch) DialPeersAsync(addrBook AddrBook, peers []string, persistent bool) error {
  322. netAddrs, errs := NewNetAddressStrings(peers)
  323. // only log errors, dial correct addresses
  324. for _, err := range errs {
  325. sw.Logger.Error("Error in peer's address", "err", err)
  326. }
  327. ourAddr := sw.nodeInfo.NetAddress()
  328. // TODO: this code feels like it's in the wrong place.
  329. // The integration tests depend on the addrBook being saved
  330. // right away but maybe we can change that. Recall that
  331. // the addrBook is only written to disk every 2min
  332. if addrBook != nil {
  333. // add peers to `addrBook`
  334. for _, netAddr := range netAddrs {
  335. // do not add our address or ID
  336. if !netAddr.Same(ourAddr) {
  337. if err := addrBook.AddAddress(netAddr, ourAddr); err != nil {
  338. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  339. }
  340. }
  341. }
  342. // Persist some peers to disk right away.
  343. // NOTE: integration tests depend on this
  344. addrBook.Save()
  345. }
  346. // permute the list, dial them in random order.
  347. perm := sw.rng.Perm(len(netAddrs))
  348. for i := 0; i < len(perm); i++ {
  349. go func(i int) {
  350. j := perm[i]
  351. addr := netAddrs[j]
  352. if addr.Same(ourAddr) {
  353. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  354. return
  355. } else if sw.IsDialingOrExistingAddress(addr) {
  356. sw.Logger.Debug("Ignore attempt to connect to an existing peer", "addr", addr)
  357. return
  358. }
  359. sw.randomSleep(0)
  360. err := sw.DialPeerWithAddress(addr, persistent)
  361. if err != nil {
  362. switch err.(type) {
  363. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID:
  364. sw.Logger.Debug("Error dialing peer", "err", err)
  365. default:
  366. sw.Logger.Error("Error dialing peer", "err", err)
  367. }
  368. }
  369. }(i)
  370. }
  371. return nil
  372. }
  373. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects and authenticates successfully.
  374. // If `persistent == true`, the switch will always try to reconnect to this peer if the connection ever fails.
  375. func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) error {
  376. sw.dialing.Set(string(addr.ID), addr)
  377. defer sw.dialing.Delete(string(addr.ID))
  378. return sw.addOutboundPeerWithConfig(addr, sw.config, persistent)
  379. }
  380. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  381. func (sw *Switch) randomSleep(interval time.Duration) {
  382. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  383. time.Sleep(r + interval)
  384. }
  385. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  386. // address or dialing it at the moment.
  387. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  388. return sw.dialing.Has(string(addr.ID)) ||
  389. sw.peers.Has(addr.ID) ||
  390. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  391. }
  392. func (sw *Switch) acceptRoutine() {
  393. for {
  394. p, err := sw.transport.Accept(peerConfig{
  395. chDescs: sw.chDescs,
  396. onPeerError: sw.StopPeerForError,
  397. reactorsByCh: sw.reactorsByCh,
  398. metrics: sw.metrics,
  399. })
  400. if err != nil {
  401. switch err.(type) {
  402. case ErrRejected:
  403. rErr := err.(ErrRejected)
  404. if rErr.IsSelf() {
  405. // Remove the given address from the address book and add to our addresses
  406. // to avoid dialing in the future.
  407. addr := rErr.Addr()
  408. sw.addrBook.RemoveAddress(&addr)
  409. sw.addrBook.AddOurAddress(&addr)
  410. }
  411. sw.Logger.Info(
  412. "Inbound Peer rejected",
  413. "err", err,
  414. "numPeers", sw.peers.Size(),
  415. )
  416. continue
  417. case *ErrTransportClosed:
  418. sw.Logger.Error(
  419. "Stopped accept routine, as transport is closed",
  420. "numPeers", sw.peers.Size(),
  421. )
  422. default:
  423. sw.Logger.Error(
  424. "Accept on transport errored",
  425. "err", err,
  426. "numPeers", sw.peers.Size(),
  427. )
  428. }
  429. break
  430. }
  431. // Ignore connection if we already have enough peers.
  432. _, in, _ := sw.NumPeers()
  433. if in >= sw.config.MaxNumInboundPeers {
  434. sw.Logger.Info(
  435. "Ignoring inbound connection: already have enough inbound peers",
  436. "address", p.NodeInfo().NetAddress().String(),
  437. "have", in,
  438. "max", sw.config.MaxNumInboundPeers,
  439. )
  440. _ = p.Stop()
  441. continue
  442. }
  443. if err := sw.addPeer(p); err != nil {
  444. _ = p.Stop()
  445. sw.Logger.Info(
  446. "Ignoring inbound connection: error while adding peer",
  447. "err", err,
  448. "id", p.ID(),
  449. )
  450. }
  451. }
  452. }
  453. // dial the peer; make secret connection; authenticate against the dialed ID;
  454. // add the peer.
  455. // if dialing fails, start the reconnect loop. If handhsake fails, its over.
  456. // If peer is started succesffuly, reconnectLoop will start when
  457. // StopPeerForError is called
  458. func (sw *Switch) addOutboundPeerWithConfig(
  459. addr *NetAddress,
  460. cfg *config.P2PConfig,
  461. persistent bool,
  462. ) error {
  463. sw.Logger.Info("Dialing peer", "address", addr)
  464. // XXX(xla): Remove the leakage of test concerns in implementation.
  465. if cfg.TestDialFail {
  466. go sw.reconnectToPeer(addr)
  467. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  468. }
  469. p, err := sw.transport.Dial(*addr, peerConfig{
  470. chDescs: sw.chDescs,
  471. onPeerError: sw.StopPeerForError,
  472. persistent: persistent,
  473. reactorsByCh: sw.reactorsByCh,
  474. metrics: sw.metrics,
  475. })
  476. if err != nil {
  477. switch e := err.(type) {
  478. case ErrRejected:
  479. if e.IsSelf() {
  480. // Remove the given address from the address book and add to our addresses
  481. // to avoid dialing in the future.
  482. sw.addrBook.RemoveAddress(addr)
  483. sw.addrBook.AddOurAddress(addr)
  484. return err
  485. }
  486. }
  487. // retry persistent peers after
  488. // any dial error besides IsSelf()
  489. if persistent {
  490. go sw.reconnectToPeer(addr)
  491. }
  492. return err
  493. }
  494. if err := sw.addPeer(p); err != nil {
  495. _ = p.Stop()
  496. return err
  497. }
  498. return nil
  499. }
  500. func (sw *Switch) filterPeer(p Peer) error {
  501. // Avoid duplicate
  502. if sw.peers.Has(p.ID()) {
  503. return ErrRejected{id: p.ID(), isDuplicate: true}
  504. }
  505. errc := make(chan error, len(sw.peerFilters))
  506. for _, f := range sw.peerFilters {
  507. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  508. errc <- f(sw.peers, p)
  509. }(f, p, errc)
  510. }
  511. for i := 0; i < cap(errc); i++ {
  512. select {
  513. case err := <-errc:
  514. if err != nil {
  515. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  516. }
  517. case <-time.After(sw.filterTimeout):
  518. return ErrFilterTimeout{}
  519. }
  520. }
  521. return nil
  522. }
  523. // addPeer starts up the Peer and adds it to the Switch.
  524. func (sw *Switch) addPeer(p Peer) error {
  525. if err := sw.filterPeer(p); err != nil {
  526. return err
  527. }
  528. p.SetLogger(sw.Logger.With("peer", p.NodeInfo().NetAddress()))
  529. // All good. Start peer
  530. if sw.IsRunning() {
  531. if err := sw.startInitPeer(p); err != nil {
  532. return err
  533. }
  534. }
  535. // Add the peer to .peers.
  536. // We start it first so that a peer in the list is safe to Stop.
  537. // It should not err since we already checked peers.Has().
  538. if err := sw.peers.Add(p); err != nil {
  539. return err
  540. }
  541. sw.Logger.Info("Added peer", "peer", p)
  542. sw.metrics.Peers.Add(float64(1))
  543. return nil
  544. }
  545. func (sw *Switch) startInitPeer(p Peer) error {
  546. err := p.Start() // spawn send/recv routines
  547. if err != nil {
  548. // Should never happen
  549. sw.Logger.Error(
  550. "Error starting peer",
  551. "err", err,
  552. "peer", p,
  553. )
  554. return err
  555. }
  556. for _, reactor := range sw.reactors {
  557. reactor.AddPeer(p)
  558. }
  559. return nil
  560. }