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.

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