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.

386 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
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. "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. panic(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) AfterStart() {
  133. // Start reactors
  134. for _, reactor := range sw.reactors {
  135. reactor.Start()
  136. }
  137. // Start peers
  138. for _, peer := range sw.peers.List() {
  139. sw.startInitPeer(peer)
  140. }
  141. // Start listeners
  142. for _, listener := range sw.listeners {
  143. go sw.listenerRoutine(listener)
  144. }
  145. }
  146. func (sw *Switch) AfterStop() {
  147. // Stop listeners
  148. for _, listener := range sw.listeners {
  149. listener.Stop()
  150. }
  151. sw.listeners = nil
  152. // Stop peers
  153. for _, peer := range sw.peers.List() {
  154. peer.Stop()
  155. }
  156. sw.peers = NewPeerSet()
  157. // Stop reactors
  158. for _, reactor := range sw.reactors {
  159. reactor.Stop()
  160. }
  161. }
  162. // NOTE: This performs a blocking handshake before the peer is added.
  163. // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed.
  164. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) {
  165. // Set deadline for handshake so we don't block forever on conn.ReadFull
  166. conn.SetDeadline(time.Now().Add(handshakeTimeoutSeconds * time.Second))
  167. // First, encrypt the connection.
  168. sconn, err := MakeSecretConnection(conn, sw.nodePrivKey)
  169. if err != nil {
  170. conn.Close()
  171. return nil, err
  172. }
  173. // Then, perform node handshake
  174. peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo)
  175. if err != nil {
  176. sconn.Close()
  177. return nil, err
  178. }
  179. // Check that the professed PubKey matches the sconn's.
  180. if !peerNodeInfo.PubKey.Equals(sconn.RemotePubKey()) {
  181. sconn.Close()
  182. return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v",
  183. peerNodeInfo.PubKey, sconn.RemotePubKey())
  184. }
  185. // Avoid self
  186. if peerNodeInfo.PubKey.Equals(sw.nodeInfo.PubKey) {
  187. sconn.Close()
  188. return nil, fmt.Errorf("Ignoring connection from self")
  189. }
  190. // Check version, chain id
  191. if err := sw.nodeInfo.CompatibleWith(peerNodeInfo); err != nil {
  192. sconn.Close()
  193. return nil, err
  194. }
  195. // The peerNodeInfo is not verified, so overwrite
  196. // the IP, and the port too if we dialed out
  197. // Everything else we just have to trust
  198. ip, port, _ := net.SplitHostPort(sconn.RemoteAddr().String())
  199. peerNodeInfo.Host = ip
  200. if outbound {
  201. porti, _ := strconv.Atoi(port)
  202. peerNodeInfo.P2PPort = uint16(porti)
  203. }
  204. peer := newPeer(sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError)
  205. // Add the peer to .peers
  206. // ignore if duplicate or if we already have too many for that IP range
  207. if err := sw.peers.Add(peer); err != nil {
  208. log.Notice("Ignoring peer", "error", err, "peer", peer)
  209. peer.Stop()
  210. return nil, err
  211. }
  212. // remove deadline and start peer
  213. conn.SetDeadline(time.Time{})
  214. if sw.IsRunning() {
  215. sw.startInitPeer(peer)
  216. }
  217. log.Notice("Added peer", "peer", peer)
  218. return peer, nil
  219. }
  220. func (sw *Switch) startInitPeer(peer *Peer) {
  221. peer.Start() // spawn send/recv routines
  222. sw.addPeerToReactors(peer) // run AddPeer on each reactor
  223. }
  224. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) {
  225. log.Info("Dialing address", "address", addr)
  226. sw.dialing.Set(addr.IP.String(), addr)
  227. conn, err := addr.DialTimeout(peerDialTimeoutSeconds * time.Second)
  228. sw.dialing.Delete(addr.IP.String())
  229. if err != nil {
  230. log.Info("Failed dialing address", "address", addr, "error", err)
  231. return nil, err
  232. }
  233. peer, err := sw.AddPeerWithConnection(conn, true)
  234. if err != nil {
  235. log.Info("Failed adding peer", "address", addr, "conn", conn, "error", err)
  236. return nil, err
  237. }
  238. log.Notice("Dialed and added peer", "address", addr, "peer", peer)
  239. return peer, nil
  240. }
  241. func (sw *Switch) IsDialing(addr *NetAddress) bool {
  242. return sw.dialing.Has(addr.IP.String())
  243. }
  244. // Broadcast runs a go routine for each attempted send, which will block
  245. // trying to send for defaultSendTimeoutSeconds. Returns a channel
  246. // which receives success values for each attempted send (false if times out)
  247. func (sw *Switch) Broadcast(chId byte, msg interface{}) chan bool {
  248. successChan := make(chan bool, len(sw.peers.List()))
  249. log.Info("Broadcast", "channel", chId, "msg", msg)
  250. for _, peer := range sw.peers.List() {
  251. go func(peer *Peer) {
  252. success := peer.Send(chId, msg)
  253. successChan <- success
  254. }(peer)
  255. }
  256. return successChan
  257. }
  258. // Returns the count of outbound/inbound and outbound-dialing peers.
  259. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  260. peers := sw.peers.List()
  261. for _, peer := range peers {
  262. if peer.outbound {
  263. outbound++
  264. } else {
  265. inbound++
  266. }
  267. }
  268. dialing = sw.dialing.Size()
  269. return
  270. }
  271. func (sw *Switch) Peers() IPeerSet {
  272. return sw.peers
  273. }
  274. // Disconnect from a peer due to external error.
  275. // TODO: make record depending on reason.
  276. func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) {
  277. log.Notice("Stopping peer for error", "peer", peer, "error", reason)
  278. sw.peers.Remove(peer)
  279. peer.Stop()
  280. sw.removePeerFromReactors(peer, reason)
  281. }
  282. // Disconnect from a peer gracefully.
  283. // TODO: handle graceful disconnects.
  284. func (sw *Switch) StopPeerGracefully(peer *Peer) {
  285. log.Notice("Stopping peer gracefully")
  286. sw.peers.Remove(peer)
  287. peer.Stop()
  288. sw.removePeerFromReactors(peer, nil)
  289. }
  290. func (sw *Switch) addPeerToReactors(peer *Peer) {
  291. for _, reactor := range sw.reactors {
  292. reactor.AddPeer(peer)
  293. }
  294. }
  295. func (sw *Switch) removePeerFromReactors(peer *Peer, reason interface{}) {
  296. for _, reactor := range sw.reactors {
  297. reactor.RemovePeer(peer, reason)
  298. }
  299. }
  300. func (sw *Switch) listenerRoutine(l Listener) {
  301. for {
  302. inConn, ok := <-l.Connections()
  303. if !ok {
  304. break
  305. }
  306. // ignore connection if we already have enough
  307. if maxNumPeers <= sw.peers.Size() {
  308. log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxNumPeers)
  309. continue
  310. }
  311. // Ignore connections from IP ranges for which we have too many
  312. if sw.peers.HasMaxForIPRange(inConn) {
  313. log.Info("Ignoring inbound connection: already have enough peers for that IP range", "address", inConn.RemoteAddr().String())
  314. continue
  315. }
  316. // New inbound connection!
  317. _, err := sw.AddPeerWithConnection(inConn, false)
  318. if err != nil {
  319. log.Notice("Ignoring inbound connection: error on AddPeerWithConnection", "address", inConn.RemoteAddr().String(), "error", err)
  320. continue
  321. }
  322. // NOTE: We don't yet have the listening port of the
  323. // remote (if they have a listener at all).
  324. // The peerHandshake will handle that
  325. }
  326. // cleanup
  327. }
  328. //-----------------------------------------------------------------------------
  329. type SwitchEventNewPeer struct {
  330. Peer *Peer
  331. }
  332. type SwitchEventDonePeer struct {
  333. Peer *Peer
  334. Error interface{}
  335. }