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.

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