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.

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