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.

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