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.

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