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.

536 lines
16 KiB

9 years ago
9 years ago
9 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
9 years ago
9 years ago
8 years ago
9 years ago
7 years ago
7 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
7 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
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
8 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
7 years ago
8 years ago
7 years ago
8 years ago
  1. package p2p
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "net"
  7. "time"
  8. "github.com/pkg/errors"
  9. crypto "github.com/tendermint/go-crypto"
  10. cfg "github.com/tendermint/tendermint/config"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. )
  13. const (
  14. // wait a random amount of time from this interval
  15. // before dialing peers or reconnecting to help prevent DoS
  16. dialRandomizerIntervalMilliseconds = 3000
  17. // repeatedly try to reconnect for a few minutes
  18. // ie. 5 * 20 = 100s
  19. reconnectAttempts = 20
  20. reconnectInterval = 5 * time.Second
  21. // then move into exponential backoff mode for ~1day
  22. // ie. 3**10 = 16hrs
  23. reconnectBackOffAttempts = 10
  24. reconnectBackOffBaseSeconds = 3
  25. )
  26. var (
  27. ErrSwitchDuplicatePeer = errors.New("Duplicate peer")
  28. ErrSwitchConnectToSelf = errors.New("Connect to self")
  29. )
  30. //-----------------------------------------------------------------------------
  31. // `Switch` handles peer connections and exposes an API to receive incoming messages
  32. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  33. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  34. // incoming messages are received on the reactor.
  35. type Switch struct {
  36. cmn.BaseService
  37. config *cfg.P2PConfig
  38. peerConfig *PeerConfig
  39. listeners []Listener
  40. reactors map[string]Reactor
  41. chDescs []*ChannelDescriptor
  42. reactorsByCh map[byte]Reactor
  43. peers *PeerSet
  44. dialing *cmn.CMap
  45. nodeInfo NodeInfo // our node info
  46. nodeKey *NodeKey // our node privkey
  47. filterConnByAddr func(net.Addr) error
  48. filterConnByPubKey func(crypto.PubKey) error
  49. rng *rand.Rand // seed for randomizing dial times and orders
  50. }
  51. func NewSwitch(config *cfg.P2PConfig) *Switch {
  52. sw := &Switch{
  53. config: config,
  54. peerConfig: DefaultPeerConfig(),
  55. reactors: make(map[string]Reactor),
  56. chDescs: make([]*ChannelDescriptor, 0),
  57. reactorsByCh: make(map[byte]Reactor),
  58. peers: NewPeerSet(),
  59. dialing: cmn.NewCMap(),
  60. }
  61. // Ensure we have a completely undeterministic PRNG. cmd.RandInt64() draws
  62. // from a seed that's initialized with OS entropy on process start.
  63. sw.rng = rand.New(rand.NewSource(cmn.RandInt64()))
  64. // TODO: collapse the peerConfig into the config ?
  65. sw.peerConfig.MConfig.flushThrottle = time.Duration(config.FlushThrottleTimeout) * time.Millisecond
  66. sw.peerConfig.MConfig.SendRate = config.SendRate
  67. sw.peerConfig.MConfig.RecvRate = config.RecvRate
  68. sw.peerConfig.MConfig.maxMsgPacketPayloadSize = config.MaxMsgPacketPayloadSize
  69. sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw)
  70. return sw
  71. }
  72. //---------------------------------------------------------------------
  73. // Switch setup
  74. // AddReactor adds the given reactor to the switch.
  75. // NOTE: Not goroutine safe.
  76. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  77. // Validate the reactor.
  78. // No two reactors can share the same channel.
  79. reactorChannels := reactor.GetChannels()
  80. for _, chDesc := range reactorChannels {
  81. chID := chDesc.ID
  82. if sw.reactorsByCh[chID] != nil {
  83. cmn.PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  84. }
  85. sw.chDescs = append(sw.chDescs, chDesc)
  86. sw.reactorsByCh[chID] = reactor
  87. }
  88. sw.reactors[name] = reactor
  89. reactor.SetSwitch(sw)
  90. return reactor
  91. }
  92. // Reactors returns a map of reactors registered on the switch.
  93. // NOTE: Not goroutine safe.
  94. func (sw *Switch) Reactors() map[string]Reactor {
  95. return sw.reactors
  96. }
  97. // Reactor returns the reactor with the given name.
  98. // NOTE: Not goroutine safe.
  99. func (sw *Switch) Reactor(name string) Reactor {
  100. return sw.reactors[name]
  101. }
  102. // AddListener adds the given listener to the switch for listening to incoming peer connections.
  103. // NOTE: Not goroutine safe.
  104. func (sw *Switch) AddListener(l Listener) {
  105. sw.listeners = append(sw.listeners, l)
  106. }
  107. // Listeners returns the list of listeners the switch listens on.
  108. // NOTE: Not goroutine safe.
  109. func (sw *Switch) Listeners() []Listener {
  110. return sw.listeners
  111. }
  112. // IsListening returns true if the switch has at least one listener.
  113. // NOTE: Not goroutine safe.
  114. func (sw *Switch) IsListening() bool {
  115. return len(sw.listeners) > 0
  116. }
  117. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  118. // NOTE: Not goroutine safe.
  119. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  120. sw.nodeInfo = nodeInfo
  121. }
  122. // NodeInfo returns the switch's NodeInfo.
  123. // NOTE: Not goroutine safe.
  124. func (sw *Switch) NodeInfo() NodeInfo {
  125. return sw.nodeInfo
  126. }
  127. // SetNodeKey sets the switch's private key for authenticated encryption.
  128. // NOTE: Not goroutine safe.
  129. func (sw *Switch) SetNodeKey(nodeKey *NodeKey) {
  130. sw.nodeKey = nodeKey
  131. }
  132. //---------------------------------------------------------------------
  133. // Service start/stop
  134. // OnStart implements BaseService. It starts all the reactors, peers, and listeners.
  135. func (sw *Switch) OnStart() error {
  136. // Start reactors
  137. for _, reactor := range sw.reactors {
  138. err := reactor.Start()
  139. if err != nil {
  140. return errors.Wrapf(err, "failed to start %v", reactor)
  141. }
  142. }
  143. // Start listeners
  144. for _, listener := range sw.listeners {
  145. go sw.listenerRoutine(listener)
  146. }
  147. return nil
  148. }
  149. // OnStop implements BaseService. It stops all listeners, peers, and reactors.
  150. func (sw *Switch) OnStop() {
  151. // Stop listeners
  152. for _, listener := range sw.listeners {
  153. listener.Stop()
  154. }
  155. sw.listeners = nil
  156. // Stop peers
  157. for _, peer := range sw.peers.List() {
  158. peer.Stop()
  159. sw.peers.Remove(peer)
  160. }
  161. // Stop reactors
  162. sw.Logger.Debug("Switch: Stopping reactors")
  163. for _, reactor := range sw.reactors {
  164. reactor.Stop()
  165. }
  166. }
  167. //---------------------------------------------------------------------
  168. // Peers
  169. // Peers returns the set of peers that are connected to the switch.
  170. func (sw *Switch) Peers() IPeerSet {
  171. return sw.peers
  172. }
  173. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  174. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  175. peers := sw.peers.List()
  176. for _, peer := range peers {
  177. if peer.IsOutbound() {
  178. outbound++
  179. } else {
  180. inbound++
  181. }
  182. }
  183. dialing = sw.dialing.Size()
  184. return
  185. }
  186. // Broadcast runs a go routine for each attempted send, which will block
  187. // trying to send for defaultSendTimeoutSeconds. Returns a channel
  188. // which receives success values for each attempted send (false if times out).
  189. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  190. // TODO: Something more intelligent.
  191. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool {
  192. successChan := make(chan bool, len(sw.peers.List()))
  193. sw.Logger.Debug("Broadcast", "channel", chID, "msg", msg)
  194. for _, peer := range sw.peers.List() {
  195. go func(peer Peer) {
  196. success := peer.Send(chID, msg)
  197. successChan <- success
  198. }(peer)
  199. }
  200. return successChan
  201. }
  202. // StopPeerForError disconnects from a peer due to external error.
  203. // If the peer is persistent, it will attempt to reconnect.
  204. // TODO: make record depending on reason.
  205. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  206. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  207. sw.stopAndRemovePeer(peer, reason)
  208. if peer.IsPersistent() {
  209. go sw.reconnectToPeer(peer)
  210. }
  211. }
  212. // StopPeerGracefully disconnects from a peer gracefully.
  213. // TODO: handle graceful disconnects.
  214. func (sw *Switch) StopPeerGracefully(peer Peer) {
  215. sw.Logger.Info("Stopping peer gracefully")
  216. sw.stopAndRemovePeer(peer, nil)
  217. }
  218. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  219. sw.peers.Remove(peer)
  220. peer.Stop()
  221. for _, reactor := range sw.reactors {
  222. reactor.RemovePeer(peer, reason)
  223. }
  224. }
  225. // reconnectToPeer tries to reconnect to the peer, first repeatedly
  226. // with a fixed interval, then with exponential backoff.
  227. // If no success after all that, it stops trying, and leaves it
  228. // to the PEX/Addrbook to find the peer again
  229. func (sw *Switch) reconnectToPeer(peer Peer) {
  230. netAddr := peer.NodeInfo().NetAddress()
  231. start := time.Now()
  232. sw.Logger.Info("Reconnecting to peer", "peer", peer)
  233. for i := 0; i < reconnectAttempts; i++ {
  234. if !sw.IsRunning() {
  235. return
  236. }
  237. peer, err := sw.DialPeerWithAddress(netAddr, true)
  238. if err != nil {
  239. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "peer", peer)
  240. // sleep a set amount
  241. sw.randomSleep(reconnectInterval)
  242. continue
  243. } else {
  244. sw.Logger.Info("Reconnected to peer", "peer", peer)
  245. return
  246. }
  247. }
  248. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  249. "peer", peer, "elapsed", time.Since(start))
  250. for i := 0; i < reconnectBackOffAttempts; i++ {
  251. if !sw.IsRunning() {
  252. return
  253. }
  254. // sleep an exponentially increasing amount
  255. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  256. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  257. peer, err := sw.DialPeerWithAddress(netAddr, true)
  258. if err != nil {
  259. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "peer", peer)
  260. continue
  261. } else {
  262. sw.Logger.Info("Reconnected to peer", "peer", peer)
  263. return
  264. }
  265. }
  266. sw.Logger.Error("Failed to reconnect to peer. Giving up", "peer", peer, "elapsed", time.Since(start))
  267. }
  268. //---------------------------------------------------------------------
  269. // Dialing
  270. // IsDialing returns true if the switch is currently dialing the given ID.
  271. func (sw *Switch) IsDialing(id ID) bool {
  272. return sw.dialing.Has(string(id))
  273. }
  274. // DialPeersAsync dials a list of peers asynchronously in random order (optionally, making them persistent).
  275. func (sw *Switch) DialPeersAsync(addrBook *AddrBook, peers []string, persistent bool) error {
  276. netAddrs, errs := NewNetAddressStrings(peers)
  277. for _, err := range errs {
  278. sw.Logger.Error("Error in peer's address", "err", err)
  279. }
  280. if addrBook != nil {
  281. // add peers to `addrBook`
  282. ourAddr := sw.nodeInfo.NetAddress()
  283. for _, netAddr := range netAddrs {
  284. // do not add our address or ID
  285. if netAddr.Same(ourAddr) {
  286. continue
  287. }
  288. addrBook.AddAddress(netAddr, ourAddr)
  289. }
  290. addrBook.Save()
  291. }
  292. // permute the list, dial them in random order.
  293. perm := sw.rng.Perm(len(netAddrs))
  294. for i := 0; i < len(perm); i++ {
  295. go func(i int) {
  296. sw.randomSleep(0)
  297. j := perm[i]
  298. peer, err := sw.DialPeerWithAddress(netAddrs[j], persistent)
  299. if err != nil {
  300. sw.Logger.Error("Error dialing peer", "err", err)
  301. } else {
  302. sw.Logger.Info("Connected to peer", "peer", peer)
  303. }
  304. }(i)
  305. }
  306. return nil
  307. }
  308. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects and authenticates successfully.
  309. // If `persistent == true`, the switch will always try to reconnect to this peer if the connection ever fails.
  310. func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (Peer, error) {
  311. sw.dialing.Set(string(addr.ID), addr)
  312. defer sw.dialing.Delete(string(addr.ID))
  313. return sw.addOutboundPeerWithConfig(addr, sw.peerConfig, persistent)
  314. }
  315. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  316. func (sw *Switch) randomSleep(interval time.Duration) {
  317. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  318. time.Sleep(r + interval)
  319. }
  320. //------------------------------------------------------------------------------------
  321. // Connection filtering
  322. // FilterConnByAddr returns an error if connecting to the given address is forbidden.
  323. func (sw *Switch) FilterConnByAddr(addr net.Addr) error {
  324. if sw.filterConnByAddr != nil {
  325. return sw.filterConnByAddr(addr)
  326. }
  327. return nil
  328. }
  329. // FilterConnByPubKey returns an error if connecting to the given public key is forbidden.
  330. func (sw *Switch) FilterConnByPubKey(pubkey crypto.PubKey) error {
  331. if sw.filterConnByPubKey != nil {
  332. return sw.filterConnByPubKey(pubkey)
  333. }
  334. return nil
  335. }
  336. // SetAddrFilter sets the function for filtering connections by address.
  337. func (sw *Switch) SetAddrFilter(f func(net.Addr) error) {
  338. sw.filterConnByAddr = f
  339. }
  340. // SetPubKeyFilter sets the function for filtering connections by public key.
  341. func (sw *Switch) SetPubKeyFilter(f func(crypto.PubKey) error) {
  342. sw.filterConnByPubKey = f
  343. }
  344. //------------------------------------------------------------------------------------
  345. func (sw *Switch) listenerRoutine(l Listener) {
  346. for {
  347. inConn, ok := <-l.Connections()
  348. if !ok {
  349. break
  350. }
  351. // ignore connection if we already have enough
  352. maxPeers := sw.config.MaxNumPeers
  353. if maxPeers <= sw.peers.Size() {
  354. sw.Logger.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers)
  355. continue
  356. }
  357. // New inbound connection!
  358. err := sw.addInboundPeerWithConfig(inConn, sw.peerConfig)
  359. if err != nil {
  360. sw.Logger.Info("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "err", err)
  361. continue
  362. }
  363. }
  364. // cleanup
  365. }
  366. func (sw *Switch) addInboundPeerWithConfig(conn net.Conn, config *PeerConfig) error {
  367. peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodeKey.PrivKey, config)
  368. if err != nil {
  369. conn.Close() // peer is nil
  370. return err
  371. }
  372. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  373. if err = sw.addPeer(peer); err != nil {
  374. peer.CloseConn()
  375. return err
  376. }
  377. return nil
  378. }
  379. // dial the peer; make secret connection; authenticate against the dialed ID;
  380. // add the peer.
  381. func (sw *Switch) addOutboundPeerWithConfig(addr *NetAddress, config *PeerConfig, persistent bool) (Peer, error) {
  382. sw.Logger.Info("Dialing peer", "address", addr)
  383. peer, err := newOutboundPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodeKey.PrivKey, config, persistent)
  384. if err != nil {
  385. sw.Logger.Error("Failed to dial peer", "address", addr, "err", err)
  386. return nil, err
  387. }
  388. peer.SetLogger(sw.Logger.With("peer", addr))
  389. // authenticate peer
  390. if addr.ID == "" {
  391. peer.Logger.Info("Dialed peer with unknown ID - unable to authenticate", "addr", addr)
  392. } else if addr.ID != peer.ID() {
  393. peer.CloseConn()
  394. return nil, fmt.Errorf("Failed to authenticate peer %v. Connected to peer with ID %s", addr, peer.ID())
  395. }
  396. err = sw.addPeer(peer)
  397. if err != nil {
  398. sw.Logger.Error("Failed to add peer", "address", addr, "err", err)
  399. peer.CloseConn()
  400. return nil, err
  401. }
  402. sw.Logger.Info("Dialed and added peer", "address", addr, "peer", peer)
  403. return peer, nil
  404. }
  405. // addPeer performs the Tendermint P2P handshake with a peer
  406. // that already has a SecretConnection. If all goes well,
  407. // it starts the peer and adds it to the switch.
  408. // NOTE: This performs a blocking handshake before the peer is added.
  409. // NOTE: If error is returned, caller is responsible for calling peer.CloseConn()
  410. func (sw *Switch) addPeer(peer *peer) error {
  411. // Avoid self
  412. if sw.nodeKey.ID() == peer.ID() {
  413. return ErrSwitchConnectToSelf
  414. }
  415. // Avoid duplicate
  416. if sw.peers.Has(peer.ID()) {
  417. return ErrSwitchDuplicatePeer
  418. }
  419. // Filter peer against white list
  420. if err := sw.FilterConnByAddr(peer.Addr()); err != nil {
  421. return err
  422. }
  423. if err := sw.FilterConnByPubKey(peer.PubKey()); err != nil {
  424. return err
  425. }
  426. // Exchange NodeInfo with the peer
  427. if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.peerConfig.HandshakeTimeout*time.Second)); err != nil {
  428. return err
  429. }
  430. // Validate the peers nodeInfo against the pubkey
  431. if err := peer.NodeInfo().Validate(peer.PubKey()); err != nil {
  432. return err
  433. }
  434. // Check version, chain id
  435. if err := sw.nodeInfo.CompatibleWith(peer.NodeInfo()); err != nil {
  436. return err
  437. }
  438. // All good. Start peer
  439. if sw.IsRunning() {
  440. sw.startInitPeer(peer)
  441. }
  442. // Add the peer to .peers.
  443. // We start it first so that a peer in the list is safe to Stop.
  444. // It should not err since we already checked peers.Has().
  445. if err := sw.peers.Add(peer); err != nil {
  446. return err
  447. }
  448. sw.Logger.Info("Added peer", "peer", peer)
  449. return nil
  450. }
  451. func (sw *Switch) startInitPeer(peer *peer) {
  452. err := peer.Start() // spawn send/recv routines
  453. if err != nil {
  454. // Should never happen
  455. sw.Logger.Error("Error starting peer", "peer", peer, "err", err)
  456. }
  457. for _, reactor := range sw.reactors {
  458. reactor.AddPeer(peer)
  459. }
  460. }