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.

384 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. }
  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, consensus.NewHandshaker(config, state, blockStore))
  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. // ConfigureRPC sets all variables in rpccore so they will serve
  213. // rpc calls from this node
  214. func (n *Node) ConfigureRPC() {
  215. rpccore.SetConfig(n.config)
  216. rpccore.SetEventSwitch(n.evsw)
  217. rpccore.SetBlockStore(n.blockStore)
  218. rpccore.SetConsensusState(n.consensusState)
  219. rpccore.SetMempool(n.mempoolReactor.Mempool)
  220. rpccore.SetSwitch(n.sw)
  221. rpccore.SetPubKey(n.privValidator.PubKey)
  222. rpccore.SetGenesisDoc(n.genesisDoc)
  223. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  224. }
  225. func (n *Node) startRPC() ([]net.Listener, error) {
  226. n.ConfigureRPC()
  227. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  228. // we may expose the rpc over both a unix and tcp socket
  229. listeners := make([]net.Listener, len(listenAddrs))
  230. for i, listenAddr := range listenAddrs {
  231. mux := http.NewServeMux()
  232. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  233. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  234. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  235. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  236. if err != nil {
  237. return nil, err
  238. }
  239. listeners[i] = listener
  240. }
  241. // we expose a simplified api over grpc for convenience to app devs
  242. grpcListenAddr := n.config.GetString("grpc_laddr")
  243. if grpcListenAddr != "" {
  244. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  245. if err != nil {
  246. return nil, err
  247. }
  248. listeners = append(listeners, listener)
  249. }
  250. return listeners, nil
  251. }
  252. func (n *Node) Switch() *p2p.Switch {
  253. return n.sw
  254. }
  255. func (n *Node) BlockStore() *bc.BlockStore {
  256. return n.blockStore
  257. }
  258. func (n *Node) ConsensusState() *consensus.ConsensusState {
  259. return n.consensusState
  260. }
  261. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  262. return n.consensusReactor
  263. }
  264. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  265. return n.mempoolReactor
  266. }
  267. func (n *Node) EventSwitch() types.EventSwitch {
  268. return n.evsw
  269. }
  270. // XXX: for convenience
  271. func (n *Node) PrivValidator() *types.PrivValidator {
  272. return n.privValidator
  273. }
  274. func (n *Node) GenesisDoc() *types.GenesisDoc {
  275. return n.genesisDoc
  276. }
  277. func (n *Node) ProxyApp() proxy.AppConns {
  278. return n.proxyApp
  279. }
  280. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  281. nodeInfo := &p2p.NodeInfo{
  282. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  283. Moniker: config.GetString("moniker"),
  284. Network: config.GetString("chain_id"),
  285. Version: version.Version,
  286. Other: []string{
  287. cmn.Fmt("wire_version=%v", wire.Version),
  288. cmn.Fmt("p2p_version=%v", p2p.Version),
  289. cmn.Fmt("consensus_version=%v", consensus.Version),
  290. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  291. },
  292. }
  293. // include git hash in the nodeInfo if available
  294. if rev, err := cmn.ReadFile(config.GetString("revision_file")); err == nil {
  295. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev)))
  296. }
  297. if !sw.IsListening() {
  298. return nodeInfo
  299. }
  300. p2pListener := sw.Listeners()[0]
  301. p2pHost := p2pListener.ExternalAddress().IP.String()
  302. p2pPort := p2pListener.ExternalAddress().Port
  303. rpcListenAddr := config.GetString("rpc_laddr")
  304. // We assume that the rpcListener has the same ExternalAddress.
  305. // This is probably true because both P2P and RPC listeners use UPnP,
  306. // except of course if the rpc is only bound to localhost
  307. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  308. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  309. return nodeInfo
  310. }
  311. func (n *Node) NodeInfo() *p2p.NodeInfo {
  312. return n.sw.NodeInfo()
  313. }
  314. func (n *Node) DialSeeds(seeds []string) {
  315. n.sw.DialSeeds(seeds)
  316. }
  317. // Defaults to tcp
  318. func ProtocolAndAddress(listenAddr string) (string, string) {
  319. protocol, address := "tcp", listenAddr
  320. parts := strings.SplitN(address, "://", 2)
  321. if len(parts) == 2 {
  322. protocol, address = parts[0], parts[1]
  323. }
  324. return protocol, address
  325. }