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.

375 lines
10 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package p2p
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "sync/atomic"
  8. "time"
  9. acm "github.com/tendermint/tendermint/account"
  10. . "github.com/tendermint/tendermint/common"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. type Reactor interface {
  14. Start(sw *Switch)
  15. Stop()
  16. GetChannels() []*ChannelDescriptor
  17. AddPeer(peer *Peer)
  18. RemovePeer(peer *Peer, reason interface{})
  19. Receive(chId byte, peer *Peer, msgBytes []byte)
  20. }
  21. //--------------------------------------
  22. type BaseReactor struct{}
  23. func (_ BaseReactor) Start(sw *Switch) {}
  24. func (_ BaseReactor) Stop() {}
  25. func (_ BaseReactor) GetChannels() []*ChannelDescriptor { return nil }
  26. func (_ BaseReactor) AddPeer(peer *Peer) {}
  27. func (_ BaseReactor) RemovePeer(peer *Peer, reason interface{}) {}
  28. func (_ BaseReactor) Receive(chId byte, peer *Peer, msgBytes []byte) {}
  29. //-----------------------------------------------------------------------------
  30. /*
  31. The `Switch` handles peer connections and exposes an API to receive incoming messages
  32. on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  33. or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  34. incoming messages are received on the reactor.
  35. */
  36. type Switch struct {
  37. listeners []Listener
  38. reactors map[string]Reactor
  39. chDescs []*ChannelDescriptor
  40. reactorsByCh map[byte]Reactor
  41. peers *PeerSet
  42. dialing *CMap
  43. running uint32
  44. nodeInfo *types.NodeInfo // our node info
  45. nodePrivKey acm.PrivKeyEd25519 // our node privkey
  46. }
  47. var (
  48. ErrSwitchDuplicatePeer = errors.New("Duplicate peer")
  49. ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers")
  50. )
  51. const (
  52. peerDialTimeoutSeconds = 3 // TODO make this configurable
  53. handshakeTimeoutSeconds = 20 // TODO make this configurable
  54. maxNumPeers = 50 // TODO make this configurable
  55. )
  56. func NewSwitch() *Switch {
  57. sw := &Switch{
  58. reactors: make(map[string]Reactor),
  59. chDescs: make([]*ChannelDescriptor, 0),
  60. reactorsByCh: make(map[byte]Reactor),
  61. peers: NewPeerSet(),
  62. dialing: NewCMap(),
  63. running: 0,
  64. nodeInfo: nil,
  65. }
  66. return sw
  67. }
  68. // Not goroutine safe.
  69. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  70. // Validate the reactor.
  71. // No two reactors can share the same channel.
  72. reactorChannels := reactor.GetChannels()
  73. for _, chDesc := range reactorChannels {
  74. chId := chDesc.Id
  75. if sw.reactorsByCh[chId] != nil {
  76. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chId, sw.reactorsByCh[chId], reactor))
  77. }
  78. sw.chDescs = append(sw.chDescs, chDesc)
  79. sw.reactorsByCh[chId] = reactor
  80. }
  81. sw.reactors[name] = reactor
  82. return reactor
  83. }
  84. // Not goroutine safe.
  85. func (sw *Switch) Reactors() map[string]Reactor {
  86. return sw.reactors
  87. }
  88. // Not goroutine safe.
  89. func (sw *Switch) Reactor(name string) Reactor {
  90. return sw.reactors[name]
  91. }
  92. // Not goroutine safe.
  93. func (sw *Switch) AddListener(l Listener) {
  94. sw.listeners = append(sw.listeners, l)
  95. }
  96. // Not goroutine safe.
  97. func (sw *Switch) Listeners() []Listener {
  98. return sw.listeners
  99. }
  100. // Not goroutine safe.
  101. func (sw *Switch) IsListening() bool {
  102. return len(sw.listeners) > 0
  103. }
  104. // Not goroutine safe.
  105. func (sw *Switch) SetNodeInfo(nodeInfo *types.NodeInfo) {
  106. sw.nodeInfo = nodeInfo
  107. }
  108. // Not goroutine safe.
  109. func (sw *Switch) NodeInfo() *types.NodeInfo {
  110. return sw.nodeInfo
  111. }
  112. // Not goroutine safe.
  113. // NOTE: Overwrites sw.nodeInfo.PubKey
  114. func (sw *Switch) SetNodePrivKey(nodePrivKey acm.PrivKeyEd25519) {
  115. sw.nodePrivKey = nodePrivKey
  116. if sw.nodeInfo != nil {
  117. sw.nodeInfo.PubKey = nodePrivKey.PubKey().(acm.PubKeyEd25519)
  118. }
  119. }
  120. func (sw *Switch) Start() {
  121. if atomic.CompareAndSwapUint32(&sw.running, 0, 1) {
  122. // Start reactors
  123. for _, reactor := range sw.reactors {
  124. reactor.Start(sw)
  125. }
  126. // Start peers
  127. for _, peer := range sw.peers.List() {
  128. sw.startInitPeer(peer)
  129. }
  130. // Start listeners
  131. for _, listener := range sw.listeners {
  132. go sw.listenerRoutine(listener)
  133. }
  134. }
  135. }
  136. func (sw *Switch) Stop() {
  137. if atomic.CompareAndSwapUint32(&sw.running, 1, 0) {
  138. // Stop listeners
  139. for _, listener := range sw.listeners {
  140. listener.Stop()
  141. }
  142. sw.listeners = nil
  143. // Stop peers
  144. for _, peer := range sw.peers.List() {
  145. peer.stop()
  146. }
  147. sw.peers = NewPeerSet()
  148. // Stop reactors
  149. for _, reactor := range sw.reactors {
  150. reactor.Stop()
  151. }
  152. }
  153. }
  154. // NOTE: This performs a blocking handshake before the peer is added.
  155. // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed.
  156. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) {
  157. // Set deadline for handshake so we don't block forever on conn.ReadFull
  158. conn.SetDeadline(time.Now().Add(handshakeTimeoutSeconds * time.Second))
  159. // First, encrypt the connection.
  160. sconn, err := MakeSecretConnection(conn, sw.nodePrivKey)
  161. if err != nil {
  162. conn.Close()
  163. return nil, err
  164. }
  165. // Then, perform node handshake
  166. peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo)
  167. if err != nil {
  168. sconn.Close()
  169. return nil, err
  170. }
  171. // Check that the professed PubKey matches the sconn's.
  172. if !peerNodeInfo.PubKey.Equals(sconn.RemotePubKey()) {
  173. sconn.Close()
  174. return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v",
  175. peerNodeInfo.PubKey, sconn.RemotePubKey())
  176. }
  177. // Avoid self
  178. if peerNodeInfo.PubKey.Equals(sw.nodeInfo.PubKey) {
  179. sconn.Close()
  180. return nil, fmt.Errorf("Ignoring connection from self")
  181. }
  182. // Check version, chain id
  183. if err := sw.nodeInfo.CompatibleWith(peerNodeInfo); err != nil {
  184. sconn.Close()
  185. return nil, err
  186. }
  187. // The peerNodeInfo is not verified, so overwrite
  188. // the IP, and the port too if we dialed out
  189. // Everything else we just have to trust
  190. ip, port, _ := net.SplitHostPort(sconn.RemoteAddr().String())
  191. peerNodeInfo.Host = ip
  192. if outbound {
  193. porti, _ := strconv.Atoi(port)
  194. peerNodeInfo.P2PPort = uint16(porti)
  195. }
  196. peer := newPeer(sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError)
  197. // Add the peer to .peers
  198. // ignore if duplicate or if we already have too many for that IP range
  199. if err := sw.peers.Add(peer); err != nil {
  200. log.Notice("Ignoring peer", "error", err, "peer", peer)
  201. peer.mconn.Stop()
  202. return nil, err
  203. }
  204. // remove deadline and start peer
  205. conn.SetDeadline(time.Time{})
  206. if atomic.LoadUint32(&sw.running) == 1 {
  207. sw.startInitPeer(peer)
  208. }
  209. log.Notice("Added peer", "peer", peer)
  210. return peer, nil
  211. }
  212. func (sw *Switch) startInitPeer(peer *Peer) {
  213. peer.start() // spawn send/recv routines
  214. sw.addPeerToReactors(peer) // run AddPeer on each reactor
  215. }
  216. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) {
  217. log.Info("Dialing address", "address", addr)
  218. sw.dialing.Set(addr.IP.String(), addr)
  219. conn, err := addr.DialTimeout(peerDialTimeoutSeconds * time.Second)
  220. sw.dialing.Delete(addr.IP.String())
  221. if err != nil {
  222. log.Info("Failed dialing address", "address", addr, "error", err)
  223. return nil, err
  224. }
  225. peer, err := sw.AddPeerWithConnection(conn, true)
  226. if err != nil {
  227. log.Info("Failed adding peer", "address", addr, "conn", conn, "error", err)
  228. return nil, err
  229. }
  230. log.Notice("Dialed and added peer", "address", addr, "peer", peer)
  231. return peer, nil
  232. }
  233. func (sw *Switch) IsDialing(addr *NetAddress) bool {
  234. return sw.dialing.Has(addr.IP.String())
  235. }
  236. // Broadcast runs a go routine for each attempted send, which will block
  237. // trying to send for defaultSendTimeoutSeconds. Returns a channel
  238. // which receives success values for each attempted send (false if times out)
  239. func (sw *Switch) Broadcast(chId byte, msg interface{}) chan bool {
  240. successChan := make(chan bool, len(sw.peers.List()))
  241. log.Info("Broadcast", "channel", chId, "msg", msg)
  242. for _, peer := range sw.peers.List() {
  243. go func(peer *Peer) {
  244. success := peer.Send(chId, msg)
  245. successChan <- success
  246. }(peer)
  247. }
  248. return successChan
  249. }
  250. // Returns the count of outbound/inbound and outbound-dialing peers.
  251. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  252. peers := sw.peers.List()
  253. for _, peer := range peers {
  254. if peer.outbound {
  255. outbound++
  256. } else {
  257. inbound++
  258. }
  259. }
  260. dialing = sw.dialing.Size()
  261. return
  262. }
  263. func (sw *Switch) Peers() IPeerSet {
  264. return sw.peers
  265. }
  266. // Disconnect from a peer due to external error.
  267. // TODO: make record depending on reason.
  268. func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) {
  269. log.Notice("Stopping peer for error", "peer", peer, "error", reason)
  270. sw.peers.Remove(peer)
  271. peer.stop()
  272. sw.removePeerFromReactors(peer, reason)
  273. }
  274. // Disconnect from a peer gracefully.
  275. // TODO: handle graceful disconnects.
  276. func (sw *Switch) StopPeerGracefully(peer *Peer) {
  277. log.Notice("Stopping peer gracefully")
  278. sw.peers.Remove(peer)
  279. peer.stop()
  280. sw.removePeerFromReactors(peer, nil)
  281. }
  282. func (sw *Switch) addPeerToReactors(peer *Peer) {
  283. for _, reactor := range sw.reactors {
  284. reactor.AddPeer(peer)
  285. }
  286. }
  287. func (sw *Switch) removePeerFromReactors(peer *Peer, reason interface{}) {
  288. for _, reactor := range sw.reactors {
  289. reactor.RemovePeer(peer, reason)
  290. }
  291. }
  292. func (sw *Switch) listenerRoutine(l Listener) {
  293. for {
  294. inConn, ok := <-l.Connections()
  295. if !ok {
  296. break
  297. }
  298. // ignore connection if we already have enough
  299. if maxNumPeers <= sw.peers.Size() {
  300. log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxNumPeers)
  301. continue
  302. }
  303. // Ignore connections from IP ranges for which we have too many
  304. if sw.peers.HasMaxForIPRange(inConn) {
  305. log.Info("Ignoring inbound connection: already have enough peers for that IP range", "address", inConn.RemoteAddr().String())
  306. continue
  307. }
  308. // New inbound connection!
  309. _, err := sw.AddPeerWithConnection(inConn, false)
  310. if err != nil {
  311. log.Notice("Ignoring inbound connection: error on AddPeerWithConnection", "address", inConn.RemoteAddr().String(), "error", err)
  312. continue
  313. }
  314. // NOTE: We don't yet have the listening port of the
  315. // remote (if they have a listener at all).
  316. // The peerHandshake will handle that
  317. }
  318. // cleanup
  319. }
  320. //-----------------------------------------------------------------------------
  321. type SwitchEventNewPeer struct {
  322. Peer *Peer
  323. }
  324. type SwitchEventDonePeer struct {
  325. Peer *Peer
  326. Error interface{}
  327. }