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.

431 lines
13 KiB

10 years ago
8 years ago
10 years ago
11 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 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. crypto "github.com/tendermint/go-crypto"
  10. wire "github.com/tendermint/go-wire"
  11. bc "github.com/tendermint/tendermint/blockchain"
  12. cfg "github.com/tendermint/tendermint/config"
  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. rpccore "github.com/tendermint/tendermint/rpc/core"
  18. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  19. rpc "github.com/tendermint/tendermint/rpc/lib"
  20. rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
  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. "github.com/tendermint/tmlibs/log"
  30. _ "net/http/pprof"
  31. )
  32. type Node struct {
  33. cmn.BaseService
  34. // config
  35. config *cfg.Config
  36. genesisDoc *types.GenesisDoc // initial validator set
  37. privValidator *types.PrivValidator // local node's validator key
  38. // network
  39. privKey crypto.PrivKeyEd25519 // local node's p2p key
  40. sw *p2p.Switch // p2p connections
  41. addrBook *p2p.AddrBook // known peers
  42. // services
  43. evsw types.EventSwitch // pub/sub for services
  44. blockStore *bc.BlockStore // store the blockchain to disk
  45. bcReactor *bc.BlockchainReactor // for fast-syncing
  46. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  47. consensusState *consensus.ConsensusState // latest consensus state
  48. consensusReactor *consensus.ConsensusReactor // for participating in the consensus
  49. proxyApp proxy.AppConns // connection to the application
  50. rpcListeners []net.Listener // rpc servers
  51. txIndexer txindex.TxIndexer
  52. }
  53. func NewNodeDefault(config *cfg.Config, logger log.Logger) *Node {
  54. // Get PrivValidator
  55. privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile(), logger)
  56. return NewNode(config, privValidator,
  57. proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()), logger)
  58. }
  59. func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator, logger log.Logger) *Node {
  60. // Get BlockStore
  61. blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir())
  62. blockStore := bc.NewBlockStore(blockStoreDB)
  63. // Get State
  64. stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir())
  65. state := sm.GetState(stateDB, config.GenesisFile())
  66. state.SetLogger(logger.With("module", "state"))
  67. // Create the proxyApp, which manages connections (consensus, mempool, query)
  68. // and sync tendermint and the app by replaying any necessary blocks
  69. proxyApp := proxy.NewAppConns(clientCreator, consensus.NewHandshaker(state, blockStore))
  70. if _, err := proxyApp.Start(); err != nil {
  71. cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err))
  72. }
  73. // reload the state (it may have been updated by the handshake)
  74. state = sm.LoadState(stateDB)
  75. state.SetLogger(logger.With("module", "state"))
  76. // Transaction indexing
  77. var txIndexer txindex.TxIndexer
  78. switch config.TxIndex {
  79. case "kv":
  80. store := dbm.NewDB("tx_index", config.DBBackend, config.DBDir())
  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.FastSync
  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(state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  105. // Make MempoolReactor
  106. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool())
  107. mempool.SetLogger(logger.With("module", "mempool"))
  108. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  109. // Make ConsensusReactor
  110. consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  111. consensusState.SetLogger(logger.With("module", "consensus"))
  112. if privValidator != nil {
  113. consensusState.SetPrivValidator(privValidator)
  114. }
  115. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  116. sw := p2p.NewSwitch(config.P2P)
  117. sw.AddReactor("MEMPOOL", mempoolReactor)
  118. sw.AddReactor("BLOCKCHAIN", bcReactor)
  119. sw.AddReactor("CONSENSUS", consensusReactor)
  120. // Optionally, start the pex reactor
  121. var addrBook *p2p.AddrBook
  122. if config.P2P.PexReactor {
  123. addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  124. pexReactor := p2p.NewPEXReactor(addrBook)
  125. sw.AddReactor("PEX", pexReactor)
  126. }
  127. // Filter peers by addr or pubkey with an ABCI query.
  128. // If the query return code is OK, add peer.
  129. // XXX: Query format subject to change
  130. if config.FilterPeers {
  131. // NOTE: addr is ip:port
  132. sw.SetAddrFilter(func(addr net.Addr) error {
  133. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  134. if err != nil {
  135. return err
  136. }
  137. if resQuery.Code.IsOK() {
  138. return nil
  139. }
  140. return errors.New(resQuery.Code.String())
  141. })
  142. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  143. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  144. if err != nil {
  145. return err
  146. }
  147. if resQuery.Code.IsOK() {
  148. return nil
  149. }
  150. return errors.New(resQuery.Code.String())
  151. })
  152. }
  153. // add the event switch to all services
  154. // they should all satisfy events.Eventable
  155. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  156. // run the profile server
  157. profileHost := config.ProfListenAddress
  158. if profileHost != "" {
  159. go func() {
  160. logger.Error("Profile server", "error", http.ListenAndServe(profileHost, nil))
  161. }()
  162. }
  163. node := &Node{
  164. config: config,
  165. genesisDoc: state.GenesisDoc,
  166. privValidator: privValidator,
  167. privKey: privKey,
  168. sw: sw,
  169. addrBook: addrBook,
  170. evsw: eventSwitch,
  171. blockStore: blockStore,
  172. bcReactor: bcReactor,
  173. mempoolReactor: mempoolReactor,
  174. consensusState: consensusState,
  175. consensusReactor: consensusReactor,
  176. proxyApp: proxyApp,
  177. txIndexer: txIndexer,
  178. }
  179. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  180. return node
  181. }
  182. func (n *Node) OnStart() error {
  183. // Create & add listener
  184. protocol, address := ProtocolAndAddress(n.config.P2P.ListenAddress)
  185. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  186. n.sw.AddListener(l)
  187. // Start the switch
  188. n.sw.SetNodeInfo(n.makeNodeInfo())
  189. n.sw.SetNodePrivKey(n.privKey)
  190. _, err := n.sw.Start()
  191. if err != nil {
  192. return err
  193. }
  194. // If seeds exist, add them to the address book and dial out
  195. if n.config.P2P.Seeds != "" {
  196. // dial out
  197. seeds := strings.Split(n.config.P2P.Seeds, ",")
  198. if err := n.DialSeeds(seeds); err != nil {
  199. return err
  200. }
  201. }
  202. // Run the RPC server
  203. if n.config.RPCListenAddress != "" {
  204. listeners, err := n.startRPC()
  205. if err != nil {
  206. return err
  207. }
  208. n.rpcListeners = listeners
  209. }
  210. return nil
  211. }
  212. func (n *Node) OnStop() {
  213. n.BaseService.OnStop()
  214. n.Logger.Info("Stopping Node")
  215. // TODO: gracefully disconnect from peers.
  216. n.sw.Stop()
  217. for _, l := range n.rpcListeners {
  218. n.Logger.Info("Closing rpc listener", "listener", l)
  219. if err := l.Close(); err != nil {
  220. n.Logger.Error("Error closing listener", "listener", l, "error", err)
  221. }
  222. }
  223. }
  224. func (n *Node) RunForever() {
  225. // Sleep forever and then...
  226. cmn.TrapSignal(func() {
  227. n.Stop()
  228. })
  229. }
  230. // Add the event switch to reactors, mempool, etc.
  231. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  232. for _, e := range eventables {
  233. e.SetEventSwitch(evsw)
  234. }
  235. }
  236. // Add a Listener to accept inbound peer connections.
  237. // Add listeners before starting the Node.
  238. // The first listener is the primary listener (in NodeInfo)
  239. func (n *Node) AddListener(l p2p.Listener) {
  240. n.sw.AddListener(l)
  241. }
  242. // ConfigureRPC sets all variables in rpccore so they will serve
  243. // rpc calls from this node
  244. func (n *Node) ConfigureRPC() {
  245. rpccore.SetEventSwitch(n.evsw)
  246. rpccore.SetBlockStore(n.blockStore)
  247. rpccore.SetConsensusState(n.consensusState)
  248. rpccore.SetMempool(n.mempoolReactor.Mempool)
  249. rpccore.SetSwitch(n.sw)
  250. rpccore.SetPubKey(n.privValidator.PubKey)
  251. rpccore.SetGenesisDoc(n.genesisDoc)
  252. rpccore.SetAddrBook(n.addrBook)
  253. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  254. rpccore.SetTxIndexer(n.txIndexer)
  255. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  256. }
  257. func (n *Node) startRPC() ([]net.Listener, error) {
  258. n.ConfigureRPC()
  259. listenAddrs := strings.Split(n.config.RPCListenAddress, ",")
  260. // we may expose the rpc over both a unix and tcp socket
  261. listeners := make([]net.Listener, len(listenAddrs))
  262. for i, listenAddr := range listenAddrs {
  263. mux := http.NewServeMux()
  264. rpcLogger := n.Logger.With("module", "rpcserver")
  265. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  266. wm.SetLogger(rpcLogger)
  267. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  268. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  269. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  270. if err != nil {
  271. return nil, err
  272. }
  273. listeners[i] = listener
  274. }
  275. // we expose a simplified api over grpc for convenience to app devs
  276. grpcListenAddr := n.config.GRPCListenAddress
  277. if grpcListenAddr != "" {
  278. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  279. if err != nil {
  280. return nil, err
  281. }
  282. listeners = append(listeners, listener)
  283. }
  284. return listeners, nil
  285. }
  286. func (n *Node) Switch() *p2p.Switch {
  287. return n.sw
  288. }
  289. func (n *Node) BlockStore() *bc.BlockStore {
  290. return n.blockStore
  291. }
  292. func (n *Node) ConsensusState() *consensus.ConsensusState {
  293. return n.consensusState
  294. }
  295. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  296. return n.consensusReactor
  297. }
  298. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  299. return n.mempoolReactor
  300. }
  301. func (n *Node) EventSwitch() types.EventSwitch {
  302. return n.evsw
  303. }
  304. // XXX: for convenience
  305. func (n *Node) PrivValidator() *types.PrivValidator {
  306. return n.privValidator
  307. }
  308. func (n *Node) GenesisDoc() *types.GenesisDoc {
  309. return n.genesisDoc
  310. }
  311. func (n *Node) ProxyApp() proxy.AppConns {
  312. return n.proxyApp
  313. }
  314. func (n *Node) makeNodeInfo() *p2p.NodeInfo {
  315. txIndexerStatus := "on"
  316. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  317. txIndexerStatus = "off"
  318. }
  319. nodeInfo := &p2p.NodeInfo{
  320. PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  321. Moniker: n.config.Moniker,
  322. Network: n.consensusState.GetState().ChainID,
  323. Version: version.Version,
  324. Other: []string{
  325. cmn.Fmt("wire_version=%v", wire.Version),
  326. cmn.Fmt("p2p_version=%v", p2p.Version),
  327. cmn.Fmt("consensus_version=%v", consensus.Version),
  328. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  329. cmn.Fmt("tx_index=%v", txIndexerStatus),
  330. },
  331. }
  332. // include git hash in the nodeInfo if available
  333. // TODO: use ld-flags
  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.RPCListenAddress
  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. }
  367. //------------------------------------------------------------------------------