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.

649 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
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
7 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
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.PrivKey // our node privkey
  71. filterConnByAddr func(net.Addr) error
  72. filterConnByPubKey func(crypto.PubKey) 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.PrivKey) {
  157. sw.nodePrivKey = nodePrivKey
  158. if sw.nodeInfo != nil {
  159. sw.nodeInfo.PubKey = nodePrivKey.PubKey()
  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. for _, listener := range sw.listeners {
  181. listener.Stop()
  182. }
  183. sw.listeners = nil
  184. // Stop peers
  185. for _, peer := range sw.peers.List() {
  186. peer.Stop()
  187. sw.peers.Remove(peer)
  188. }
  189. // Stop reactors
  190. sw.Logger.Debug("Switch: Stopping reactors")
  191. for _, reactor := range sw.reactors {
  192. reactor.Stop()
  193. }
  194. }
  195. // addPeer checks the given peer's validity, performs a handshake, and adds the
  196. // peer to the switch and to all registered reactors.
  197. // NOTE: This performs a blocking handshake before the peer is added.
  198. // NOTE: If error is returned, caller is responsible for calling peer.CloseConn()
  199. func (sw *Switch) addPeer(peer *peer) error {
  200. // Avoid self
  201. if sw.nodeInfo.PubKey.Equals(peer.PubKey().Wrap()) {
  202. return errors.New("Ignoring connection from self")
  203. }
  204. // Filter peer against white list
  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 duplicate
  215. if sw.peers.Has(peer.Key()) {
  216. return ErrSwitchDuplicatePeer
  217. }
  218. // Check version, chain id
  219. if err := sw.nodeInfo.CompatibleWith(peer.NodeInfo()); err != nil {
  220. return err
  221. }
  222. // Start peer
  223. if sw.IsRunning() {
  224. sw.startInitPeer(peer)
  225. }
  226. // Add the peer to .peers.
  227. // We start it first so that a peer in the list is safe to Stop.
  228. // It should not err since we already checked peers.Has().
  229. if err := sw.peers.Add(peer); err != nil {
  230. return err
  231. }
  232. sw.Logger.Info("Added peer", "peer", peer)
  233. return nil
  234. }
  235. // FilterConnByAddr returns an error if connecting to the given address is forbidden.
  236. func (sw *Switch) FilterConnByAddr(addr net.Addr) error {
  237. if sw.filterConnByAddr != nil {
  238. return sw.filterConnByAddr(addr)
  239. }
  240. return nil
  241. }
  242. // FilterConnByPubKey returns an error if connecting to the given public key is forbidden.
  243. func (sw *Switch) FilterConnByPubKey(pubkey crypto.PubKey) error {
  244. if sw.filterConnByPubKey != nil {
  245. return sw.filterConnByPubKey(pubkey)
  246. }
  247. return nil
  248. }
  249. // SetAddrFilter sets the function for filtering connections by address.
  250. func (sw *Switch) SetAddrFilter(f func(net.Addr) error) {
  251. sw.filterConnByAddr = f
  252. }
  253. // SetPubKeyFilter sets the function for filtering connections by public key.
  254. func (sw *Switch) SetPubKeyFilter(f func(crypto.PubKey) error) {
  255. sw.filterConnByPubKey = f
  256. }
  257. func (sw *Switch) startInitPeer(peer *peer) {
  258. err := peer.Start() // spawn send/recv routines
  259. if err != nil {
  260. // Should never happen
  261. sw.Logger.Error("Error starting peer", "peer", peer, "err", err)
  262. }
  263. for _, reactor := range sw.reactors {
  264. reactor.AddPeer(peer)
  265. }
  266. }
  267. // DialSeeds dials a list of seeds asynchronously in random order.
  268. func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error {
  269. netAddrs, errs := NewNetAddressStrings(seeds)
  270. for _, err := range errs {
  271. sw.Logger.Error("Error in seed's address", "err", err)
  272. }
  273. if addrBook != nil {
  274. // add seeds to `addrBook`
  275. ourAddrS := sw.nodeInfo.ListenAddr
  276. ourAddr, _ := NewNetAddressString(ourAddrS)
  277. for _, netAddr := range netAddrs {
  278. // do not add ourselves
  279. if netAddr.Equals(ourAddr) {
  280. continue
  281. }
  282. addrBook.AddAddress(netAddr, ourAddr)
  283. }
  284. addrBook.Save()
  285. }
  286. // permute the list, dial them in random order.
  287. perm := sw.rng.Perm(len(netAddrs))
  288. for i := 0; i < len(perm); i++ {
  289. go func(i int) {
  290. sw.randomSleep(0)
  291. j := perm[i]
  292. sw.dialSeed(netAddrs[j])
  293. }(i)
  294. }
  295. return nil
  296. }
  297. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  298. func (sw *Switch) randomSleep(interval time.Duration) {
  299. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  300. time.Sleep(r + interval)
  301. }
  302. func (sw *Switch) dialSeed(addr *NetAddress) {
  303. peer, err := sw.DialPeerWithAddress(addr, true)
  304. if err != nil {
  305. sw.Logger.Error("Error dialing seed", "err", err)
  306. } else {
  307. sw.Logger.Info("Connected to seed", "peer", peer)
  308. }
  309. }
  310. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects successfully.
  311. // If `persistent == true`, the switch will always try to reconnect to this peer if the connection ever fails.
  312. func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (Peer, error) {
  313. sw.dialing.Set(addr.IP.String(), addr)
  314. defer sw.dialing.Delete(addr.IP.String())
  315. sw.Logger.Info("Dialing peer", "address", addr)
  316. peer, err := newOutboundPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig)
  317. if err != nil {
  318. sw.Logger.Error("Failed to dial peer", "address", addr, "err", err)
  319. return nil, err
  320. }
  321. peer.SetLogger(sw.Logger.With("peer", addr))
  322. if persistent {
  323. peer.makePersistent()
  324. }
  325. err = sw.addPeer(peer)
  326. if err != nil {
  327. sw.Logger.Error("Failed to add peer", "address", addr, "err", err)
  328. peer.CloseConn()
  329. return nil, err
  330. }
  331. sw.Logger.Info("Dialed and added peer", "address", addr, "peer", peer)
  332. return peer, nil
  333. }
  334. // IsDialing returns true if the switch is currently dialing the given address.
  335. func (sw *Switch) IsDialing(addr *NetAddress) bool {
  336. return sw.dialing.Has(addr.IP.String())
  337. }
  338. // Broadcast runs a go routine for each attempted send, which will block
  339. // trying to send for defaultSendTimeoutSeconds. Returns a channel
  340. // which receives success values for each attempted send (false if times out).
  341. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  342. // TODO: Something more intelligent.
  343. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool {
  344. successChan := make(chan bool, len(sw.peers.List()))
  345. sw.Logger.Debug("Broadcast", "channel", chID, "msg", msg)
  346. for _, peer := range sw.peers.List() {
  347. go func(peer Peer) {
  348. success := peer.Send(chID, msg)
  349. successChan <- success
  350. }(peer)
  351. }
  352. return successChan
  353. }
  354. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  355. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  356. peers := sw.peers.List()
  357. for _, peer := range peers {
  358. if peer.IsOutbound() {
  359. outbound++
  360. } else {
  361. inbound++
  362. }
  363. }
  364. dialing = sw.dialing.Size()
  365. return
  366. }
  367. // Peers returns the set of peers that are connected to the switch.
  368. func (sw *Switch) Peers() IPeerSet {
  369. return sw.peers
  370. }
  371. // StopPeerForError disconnects from a peer due to external error.
  372. // If the peer is persistent, it will attempt to reconnect.
  373. // TODO: make record depending on reason.
  374. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  375. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  376. sw.stopAndRemovePeer(peer, reason)
  377. if peer.IsPersistent() {
  378. go sw.reconnectToPeer(peer)
  379. }
  380. }
  381. // reconnectToPeer tries to reconnect to the peer, first repeatedly
  382. // with a fixed interval, then with exponential backoff.
  383. // If no success after all that, it stops trying, and leaves it
  384. // to the PEX/Addrbook to find the peer again
  385. func (sw *Switch) reconnectToPeer(peer Peer) {
  386. addr, _ := NewNetAddressString(peer.NodeInfo().RemoteAddr)
  387. start := time.Now()
  388. sw.Logger.Info("Reconnecting to peer", "peer", peer)
  389. for i := 0; i < reconnectAttempts; i++ {
  390. if !sw.IsRunning() {
  391. return
  392. }
  393. peer, err := sw.DialPeerWithAddress(addr, true)
  394. if err != nil {
  395. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "peer", peer)
  396. // sleep a set amount
  397. sw.randomSleep(reconnectInterval)
  398. continue
  399. } else {
  400. sw.Logger.Info("Reconnected to peer", "peer", peer)
  401. return
  402. }
  403. }
  404. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  405. "peer", peer, "elapsed", time.Since(start))
  406. for i := 0; i < reconnectBackOffAttempts; i++ {
  407. if !sw.IsRunning() {
  408. return
  409. }
  410. // sleep an exponentially increasing amount
  411. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  412. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  413. peer, err := sw.DialPeerWithAddress(addr, true)
  414. if err != nil {
  415. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "peer", peer)
  416. continue
  417. } else {
  418. sw.Logger.Info("Reconnected to peer", "peer", peer)
  419. return
  420. }
  421. }
  422. sw.Logger.Error("Failed to reconnect to peer. Giving up", "peer", peer, "elapsed", time.Since(start))
  423. }
  424. // StopPeerGracefully disconnects from a peer gracefully.
  425. // TODO: handle graceful disconnects.
  426. func (sw *Switch) StopPeerGracefully(peer Peer) {
  427. sw.Logger.Info("Stopping peer gracefully")
  428. sw.stopAndRemovePeer(peer, nil)
  429. }
  430. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  431. sw.peers.Remove(peer)
  432. peer.Stop()
  433. for _, reactor := range sw.reactors {
  434. reactor.RemovePeer(peer, reason)
  435. }
  436. }
  437. func (sw *Switch) listenerRoutine(l Listener) {
  438. for {
  439. inConn, ok := <-l.Connections()
  440. if !ok {
  441. break
  442. }
  443. // ignore connection if we already have enough
  444. maxPeers := sw.config.MaxNumPeers
  445. if maxPeers <= sw.peers.Size() {
  446. sw.Logger.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers)
  447. continue
  448. }
  449. // New inbound connection!
  450. err := sw.addPeerWithConnectionAndConfig(inConn, sw.peerConfig)
  451. if err != nil {
  452. sw.Logger.Info("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "err", err)
  453. continue
  454. }
  455. // NOTE: We don't yet have the listening port of the
  456. // remote (if they have a listener at all).
  457. // The peerHandshake will handle that.
  458. }
  459. // cleanup
  460. }
  461. //------------------------------------------------------------------
  462. // Connects switches via arbitrary net.Conn. Used for testing.
  463. // MakeConnectedSwitches returns n switches, connected according to the connect func.
  464. // If connect==Connect2Switches, the switches will be fully connected.
  465. // initSwitch defines how the i'th switch should be initialized (ie. with what reactors).
  466. // NOTE: panics if any switch fails to start.
  467. func MakeConnectedSwitches(cfg *cfg.P2PConfig, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch {
  468. switches := make([]*Switch, n)
  469. for i := 0; i < n; i++ {
  470. switches[i] = makeSwitch(cfg, i, "testing", "123.123.123", initSwitch)
  471. }
  472. if err := StartSwitches(switches); err != nil {
  473. panic(err)
  474. }
  475. for i := 0; i < n; i++ {
  476. for j := i + 1; j < n; j++ {
  477. connect(switches, i, j)
  478. }
  479. }
  480. return switches
  481. }
  482. // Connect2Switches will connect switches i and j via net.Pipe().
  483. // Blocks until a connection is established.
  484. // NOTE: caller ensures i and j are within bounds.
  485. func Connect2Switches(switches []*Switch, i, j int) {
  486. switchI := switches[i]
  487. switchJ := switches[j]
  488. c1, c2 := netPipe()
  489. doneCh := make(chan struct{})
  490. go func() {
  491. err := switchI.addPeerWithConnection(c1)
  492. if err != nil {
  493. panic(err)
  494. }
  495. doneCh <- struct{}{}
  496. }()
  497. go func() {
  498. err := switchJ.addPeerWithConnection(c2)
  499. if err != nil {
  500. panic(err)
  501. }
  502. doneCh <- struct{}{}
  503. }()
  504. <-doneCh
  505. <-doneCh
  506. }
  507. // StartSwitches calls sw.Start() for each given switch.
  508. // It returns the first encountered error.
  509. func StartSwitches(switches []*Switch) error {
  510. for _, s := range switches {
  511. err := s.Start() // start switch and reactors
  512. if err != nil {
  513. return err
  514. }
  515. }
  516. return nil
  517. }
  518. func makeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch {
  519. privKey := crypto.GenPrivKeyEd25519()
  520. // new switch, add reactors
  521. // TODO: let the config be passed in?
  522. s := initSwitch(i, NewSwitch(cfg))
  523. s.SetNodeInfo(&NodeInfo{
  524. PubKey: privKey.PubKey(),
  525. Moniker: cmn.Fmt("switch%d", i),
  526. Network: network,
  527. Version: version,
  528. RemoteAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
  529. ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
  530. })
  531. s.SetNodePrivKey(privKey.Wrap())
  532. return s
  533. }
  534. func (sw *Switch) addPeerWithConnection(conn net.Conn) error {
  535. peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig)
  536. if err != nil {
  537. if err := conn.Close(); err != nil {
  538. sw.Logger.Error("Error closing connection", "err", err)
  539. }
  540. return err
  541. }
  542. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  543. if err = sw.addPeer(peer); err != nil {
  544. peer.CloseConn()
  545. return err
  546. }
  547. return nil
  548. }
  549. func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConfig) error {
  550. peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config)
  551. if err != nil {
  552. if err := conn.Close(); err != nil {
  553. sw.Logger.Error("Error closing connection", "err", err)
  554. }
  555. return err
  556. }
  557. peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr()))
  558. if err = sw.addPeer(peer); err != nil {
  559. peer.CloseConn()
  560. return err
  561. }
  562. return nil
  563. }