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.

603 lines
17 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 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
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 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
9 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
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 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
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 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
9 years ago
7 years ago
9 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
9 years ago
7 years ago
7 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
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
  1. package p2p
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "net"
  6. "time"
  7. "github.com/pkg/errors"
  8. crypto "github.com/tendermint/go-crypto"
  9. cfg "github.com/tendermint/tendermint/config"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. )
  12. const (
  13. reconnectAttempts = 30
  14. reconnectInterval = 3 * time.Second
  15. )
  16. type Reactor interface {
  17. cmn.Service // Start, Stop
  18. SetSwitch(*Switch)
  19. GetChannels() []*ChannelDescriptor
  20. AddPeer(peer Peer)
  21. RemovePeer(peer Peer, reason interface{})
  22. Receive(chID byte, peer Peer, msgBytes []byte) // CONTRACT: msgBytes are not nil
  23. }
  24. //--------------------------------------
  25. type BaseReactor struct {
  26. cmn.BaseService // Provides Start, Stop, .Quit
  27. Switch *Switch
  28. }
  29. func NewBaseReactor(name string, impl Reactor) *BaseReactor {
  30. return &BaseReactor{
  31. BaseService: *cmn.NewBaseService(nil, name, impl),
  32. Switch: nil,
  33. }
  34. }
  35. func (br *BaseReactor) SetSwitch(sw *Switch) {
  36. br.Switch = sw
  37. }
  38. func (_ *BaseReactor) GetChannels() []*ChannelDescriptor { return nil }
  39. func (_ *BaseReactor) AddPeer(peer Peer) {}
  40. func (_ *BaseReactor) RemovePeer(peer Peer, reason interface{}) {}
  41. func (_ *BaseReactor) Receive(chID byte, peer Peer, msgBytes []byte) {}
  42. //-----------------------------------------------------------------------------
  43. /*
  44. The `Switch` handles peer connections and exposes an API to receive incoming messages
  45. on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  46. or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  47. incoming messages are received on the reactor.
  48. */
  49. type Switch struct {
  50. cmn.BaseService
  51. config *cfg.P2PConfig
  52. peerConfig *PeerConfig
  53. listeners []Listener
  54. reactors map[string]Reactor
  55. chDescs []*ChannelDescriptor
  56. reactorsByCh map[byte]Reactor
  57. peers *PeerSet
  58. dialing *cmn.CMap
  59. nodeInfo *NodeInfo // our node info
  60. nodePrivKey crypto.PrivKeyEd25519 // our node privkey
  61. filterConnByAddr func(net.Addr) error
  62. filterConnByPubKey func(crypto.PubKeyEd25519) error
  63. }
  64. var (
  65. ErrSwitchDuplicatePeer = errors.New("Duplicate peer")
  66. )
  67. func NewSwitch(config *cfg.P2PConfig) *Switch {
  68. sw := &Switch{
  69. config: config,
  70. peerConfig: DefaultPeerConfig(),
  71. reactors: make(map[string]Reactor),
  72. chDescs: make([]*ChannelDescriptor, 0),
  73. reactorsByCh: make(map[byte]Reactor),
  74. peers: NewPeerSet(),
  75. dialing: cmn.NewCMap(),
  76. nodeInfo: nil,
  77. }
  78. // TODO: collapse the peerConfig into the config ?
  79. sw.peerConfig.MConfig.flushThrottle = time.Duration(config.FlushThrottleTimeout) * time.Millisecond
  80. sw.peerConfig.MConfig.SendRate = config.SendRate
  81. sw.peerConfig.MConfig.RecvRate = config.RecvRate
  82. sw.peerConfig.MConfig.maxMsgPacketPayloadSize = config.MaxMsgPacketPayloadSize
  83. sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw)
  84. return sw
  85. }
  86. // AddReactor adds the given reactor to the switch.
  87. // NOTE: Not goroutine safe.
  88. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  89. // Validate the reactor.
  90. // No two reactors can share the same channel.
  91. reactorChannels := reactor.GetChannels()
  92. for _, chDesc := range reactorChannels {
  93. chID := chDesc.ID
  94. if sw.reactorsByCh[chID] != nil {
  95. cmn.PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  96. }
  97. sw.chDescs = append(sw.chDescs, chDesc)
  98. sw.reactorsByCh[chID] = reactor
  99. }
  100. sw.reactors[name] = reactor
  101. reactor.SetSwitch(sw)
  102. return reactor
  103. }
  104. // Reactors returns a map of reactors registered on the switch.
  105. // NOTE: Not goroutine safe.
  106. func (sw *Switch) Reactors() map[string]Reactor {
  107. return sw.reactors
  108. }
  109. // Reactor returns the reactor with the given name.
  110. // NOTE: Not goroutine safe.
  111. func (sw *Switch) Reactor(name string) Reactor {
  112. return sw.reactors[name]
  113. }
  114. // AddListener adds the given listener to the switch for listening to incoming peer connections.
  115. // NOTE: Not goroutine safe.
  116. func (sw *Switch) AddListener(l Listener) {
  117. sw.listeners = append(sw.listeners, l)
  118. }
  119. // Listeners returns the list of listeners the switch listens on.
  120. // NOTE: Not goroutine safe.
  121. func (sw *Switch) Listeners() []Listener {
  122. return sw.listeners
  123. }
  124. // IsListening returns true if the switch has at least one listener.
  125. // NOTE: Not goroutine safe.
  126. func (sw *Switch) IsListening() bool {
  127. return len(sw.listeners) > 0
  128. }
  129. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  130. // NOTE: Not goroutine safe.
  131. func (sw *Switch) SetNodeInfo(nodeInfo *NodeInfo) {
  132. sw.nodeInfo = nodeInfo
  133. }
  134. // NodeInfo returns the switch's NodeInfo.
  135. // NOTE: Not goroutine safe.
  136. func (sw *Switch) NodeInfo() *NodeInfo {
  137. return sw.nodeInfo
  138. }
  139. // SetNodePrivKey sets the switch's private key for authenticated encryption.
  140. // NOTE: Overwrites sw.nodeInfo.PubKey.
  141. // NOTE: Not goroutine safe.
  142. func (sw *Switch) SetNodePrivKey(nodePrivKey crypto.PrivKeyEd25519) {
  143. sw.nodePrivKey = nodePrivKey
  144. if sw.nodeInfo != nil {
  145. sw.nodeInfo.PubKey = nodePrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519)
  146. }
  147. }
  148. // OnStart implements BaseService. It starts all the reactors, peers, and listeners.
  149. func (sw *Switch) OnStart() error {
  150. // Start reactors
  151. for _, reactor := range sw.reactors {
  152. err := reactor.Start()
  153. if err != nil {
  154. return errors.Wrapf(err, "failed to start %v", reactor)
  155. }
  156. }
  157. // Start listeners
  158. for _, listener := range sw.listeners {
  159. go sw.listenerRoutine(listener)
  160. }
  161. return nil
  162. }
  163. // OnStop implements BaseService. It stops all listeners, peers, and reactors.
  164. func (sw *Switch) OnStop() {
  165. // Stop listeners
  166. for _, listener := range sw.listeners {
  167. listener.Stop()
  168. }
  169. sw.listeners = nil
  170. // Stop peers
  171. for _, peer := range sw.peers.List() {
  172. peer.Stop()
  173. sw.peers.Remove(peer)
  174. }
  175. // Stop reactors
  176. for _, reactor := range sw.reactors {
  177. reactor.Stop()
  178. }
  179. }
  180. // addPeer checks the given peer's validity, performs a handshake, and adds the
  181. // peer to the switch and to all registered reactors.
  182. // NOTE: This performs a blocking handshake before the peer is added.
  183. // NOTE: If error is returned, caller is responsible for calling peer.CloseConn()
  184. func (sw *Switch) addPeer(peer *peer) error {
  185. if err := sw.FilterConnByAddr(peer.Addr()); err != nil {
  186. return err
  187. }
  188. if err := sw.FilterConnByPubKey(peer.PubKey()); err != nil {
  189. return err
  190. }
  191. if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.peerConfig.HandshakeTimeout*time.Second)); err != nil {
  192. return err
  193. }
  194. // Avoid self
  195. if sw.nodeInfo.PubKey.Equals(peer.PubKey().Wrap()) {
  196. return errors.New("Ignoring connection from self")
  197. }
  198. // Check version, chain id
  199. if err := sw.nodeInfo.CompatibleWith(peer.NodeInfo()); err != nil {
  200. return err
  201. }
  202. // Check for duplicate peer
  203. if sw.peers.Has(peer.Key()) {
  204. return ErrSwitchDuplicatePeer
  205. }
  206. // Start peer
  207. if sw.IsRunning() {
  208. sw.startInitPeer(peer)
  209. }
  210. // Add the peer to .peers.
  211. // We start it first so that a peer in the list is safe to Stop.
  212. // It should not err since we already checked peers.Has().
  213. if err := sw.peers.Add(peer); err != nil {
  214. return err
  215. }
  216. sw.Logger.Info("Added peer", "peer", peer)
  217. return nil
  218. }
  219. // FilterConnByAddr returns an error if connecting to the given address is forbidden.
  220. func (sw *Switch) FilterConnByAddr(addr net.Addr) error {
  221. if sw.filterConnByAddr != nil {
  222. return sw.filterConnByAddr(addr)
  223. }
  224. return nil
  225. }
  226. // FilterConnByPubKey returns an error if connecting to the given public key is forbidden.
  227. func (sw *Switch) FilterConnByPubKey(pubkey crypto.PubKeyEd25519) error {
  228. if sw.filterConnByPubKey != nil {
  229. return sw.filterConnByPubKey(pubkey)
  230. }
  231. return nil
  232. }
  233. // SetAddrFilter sets the function for filtering connections by address.
  234. func (sw *Switch) SetAddrFilter(f func(net.Addr) error) {
  235. sw.filterConnByAddr = f
  236. }
  237. // SetPubKeyFilter sets the function for filtering connections by public key.
  238. func (sw *Switch) SetPubKeyFilter(f func(crypto.PubKeyEd25519) error) {
  239. sw.filterConnByPubKey = f
  240. }
  241. func (sw *Switch) startInitPeer(peer *peer) {
  242. err := peer.Start() // spawn send/recv routines
  243. if err != nil {
  244. // Should never happen
  245. sw.Logger.Error("Error starting peer", "peer", peer, "err", err)
  246. }
  247. for _, reactor := range sw.reactors {
  248. reactor.AddPeer(peer)
  249. }
  250. }
  251. // DialSeeds dials a list of seeds asynchronously in random order.
  252. func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error {
  253. netAddrs, err := NewNetAddressStrings(seeds)
  254. if err != nil {
  255. return err
  256. }
  257. if addrBook != nil {
  258. // add seeds to `addrBook`
  259. ourAddrS := sw.nodeInfo.ListenAddr
  260. ourAddr, _ := NewNetAddressString(ourAddrS)
  261. for _, netAddr := range netAddrs {
  262. // do not add ourselves
  263. if netAddr.Equals(ourAddr) {
  264. continue
  265. }
  266. addrBook.AddAddress(netAddr, ourAddr)
  267. }
  268. addrBook.Save()
  269. }
  270. // Ensure we have a completely undeterministic PRNG. cmd.RandInt64() draws
  271. // from a seed that's initialized with OS entropy on process start.
  272. rng := rand.New(rand.NewSource(cmn.RandInt64()))
  273. // permute the list, dial them in random order.
  274. perm := rng.Perm(len(netAddrs))
  275. for i := 0; i < len(perm); i++ {
  276. go func(i int) {
  277. time.Sleep(time.Duration(rng.Int63n(3000)) * time.Millisecond)
  278. j := perm[i]
  279. sw.dialSeed(netAddrs[j])
  280. }(i)
  281. }
  282. return nil
  283. }
  284. func (sw *Switch) dialSeed(addr *NetAddress) {
  285. peer, err := sw.DialPeerWithAddress(addr, true)
  286. if err != nil {
  287. sw.Logger.Error("Error dialing seed", "err", err)
  288. } else {
  289. sw.Logger.Info("Connected to seed", "peer", peer)
  290. }
  291. }
  292. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects successfully.
  293. // If `persistent == true`, the switch will always try to reconnect to this peer if the connection ever fails.
  294. func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (Peer, error) {
  295. sw.dialing.Set(addr.IP.String(), addr)
  296. defer sw.dialing.Delete(addr.IP.String())
  297. sw.Logger.Info("Dialing peer", "address", addr)
  298. peer, err := newOutboundPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig)
  299. if err != nil {
  300. sw.Logger.Error("Failed to dial peer", "address", addr, "err", err)
  301. return nil, err
  302. }
  303. peer.SetLogger(sw.Logger.With("peer", addr))
  304. if persistent {
  305. peer.makePersistent()
  306. }
  307. err = sw.addPeer(peer)
  308. if err != nil {
  309. sw.Logger.Error("Failed to add peer", "address", addr, "err", err)
  310. peer.CloseConn()
  311. return nil, err
  312. }
  313. sw.Logger.Info("Dialed and added peer", "address", addr, "peer", peer)
  314. return peer, nil
  315. }
  316. // IsDialing returns true if the switch is currently dialing the given address.
  317. func (sw *Switch) IsDialing(addr *NetAddress) bool {
  318. return sw.dialing.Has(addr.IP.String())
  319. }
  320. // Broadcast runs a go routine for each attempted send, which will block
  321. // trying to send for defaultSendTimeoutSeconds. Returns a channel
  322. // which receives success values for each attempted send (false if times out).
  323. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  324. // TODO: Something more intelligent.
  325. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool {
  326. successChan := make(chan bool, len(sw.peers.List()))
  327. sw.Logger.Debug("Broadcast", "channel", chID, "msg", msg)
  328. for _, peer := range sw.peers.List() {
  329. go func(peer Peer) {
  330. success := peer.Send(chID, msg)
  331. successChan <- success
  332. }(peer)
  333. }
  334. return successChan
  335. }
  336. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  337. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  338. peers := sw.peers.List()
  339. for _, peer := range peers {
  340. if peer.IsOutbound() {
  341. outbound++
  342. } else {
  343. inbound++
  344. }
  345. }
  346. dialing = sw.dialing.Size()
  347. return
  348. }
  349. // Peers returns the set of peers that are connected to the switch.
  350. func (sw *Switch) Peers() IPeerSet {
  351. return sw.peers
  352. }
  353. // StopPeerForError disconnects from a peer due to external error.
  354. // If the peer is persistent, it will attempt to reconnect.
  355. // TODO: make record depending on reason.
  356. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  357. addr, _ := NewNetAddressString(peer.NodeInfo().RemoteAddr)
  358. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  359. sw.stopAndRemovePeer(peer, reason)
  360. if peer.IsPersistent() {
  361. go func() {
  362. sw.Logger.Info("Reconnecting to peer", "peer", peer)
  363. for i := 1; i < reconnectAttempts; i++ {
  364. if !sw.IsRunning() {
  365. return
  366. }
  367. peer, err := sw.DialPeerWithAddress(addr, true)
  368. if err != nil {
  369. if i == reconnectAttempts {
  370. sw.Logger.Info("Error reconnecting to peer. Giving up", "tries", i, "err", err)
  371. return
  372. }
  373. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err)
  374. time.Sleep(reconnectInterval)
  375. continue
  376. }
  377. sw.Logger.Info("Reconnected to peer", "peer", peer)
  378. return
  379. }
  380. }()
  381. }
  382. }
  383. // StopPeerGracefully disconnects from a peer gracefully.
  384. // TODO: handle graceful disconnects.
  385. func (sw *Switch) StopPeerGracefully(peer Peer) {
  386. sw.Logger.Info("Stopping peer gracefully")
  387. sw.stopAndRemovePeer(peer, nil)
  388. }
  389. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  390. sw.peers.Remove(peer)
  391. peer.Stop()
  392. for _, reactor := range sw.reactors {
  393. reactor.RemovePeer(peer, reason)
  394. }
  395. }
  396. func (sw *Switch) listenerRoutine(l Listener) {
  397. for {
  398. inConn, ok := <-l.Connections()
  399. if !ok {
  400. break
  401. }
  402. // ignore connection if we already have enough
  403. maxPeers := sw.config.MaxNumPeers
  404. if maxPeers <= sw.peers.Size() {
  405. sw.Logger.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers)
  406. continue
  407. }
  408. // New inbound connection!
  409. err := sw.addPeerWithConnectionAndConfig(inConn, sw.peerConfig)
  410. if err != nil {
  411. sw.Logger.Info("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "err", err)
  412. continue
  413. }
  414. // NOTE: We don't yet have the listening port of the
  415. // remote (if they have a listener at all).
  416. // The peerHandshake will handle that.
  417. }
  418. // cleanup
  419. }
  420. //------------------------------------------------------------------
  421. // Connects switches via arbitrary net.Conn. Used for testing.
  422. // MakeConnectedSwitches returns n switches, connected according to the connect func.
  423. // If connect==Connect2Switches, the switches will be fully connected.
  424. // initSwitch defines how the i'th switch should be initialized (ie. with what reactors).
  425. // NOTE: panics if any switch fails to start.
  426. func MakeConnectedSwitches(cfg *cfg.P2PConfig, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch {
  427. switches := make([]*Switch, n)
  428. for i := 0; i < n; i++ {
  429. switches[i] = makeSwitch(cfg, i, "testing", "123.123.123", initSwitch)
  430. }
  431. if err := StartSwitches(switches); err != nil {
  432. panic(err)
  433. }
  434. for i := 0; i < n; i++ {
  435. for j := i + 1; j < n; j++ {
  436. connect(switches, i, j)
  437. }
  438. }
  439. return switches
  440. }
  441. // Connect2Switches will connect switches i and j via net.Pipe().
  442. // Blocks until a connection is established.
  443. // NOTE: caller ensures i and j are within bounds.
  444. func Connect2Switches(switches []*Switch, i, j int) {
  445. switchI := switches[i]
  446. switchJ := switches[j]
  447. c1, c2 := netPipe()
  448. doneCh := make(chan struct{})
  449. go func() {
  450. err := switchI.addPeerWithConnection(c1)
  451. if err != nil {
  452. panic(err)
  453. }
  454. doneCh <- struct{}{}
  455. }()
  456. go func() {
  457. err := switchJ.addPeerWithConnection(c2)
  458. if err != nil {
  459. panic(err)
  460. }
  461. doneCh <- struct{}{}
  462. }()
  463. <-doneCh
  464. <-doneCh
  465. }
  466. // StartSwitches calls sw.Start() for each given switch.
  467. // It returns the first encountered error.
  468. func StartSwitches(switches []*Switch) error {
  469. for _, s := range switches {
  470. err := s.Start() // start switch and reactors
  471. if err != nil {
  472. return err
  473. }
  474. }
  475. return nil
  476. }
  477. func makeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch {
  478. privKey := crypto.GenPrivKeyEd25519()
  479. // new switch, add reactors
  480. // TODO: let the config be passed in?
  481. s := initSwitch(i, NewSwitch(cfg))
  482. s.SetNodeInfo(&NodeInfo{
  483. PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  484. Moniker: cmn.Fmt("switch%d", i),
  485. Network: network,
  486. Version: version,
  487. RemoteAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
  488. ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
  489. })
  490. s.SetNodePrivKey(privKey)
  491. return s
  492. }
  493. func (sw *Switch) addPeerWithConnection(conn net.Conn) error {
  494. peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig)
  495. if err != nil {
  496. if err := conn.Close(); err != nil {
  497. sw.Logger.Error("Error closing connection", "err", err)
  498. }
  499. return err
  500. }
  501. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  502. if err = sw.addPeer(peer); err != nil {
  503. peer.CloseConn()
  504. return err
  505. }
  506. return nil
  507. }
  508. func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConfig) error {
  509. peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config)
  510. if err != nil {
  511. if err := conn.Close(); err != nil {
  512. sw.Logger.Error("Error closing connection", "err", err)
  513. }
  514. return err
  515. }
  516. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  517. if err = sw.addPeer(peer); err != nil {
  518. peer.CloseConn()
  519. return err
  520. }
  521. return nil
  522. }