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.

393 lines
11 KiB

10 years ago
10 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
10 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "errors"
  5. "net"
  6. "net/http"
  7. "strings"
  8. abci "github.com/tendermint/abci/types"
  9. cmn "github.com/tendermint/go-common"
  10. cfg "github.com/tendermint/go-config"
  11. "github.com/tendermint/go-crypto"
  12. dbm "github.com/tendermint/go-db"
  13. "github.com/tendermint/go-p2p"
  14. "github.com/tendermint/go-rpc"
  15. "github.com/tendermint/go-rpc/server"
  16. "github.com/tendermint/go-wire"
  17. bc "github.com/tendermint/tendermint/blockchain"
  18. "github.com/tendermint/tendermint/consensus"
  19. mempl "github.com/tendermint/tendermint/mempool"
  20. "github.com/tendermint/tendermint/proxy"
  21. rpccore "github.com/tendermint/tendermint/rpc/core"
  22. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  23. sm "github.com/tendermint/tendermint/state"
  24. "github.com/tendermint/tendermint/types"
  25. "github.com/tendermint/tendermint/version"
  26. _ "net/http/pprof"
  27. )
  28. type Node struct {
  29. cmn.BaseService
  30. config cfg.Config
  31. sw *p2p.Switch
  32. evsw types.EventSwitch
  33. blockStore *bc.BlockStore
  34. bcReactor *bc.BlockchainReactor
  35. mempoolReactor *mempl.MempoolReactor
  36. consensusState *consensus.ConsensusState
  37. consensusReactor *consensus.ConsensusReactor
  38. privValidator *types.PrivValidator
  39. genesisDoc *types.GenesisDoc
  40. privKey crypto.PrivKeyEd25519
  41. proxyApp proxy.AppConns
  42. rpcListeners []net.Listener
  43. }
  44. func NewNodeDefault(config cfg.Config) *Node {
  45. // Get PrivValidator
  46. privValidatorFile := config.GetString("priv_validator_file")
  47. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  48. return NewNode(config, privValidator, proxy.DefaultClientCreator(config))
  49. }
  50. func NewNode(config cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node {
  51. // Get BlockStore
  52. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  53. blockStore := bc.NewBlockStore(blockStoreDB)
  54. // Get State
  55. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  56. state := sm.GetState(config, stateDB)
  57. // add the chainid and number of validators to the global config
  58. config.Set("chain_id", state.ChainID)
  59. config.Set("num_vals", state.Validators.Size())
  60. // Create the proxyApp, which manages connections (consensus, mempool, query)
  61. // and sync tendermint and the app by replaying any necessary blocks
  62. proxyApp := proxy.NewAppConns(config, clientCreator, consensus.NewHandshaker(config, state, blockStore))
  63. if _, err := proxyApp.Start(); err != nil {
  64. cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err))
  65. }
  66. // reload the state (it may have been updated by the handshake)
  67. state = sm.LoadState(stateDB)
  68. // Generate node PrivKey
  69. privKey := crypto.GenPrivKeyEd25519()
  70. // Make event switch
  71. eventSwitch := types.NewEventSwitch()
  72. _, err := eventSwitch.Start()
  73. if err != nil {
  74. cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
  75. }
  76. // Decide whether to fast-sync or not
  77. // We don't fast-sync when the only validator is us.
  78. fastSync := config.GetBool("fast_sync")
  79. if state.Validators.Size() == 1 {
  80. addr, _ := state.Validators.GetByIndex(0)
  81. if bytes.Equal(privValidator.Address, addr) {
  82. fastSync = false
  83. }
  84. }
  85. // Make BlockchainReactor
  86. bcReactor := bc.NewBlockchainReactor(config, state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  87. // Make MempoolReactor
  88. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  89. mempoolReactor := mempl.NewMempoolReactor(config, mempool)
  90. // Make ConsensusReactor
  91. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  92. if privValidator != nil {
  93. consensusState.SetPrivValidator(privValidator)
  94. }
  95. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  96. // Make p2p network switch
  97. sw := p2p.NewSwitch(config.GetConfig("p2p"))
  98. sw.AddReactor("MEMPOOL", mempoolReactor)
  99. sw.AddReactor("BLOCKCHAIN", bcReactor)
  100. sw.AddReactor("CONSENSUS", consensusReactor)
  101. // Optionally, start the pex reactor
  102. // TODO: this is a dev feature, it needs some love
  103. if config.GetBool("pex_reactor") {
  104. addrBook := p2p.NewAddrBook(config.GetString("addrbook_file"), config.GetBool("addrbook_strict"))
  105. addrBook.Start()
  106. pexReactor := p2p.NewPEXReactor(addrBook)
  107. sw.AddReactor("PEX", pexReactor)
  108. }
  109. // Filter peers by addr or pubkey with an ABCI query.
  110. // If the query return code is OK, add peer.
  111. // XXX: Query format subject to change
  112. if config.GetBool("filter_peers") {
  113. // NOTE: addr is ip:port
  114. sw.SetAddrFilter(func(addr net.Addr) error {
  115. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  116. if err != nil {
  117. return err
  118. }
  119. if resQuery.Code.IsOK() {
  120. return nil
  121. }
  122. return errors.New(resQuery.Code.String())
  123. })
  124. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  125. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  126. if err != nil {
  127. return err
  128. }
  129. if resQuery.Code.IsOK() {
  130. return nil
  131. }
  132. return errors.New(resQuery.Code.String())
  133. })
  134. }
  135. // add the event switch to all services
  136. // they should all satisfy events.Eventable
  137. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  138. // run the profile server
  139. profileHost := config.GetString("prof_laddr")
  140. if profileHost != "" {
  141. go func() {
  142. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  143. }()
  144. }
  145. node := &Node{
  146. config: config,
  147. sw: sw,
  148. evsw: eventSwitch,
  149. blockStore: blockStore,
  150. bcReactor: bcReactor,
  151. mempoolReactor: mempoolReactor,
  152. consensusState: consensusState,
  153. consensusReactor: consensusReactor,
  154. privValidator: privValidator,
  155. genesisDoc: state.GenesisDoc,
  156. privKey: privKey,
  157. proxyApp: proxyApp,
  158. }
  159. node.BaseService = *cmn.NewBaseService(log, "Node", node)
  160. return node
  161. }
  162. func (n *Node) OnStart() error {
  163. n.BaseService.OnStart()
  164. // Create & add listener
  165. protocol, address := ProtocolAndAddress(n.config.GetString("node_laddr"))
  166. l := p2p.NewDefaultListener(protocol, address, n.config.GetBool("skip_upnp"))
  167. n.sw.AddListener(l)
  168. // Start the switch
  169. n.sw.SetNodeInfo(makeNodeInfo(n.config, n.sw, n.privKey))
  170. n.sw.SetNodePrivKey(n.privKey)
  171. _, err := n.sw.Start()
  172. if err != nil {
  173. return err
  174. }
  175. // Dial out of seed nodes exist
  176. if n.config.GetString("seeds") != "" {
  177. seeds := strings.Split(n.config.GetString("seeds"), ",")
  178. n.sw.DialSeeds(seeds)
  179. }
  180. // Run the RPC server
  181. if n.config.GetString("rpc_laddr") != "" {
  182. listeners, err := n.startRPC()
  183. if err != nil {
  184. return err
  185. }
  186. n.rpcListeners = listeners
  187. }
  188. return nil
  189. }
  190. func (n *Node) RunForever() {
  191. // Sleep forever and then...
  192. cmn.TrapSignal(func() {
  193. n.Stop()
  194. })
  195. }
  196. func (n *Node) OnStop() {
  197. n.BaseService.OnStop()
  198. log.Notice("Stopping Node")
  199. // TODO: gracefully disconnect from peers.
  200. n.sw.Stop()
  201. for _, l := range n.rpcListeners {
  202. log.Info("Closing rpc listener", "listener", l)
  203. if err := l.Close(); err != nil {
  204. log.Error("Error closing listener", "listener", l, "error", err)
  205. }
  206. }
  207. }
  208. // Add the event switch to reactors, mempool, etc.
  209. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  210. for _, e := range eventables {
  211. e.SetEventSwitch(evsw)
  212. }
  213. }
  214. // Add a Listener to accept inbound peer connections.
  215. // Add listeners before starting the Node.
  216. // The first listener is the primary listener (in NodeInfo)
  217. func (n *Node) AddListener(l p2p.Listener) {
  218. n.sw.AddListener(l)
  219. }
  220. // ConfigureRPC sets all variables in rpccore so they will serve
  221. // rpc calls from this node
  222. func (n *Node) ConfigureRPC() {
  223. rpccore.SetConfig(n.config)
  224. rpccore.SetEventSwitch(n.evsw)
  225. rpccore.SetBlockStore(n.blockStore)
  226. rpccore.SetConsensusState(n.consensusState)
  227. rpccore.SetMempool(n.mempoolReactor.Mempool)
  228. rpccore.SetSwitch(n.sw)
  229. rpccore.SetPubKey(n.privValidator.PubKey)
  230. rpccore.SetGenesisDoc(n.genesisDoc)
  231. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  232. }
  233. func (n *Node) startRPC() ([]net.Listener, error) {
  234. n.ConfigureRPC()
  235. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  236. // we may expose the rpc over both a unix and tcp socket
  237. listeners := make([]net.Listener, len(listenAddrs))
  238. for i, listenAddr := range listenAddrs {
  239. mux := http.NewServeMux()
  240. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  241. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  242. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  243. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  244. if err != nil {
  245. return nil, err
  246. }
  247. listeners[i] = listener
  248. }
  249. // we expose a simplified api over grpc for convenience to app devs
  250. grpcListenAddr := n.config.GetString("grpc_laddr")
  251. if grpcListenAddr != "" {
  252. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  253. if err != nil {
  254. return nil, err
  255. }
  256. listeners = append(listeners, listener)
  257. }
  258. return listeners, nil
  259. }
  260. func (n *Node) Switch() *p2p.Switch {
  261. return n.sw
  262. }
  263. func (n *Node) BlockStore() *bc.BlockStore {
  264. return n.blockStore
  265. }
  266. func (n *Node) ConsensusState() *consensus.ConsensusState {
  267. return n.consensusState
  268. }
  269. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  270. return n.consensusReactor
  271. }
  272. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  273. return n.mempoolReactor
  274. }
  275. func (n *Node) EventSwitch() types.EventSwitch {
  276. return n.evsw
  277. }
  278. // XXX: for convenience
  279. func (n *Node) PrivValidator() *types.PrivValidator {
  280. return n.privValidator
  281. }
  282. func (n *Node) GenesisDoc() *types.GenesisDoc {
  283. return n.genesisDoc
  284. }
  285. func (n *Node) ProxyApp() proxy.AppConns {
  286. return n.proxyApp
  287. }
  288. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  289. nodeInfo := &p2p.NodeInfo{
  290. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  291. Moniker: config.GetString("moniker"),
  292. Network: config.GetString("chain_id"),
  293. Version: version.Version,
  294. Other: []string{
  295. cmn.Fmt("wire_version=%v", wire.Version),
  296. cmn.Fmt("p2p_version=%v", p2p.Version),
  297. cmn.Fmt("consensus_version=%v", consensus.Version),
  298. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  299. },
  300. }
  301. // include git hash in the nodeInfo if available
  302. if rev, err := cmn.ReadFile(config.GetString("revision_file")); err == nil {
  303. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev)))
  304. }
  305. if !sw.IsListening() {
  306. return nodeInfo
  307. }
  308. p2pListener := sw.Listeners()[0]
  309. p2pHost := p2pListener.ExternalAddress().IP.String()
  310. p2pPort := p2pListener.ExternalAddress().Port
  311. rpcListenAddr := config.GetString("rpc_laddr")
  312. // We assume that the rpcListener has the same ExternalAddress.
  313. // This is probably true because both P2P and RPC listeners use UPnP,
  314. // except of course if the rpc is only bound to localhost
  315. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  316. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  317. return nodeInfo
  318. }
  319. func (n *Node) NodeInfo() *p2p.NodeInfo {
  320. return n.sw.NodeInfo()
  321. }
  322. func (n *Node) DialSeeds(seeds []string) {
  323. n.sw.DialSeeds(seeds)
  324. }
  325. // Defaults to tcp
  326. func ProtocolAndAddress(listenAddr string) (string, string) {
  327. protocol, address := "tcp", listenAddr
  328. parts := strings.SplitN(address, "://", 2)
  329. if len(parts) == 2 {
  330. protocol, address = parts[0], parts[1]
  331. }
  332. return protocol, address
  333. }