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.

407 lines
12 KiB

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