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.

433 lines
13 KiB

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