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.

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