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.

562 lines
14 KiB

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