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.

578 lines
15 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 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
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
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package p2p
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "net"
  7. "time"
  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)
  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. sw.peerConfig.MConfig.flushThrottle = time.Duration(config.FlushThrottleTimeout) * time.Millisecond // TODO: collapse the peerConfig into the config ?
  79. sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw)
  80. return sw
  81. }
  82. // Not goroutine safe.
  83. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  84. // Validate the reactor.
  85. // No two reactors can share the same channel.
  86. reactorChannels := reactor.GetChannels()
  87. for _, chDesc := range reactorChannels {
  88. chID := chDesc.ID
  89. if sw.reactorsByCh[chID] != nil {
  90. cmn.PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  91. }
  92. sw.chDescs = append(sw.chDescs, chDesc)
  93. sw.reactorsByCh[chID] = reactor
  94. }
  95. sw.reactors[name] = reactor
  96. reactor.SetSwitch(sw)
  97. return reactor
  98. }
  99. // Not goroutine safe.
  100. func (sw *Switch) Reactors() map[string]Reactor {
  101. return sw.reactors
  102. }
  103. // Not goroutine safe.
  104. func (sw *Switch) Reactor(name string) Reactor {
  105. return sw.reactors[name]
  106. }
  107. // Not goroutine safe.
  108. func (sw *Switch) AddListener(l Listener) {
  109. sw.listeners = append(sw.listeners, l)
  110. }
  111. // Not goroutine safe.
  112. func (sw *Switch) Listeners() []Listener {
  113. return sw.listeners
  114. }
  115. // Not goroutine safe.
  116. func (sw *Switch) IsListening() bool {
  117. return len(sw.listeners) > 0
  118. }
  119. // Not goroutine safe.
  120. func (sw *Switch) SetNodeInfo(nodeInfo *NodeInfo) {
  121. sw.nodeInfo = nodeInfo
  122. }
  123. // Not goroutine safe.
  124. func (sw *Switch) NodeInfo() *NodeInfo {
  125. return sw.nodeInfo
  126. }
  127. // Not goroutine safe.
  128. // NOTE: Overwrites sw.nodeInfo.PubKey
  129. func (sw *Switch) SetNodePrivKey(nodePrivKey crypto.PrivKeyEd25519) {
  130. sw.nodePrivKey = nodePrivKey
  131. if sw.nodeInfo != nil {
  132. sw.nodeInfo.PubKey = nodePrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519)
  133. }
  134. }
  135. // Switch.Start() starts all the reactors, peers, and listeners.
  136. func (sw *Switch) OnStart() error {
  137. sw.BaseService.OnStart()
  138. // Start reactors
  139. for _, reactor := range sw.reactors {
  140. _, err := reactor.Start()
  141. if err != nil {
  142. return err
  143. }
  144. }
  145. // Start peers
  146. for _, peer := range sw.peers.List() {
  147. sw.startInitPeer(peer)
  148. }
  149. // Start listeners
  150. for _, listener := range sw.listeners {
  151. go sw.listenerRoutine(listener)
  152. }
  153. return nil
  154. }
  155. func (sw *Switch) OnStop() {
  156. sw.BaseService.OnStop()
  157. // Stop listeners
  158. for _, listener := range sw.listeners {
  159. listener.Stop()
  160. }
  161. sw.listeners = nil
  162. // Stop peers
  163. for _, peer := range sw.peers.List() {
  164. peer.Stop()
  165. sw.peers.Remove(peer)
  166. }
  167. // Stop reactors
  168. for _, reactor := range sw.reactors {
  169. reactor.Stop()
  170. }
  171. }
  172. // NOTE: This performs a blocking handshake before the peer is added.
  173. // CONTRACT: If error is returned, peer is nil, and conn is immediately closed.
  174. func (sw *Switch) AddPeer(peer *Peer) error {
  175. if err := sw.FilterConnByAddr(peer.Addr()); err != nil {
  176. return err
  177. }
  178. if err := sw.FilterConnByPubKey(peer.PubKey()); err != nil {
  179. return err
  180. }
  181. if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.peerConfig.HandshakeTimeout*time.Second)); err != nil {
  182. return err
  183. }
  184. // Avoid self
  185. if sw.nodeInfo.PubKey.Equals(peer.PubKey().Wrap()) {
  186. return errors.New("Ignoring connection from self")
  187. }
  188. // Check version, chain id
  189. if err := sw.nodeInfo.CompatibleWith(peer.NodeInfo); err != nil {
  190. return err
  191. }
  192. // Check for duplicate peer
  193. if sw.peers.Has(peer.Key) {
  194. return ErrSwitchDuplicatePeer
  195. }
  196. // Start peer
  197. if sw.IsRunning() {
  198. sw.startInitPeer(peer)
  199. }
  200. // Add the peer to .peers.
  201. // We start it first so that a peer in the list is safe to Stop.
  202. // It should not err since we already checked peers.Has()
  203. if err := sw.peers.Add(peer); err != nil {
  204. return err
  205. }
  206. sw.Logger.Info("Added peer", "peer", peer)
  207. return nil
  208. }
  209. func (sw *Switch) FilterConnByAddr(addr net.Addr) error {
  210. if sw.filterConnByAddr != nil {
  211. return sw.filterConnByAddr(addr)
  212. }
  213. return nil
  214. }
  215. func (sw *Switch) FilterConnByPubKey(pubkey crypto.PubKeyEd25519) error {
  216. if sw.filterConnByPubKey != nil {
  217. return sw.filterConnByPubKey(pubkey)
  218. }
  219. return nil
  220. }
  221. func (sw *Switch) SetAddrFilter(f func(net.Addr) error) {
  222. sw.filterConnByAddr = f
  223. }
  224. func (sw *Switch) SetPubKeyFilter(f func(crypto.PubKeyEd25519) error) {
  225. sw.filterConnByPubKey = f
  226. }
  227. func (sw *Switch) startInitPeer(peer *Peer) {
  228. peer.Start() // spawn send/recv routines
  229. for _, reactor := range sw.reactors {
  230. reactor.AddPeer(peer)
  231. }
  232. }
  233. // Dial a list of seeds asynchronously in random order
  234. func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error {
  235. netAddrs, err := NewNetAddressStrings(seeds)
  236. if err != nil {
  237. return err
  238. }
  239. if addrBook != nil {
  240. // add seeds to `addrBook`
  241. ourAddrS := sw.nodeInfo.ListenAddr
  242. ourAddr, _ := NewNetAddressString(ourAddrS)
  243. for _, netAddr := range netAddrs {
  244. // do not add ourselves
  245. if netAddr.Equals(ourAddr) {
  246. continue
  247. }
  248. addrBook.AddAddress(netAddr, ourAddr)
  249. }
  250. addrBook.Save()
  251. }
  252. // permute the list, dial them in random order.
  253. perm := rand.Perm(len(netAddrs))
  254. for i := 0; i < len(perm); i++ {
  255. go func(i int) {
  256. time.Sleep(time.Duration(rand.Int63n(3000)) * time.Millisecond)
  257. j := perm[i]
  258. sw.dialSeed(netAddrs[j])
  259. }(i)
  260. }
  261. return nil
  262. }
  263. func (sw *Switch) dialSeed(addr *NetAddress) {
  264. peer, err := sw.DialPeerWithAddress(addr, true)
  265. if err != nil {
  266. sw.Logger.Error("Error dialing seed", "err", err)
  267. } else {
  268. sw.Logger.Info("Connected to seed", "peer", peer)
  269. }
  270. }
  271. func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, error) {
  272. sw.dialing.Set(addr.IP.String(), addr)
  273. defer sw.dialing.Delete(addr.IP.String())
  274. sw.Logger.Info("Dialing peer", "address", addr)
  275. peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig)
  276. if err != nil {
  277. sw.Logger.Error("Failed to dial peer", "address", addr, "err", err)
  278. return nil, err
  279. }
  280. peer.SetLogger(sw.Logger.With("peer", addr))
  281. if persistent {
  282. peer.makePersistent()
  283. }
  284. err = sw.AddPeer(peer)
  285. if err != nil {
  286. sw.Logger.Error("Failed to add peer", "address", addr, "err", err)
  287. peer.CloseConn()
  288. return nil, err
  289. }
  290. sw.Logger.Info("Dialed and added peer", "address", addr, "peer", peer)
  291. return peer, nil
  292. }
  293. func (sw *Switch) IsDialing(addr *NetAddress) bool {
  294. return sw.dialing.Has(addr.IP.String())
  295. }
  296. // Broadcast runs a go routine for each attempted send, which will block
  297. // trying to send for defaultSendTimeoutSeconds. Returns a channel
  298. // which receives success values for each attempted send (false if times out)
  299. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  300. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool {
  301. successChan := make(chan bool, len(sw.peers.List()))
  302. sw.Logger.Debug("Broadcast", "channel", chID, "msg", msg)
  303. for _, peer := range sw.peers.List() {
  304. go func(peer *Peer) {
  305. success := peer.Send(chID, msg)
  306. successChan <- success
  307. }(peer)
  308. }
  309. return successChan
  310. }
  311. // Returns the count of outbound/inbound and outbound-dialing peers.
  312. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  313. peers := sw.peers.List()
  314. for _, peer := range peers {
  315. if peer.outbound {
  316. outbound++
  317. } else {
  318. inbound++
  319. }
  320. }
  321. dialing = sw.dialing.Size()
  322. return
  323. }
  324. func (sw *Switch) Peers() IPeerSet {
  325. return sw.peers
  326. }
  327. // Disconnect from a peer due to external error, retry if it is a persistent peer.
  328. // TODO: make record depending on reason.
  329. func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) {
  330. addr := NewNetAddress(peer.Addr())
  331. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  332. sw.stopAndRemovePeer(peer, reason)
  333. if peer.IsPersistent() {
  334. go func() {
  335. sw.Logger.Info("Reconnecting to peer", "peer", peer)
  336. for i := 1; i < reconnectAttempts; i++ {
  337. if !sw.IsRunning() {
  338. return
  339. }
  340. peer, err := sw.DialPeerWithAddress(addr, true)
  341. if err != nil {
  342. if i == reconnectAttempts {
  343. sw.Logger.Info("Error reconnecting to peer. Giving up", "tries", i, "err", err)
  344. return
  345. }
  346. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err)
  347. time.Sleep(reconnectInterval)
  348. continue
  349. }
  350. sw.Logger.Info("Reconnected to peer", "peer", peer)
  351. return
  352. }
  353. }()
  354. }
  355. }
  356. // Disconnect from a peer gracefully.
  357. // TODO: handle graceful disconnects.
  358. func (sw *Switch) StopPeerGracefully(peer *Peer) {
  359. sw.Logger.Info("Stopping peer gracefully")
  360. sw.stopAndRemovePeer(peer, nil)
  361. }
  362. func (sw *Switch) stopAndRemovePeer(peer *Peer, reason interface{}) {
  363. sw.peers.Remove(peer)
  364. peer.Stop()
  365. for _, reactor := range sw.reactors {
  366. reactor.RemovePeer(peer, reason)
  367. }
  368. }
  369. func (sw *Switch) listenerRoutine(l Listener) {
  370. for {
  371. inConn, ok := <-l.Connections()
  372. if !ok {
  373. break
  374. }
  375. // ignore connection if we already have enough
  376. maxPeers := sw.config.MaxNumPeers
  377. if maxPeers <= sw.peers.Size() {
  378. sw.Logger.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers)
  379. continue
  380. }
  381. // New inbound connection!
  382. err := sw.addPeerWithConnectionAndConfig(inConn, sw.peerConfig)
  383. if err != nil {
  384. sw.Logger.Info("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "err", err)
  385. continue
  386. }
  387. // NOTE: We don't yet have the listening port of the
  388. // remote (if they have a listener at all).
  389. // The peerHandshake will handle that
  390. }
  391. // cleanup
  392. }
  393. //-----------------------------------------------------------------------------
  394. type SwitchEventNewPeer struct {
  395. Peer *Peer
  396. }
  397. type SwitchEventDonePeer struct {
  398. Peer *Peer
  399. Error interface{}
  400. }
  401. //------------------------------------------------------------------
  402. // Switches connected via arbitrary net.Conn; useful for testing
  403. // Returns n switches, connected according to the connect func.
  404. // If connect==Connect2Switches, the switches will be fully connected.
  405. // initSwitch defines how the ith switch should be initialized (ie. with what reactors).
  406. // NOTE: panics if any switch fails to start.
  407. func MakeConnectedSwitches(cfg *cfg.P2PConfig, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch {
  408. switches := make([]*Switch, n)
  409. for i := 0; i < n; i++ {
  410. switches[i] = makeSwitch(cfg, i, "testing", "123.123.123", initSwitch)
  411. }
  412. if err := StartSwitches(switches); err != nil {
  413. panic(err)
  414. }
  415. for i := 0; i < n; i++ {
  416. for j := i; j < n; j++ {
  417. connect(switches, i, j)
  418. }
  419. }
  420. return switches
  421. }
  422. var PanicOnAddPeerErr = false
  423. // Will connect switches i and j via net.Pipe()
  424. // Blocks until a conection is established.
  425. // NOTE: caller ensures i and j are within bounds
  426. func Connect2Switches(switches []*Switch, i, j int) {
  427. switchI := switches[i]
  428. switchJ := switches[j]
  429. c1, c2 := net.Pipe()
  430. doneCh := make(chan struct{})
  431. go func() {
  432. err := switchI.addPeerWithConnection(c1)
  433. if PanicOnAddPeerErr && err != nil {
  434. panic(err)
  435. }
  436. doneCh <- struct{}{}
  437. }()
  438. go func() {
  439. err := switchJ.addPeerWithConnection(c2)
  440. if PanicOnAddPeerErr && err != nil {
  441. panic(err)
  442. }
  443. doneCh <- struct{}{}
  444. }()
  445. <-doneCh
  446. <-doneCh
  447. }
  448. func StartSwitches(switches []*Switch) error {
  449. for _, s := range switches {
  450. _, err := s.Start() // start switch and reactors
  451. if err != nil {
  452. return err
  453. }
  454. }
  455. return nil
  456. }
  457. func makeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch {
  458. privKey := crypto.GenPrivKeyEd25519()
  459. // new switch, add reactors
  460. // TODO: let the config be passed in?
  461. s := initSwitch(i, NewSwitch(cfg))
  462. s.SetNodeInfo(&NodeInfo{
  463. PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  464. Moniker: cmn.Fmt("switch%d", i),
  465. Network: network,
  466. Version: version,
  467. RemoteAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
  468. ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
  469. })
  470. s.SetNodePrivKey(privKey)
  471. return s
  472. }
  473. func (sw *Switch) addPeerWithConnection(conn net.Conn) error {
  474. peer, err := newInboundPeerWithConfig(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig)
  475. if err != nil {
  476. conn.Close()
  477. return err
  478. }
  479. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  480. if err = sw.AddPeer(peer); err != nil {
  481. conn.Close()
  482. return err
  483. }
  484. return nil
  485. }
  486. func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConfig) error {
  487. peer, err := newInboundPeerWithConfig(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config)
  488. if err != nil {
  489. conn.Close()
  490. return err
  491. }
  492. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  493. if err = sw.AddPeer(peer); err != nil {
  494. conn.Close()
  495. return err
  496. }
  497. return nil
  498. }