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.

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