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.

446 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
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
  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. consensusLogger := logger.With("module", "consensus")
  68. // Create the proxyApp, which manages connections (consensus, mempool, query)
  69. // and sync tendermint and the app by replaying any necessary blocks
  70. handshaker := consensus.NewHandshaker(state, blockStore)
  71. handshaker.SetLogger(consensusLogger)
  72. proxyApp := proxy.NewAppConns(clientCreator, handshaker)
  73. proxyApp.SetLogger(logger.With("module", "proxy"))
  74. if _, err := proxyApp.Start(); err != nil {
  75. cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err))
  76. }
  77. // reload the state (it may have been updated by the handshake)
  78. state = sm.LoadState(stateDB)
  79. state.SetLogger(logger.With("module", "state"))
  80. // Transaction indexing
  81. var txIndexer txindex.TxIndexer
  82. switch config.TxIndex {
  83. case "kv":
  84. store := dbm.NewDB("tx_index", config.DBBackend, config.DBDir())
  85. txIndexer = kv.NewTxIndex(store)
  86. default:
  87. txIndexer = &null.TxIndex{}
  88. }
  89. state.TxIndexer = txIndexer
  90. // Generate node PrivKey
  91. privKey := crypto.GenPrivKeyEd25519()
  92. // Make event switch
  93. eventSwitch := types.NewEventSwitch()
  94. eventSwitch.SetLogger(logger.With("module", "types"))
  95. _, err := eventSwitch.Start()
  96. if err != nil {
  97. cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
  98. }
  99. // Decide whether to fast-sync or not
  100. // We don't fast-sync when the only validator is us.
  101. fastSync := config.FastSync
  102. if state.Validators.Size() == 1 {
  103. addr, _ := state.Validators.GetByIndex(0)
  104. if bytes.Equal(privValidator.Address, addr) {
  105. fastSync = false
  106. }
  107. }
  108. // Make BlockchainReactor
  109. bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  110. bcReactor.SetLogger(logger.With("module", "blockchain"))
  111. // Make MempoolReactor
  112. mempoolLogger := logger.With("module", "consensus")
  113. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool())
  114. mempool.SetLogger(mempoolLogger)
  115. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  116. mempoolReactor.SetLogger(mempoolLogger)
  117. // Make ConsensusReactor
  118. consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  119. consensusState.SetLogger(consensusLogger)
  120. if privValidator != nil {
  121. consensusState.SetPrivValidator(privValidator)
  122. }
  123. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  124. consensusReactor.SetLogger(consensusLogger)
  125. p2pLogger := logger.With("module", "p2p")
  126. sw := p2p.NewSwitch(config.P2P)
  127. sw.SetLogger(p2pLogger)
  128. sw.AddReactor("MEMPOOL", mempoolReactor)
  129. sw.AddReactor("BLOCKCHAIN", bcReactor)
  130. sw.AddReactor("CONSENSUS", consensusReactor)
  131. // Optionally, start the pex reactor
  132. var addrBook *p2p.AddrBook
  133. if config.P2P.PexReactor {
  134. addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  135. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  136. pexReactor := p2p.NewPEXReactor(addrBook)
  137. pexReactor.SetLogger(p2pLogger)
  138. sw.AddReactor("PEX", pexReactor)
  139. }
  140. // Filter peers by addr or pubkey with an ABCI query.
  141. // If the query return code is OK, add peer.
  142. // XXX: Query format subject to change
  143. if config.FilterPeers {
  144. // NOTE: addr is ip:port
  145. sw.SetAddrFilter(func(addr net.Addr) error {
  146. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  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. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  156. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  157. if err != nil {
  158. return err
  159. }
  160. if resQuery.Code.IsOK() {
  161. return nil
  162. }
  163. return errors.New(resQuery.Code.String())
  164. })
  165. }
  166. // add the event switch to all services
  167. // they should all satisfy events.Eventable
  168. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  169. // run the profile server
  170. profileHost := config.ProfListenAddress
  171. if profileHost != "" {
  172. go func() {
  173. logger.Error("Profile server", "error", http.ListenAndServe(profileHost, nil))
  174. }()
  175. }
  176. node := &Node{
  177. config: config,
  178. genesisDoc: state.GenesisDoc,
  179. privValidator: privValidator,
  180. privKey: privKey,
  181. sw: sw,
  182. addrBook: addrBook,
  183. evsw: eventSwitch,
  184. blockStore: blockStore,
  185. bcReactor: bcReactor,
  186. mempoolReactor: mempoolReactor,
  187. consensusState: consensusState,
  188. consensusReactor: consensusReactor,
  189. proxyApp: proxyApp,
  190. txIndexer: txIndexer,
  191. }
  192. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  193. return node
  194. }
  195. func (n *Node) OnStart() error {
  196. // Create & add listener
  197. protocol, address := ProtocolAndAddress(n.config.P2P.ListenAddress)
  198. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  199. n.sw.AddListener(l)
  200. // Start the switch
  201. n.sw.SetNodeInfo(n.makeNodeInfo())
  202. n.sw.SetNodePrivKey(n.privKey)
  203. _, err := n.sw.Start()
  204. if err != nil {
  205. return err
  206. }
  207. // If seeds exist, add them to the address book and dial out
  208. if n.config.P2P.Seeds != "" {
  209. // dial out
  210. seeds := strings.Split(n.config.P2P.Seeds, ",")
  211. if err := n.DialSeeds(seeds); err != nil {
  212. return err
  213. }
  214. }
  215. // Run the RPC server
  216. if n.config.RPCListenAddress != "" {
  217. listeners, err := n.startRPC()
  218. if err != nil {
  219. return err
  220. }
  221. n.rpcListeners = listeners
  222. }
  223. return nil
  224. }
  225. func (n *Node) OnStop() {
  226. n.BaseService.OnStop()
  227. n.Logger.Info("Stopping Node")
  228. // TODO: gracefully disconnect from peers.
  229. n.sw.Stop()
  230. for _, l := range n.rpcListeners {
  231. n.Logger.Info("Closing rpc listener", "listener", l)
  232. if err := l.Close(); err != nil {
  233. n.Logger.Error("Error closing listener", "listener", l, "error", err)
  234. }
  235. }
  236. }
  237. func (n *Node) RunForever() {
  238. // Sleep forever and then...
  239. cmn.TrapSignal(func() {
  240. n.Stop()
  241. })
  242. }
  243. // Add the event switch to reactors, mempool, etc.
  244. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  245. for _, e := range eventables {
  246. e.SetEventSwitch(evsw)
  247. }
  248. }
  249. // Add a Listener to accept inbound peer connections.
  250. // Add listeners before starting the Node.
  251. // The first listener is the primary listener (in NodeInfo)
  252. func (n *Node) AddListener(l p2p.Listener) {
  253. n.sw.AddListener(l)
  254. }
  255. // ConfigureRPC sets all variables in rpccore so they will serve
  256. // rpc calls from this node
  257. func (n *Node) ConfigureRPC() {
  258. rpccore.SetEventSwitch(n.evsw)
  259. rpccore.SetBlockStore(n.blockStore)
  260. rpccore.SetConsensusState(n.consensusState)
  261. rpccore.SetMempool(n.mempoolReactor.Mempool)
  262. rpccore.SetSwitch(n.sw)
  263. rpccore.SetPubKey(n.privValidator.PubKey)
  264. rpccore.SetGenesisDoc(n.genesisDoc)
  265. rpccore.SetAddrBook(n.addrBook)
  266. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  267. rpccore.SetTxIndexer(n.txIndexer)
  268. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  269. }
  270. func (n *Node) startRPC() ([]net.Listener, error) {
  271. n.ConfigureRPC()
  272. listenAddrs := strings.Split(n.config.RPCListenAddress, ",")
  273. // we may expose the rpc over both a unix and tcp socket
  274. listeners := make([]net.Listener, len(listenAddrs))
  275. for i, listenAddr := range listenAddrs {
  276. mux := http.NewServeMux()
  277. rpcLogger := n.Logger.With("module", "rpcserver")
  278. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  279. wm.SetLogger(rpcLogger)
  280. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  281. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  282. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  283. if err != nil {
  284. return nil, err
  285. }
  286. listeners[i] = listener
  287. }
  288. // we expose a simplified api over grpc for convenience to app devs
  289. grpcListenAddr := n.config.GRPCListenAddress
  290. if grpcListenAddr != "" {
  291. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  292. if err != nil {
  293. return nil, err
  294. }
  295. listeners = append(listeners, listener)
  296. }
  297. return listeners, nil
  298. }
  299. func (n *Node) Switch() *p2p.Switch {
  300. return n.sw
  301. }
  302. func (n *Node) BlockStore() *bc.BlockStore {
  303. return n.blockStore
  304. }
  305. func (n *Node) ConsensusState() *consensus.ConsensusState {
  306. return n.consensusState
  307. }
  308. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  309. return n.consensusReactor
  310. }
  311. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  312. return n.mempoolReactor
  313. }
  314. func (n *Node) EventSwitch() types.EventSwitch {
  315. return n.evsw
  316. }
  317. // XXX: for convenience
  318. func (n *Node) PrivValidator() *types.PrivValidator {
  319. return n.privValidator
  320. }
  321. func (n *Node) GenesisDoc() *types.GenesisDoc {
  322. return n.genesisDoc
  323. }
  324. func (n *Node) ProxyApp() proxy.AppConns {
  325. return n.proxyApp
  326. }
  327. func (n *Node) makeNodeInfo() *p2p.NodeInfo {
  328. txIndexerStatus := "on"
  329. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  330. txIndexerStatus = "off"
  331. }
  332. nodeInfo := &p2p.NodeInfo{
  333. PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  334. Moniker: n.config.Moniker,
  335. Network: n.consensusState.GetState().ChainID,
  336. Version: version.Version,
  337. Other: []string{
  338. cmn.Fmt("wire_version=%v", wire.Version),
  339. cmn.Fmt("p2p_version=%v", p2p.Version),
  340. cmn.Fmt("consensus_version=%v", consensus.Version),
  341. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  342. cmn.Fmt("tx_index=%v", txIndexerStatus),
  343. },
  344. }
  345. // include git hash in the nodeInfo if available
  346. // TODO: use ld-flags
  347. /*if rev, err := cmn.ReadFile(n.config.GetString("revision_file")); err == nil {
  348. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev)))
  349. }*/
  350. if !n.sw.IsListening() {
  351. return nodeInfo
  352. }
  353. p2pListener := n.sw.Listeners()[0]
  354. p2pHost := p2pListener.ExternalAddress().IP.String()
  355. p2pPort := p2pListener.ExternalAddress().Port
  356. rpcListenAddr := n.config.RPCListenAddress
  357. // We assume that the rpcListener has the same ExternalAddress.
  358. // This is probably true because both P2P and RPC listeners use UPnP,
  359. // except of course if the rpc is only bound to localhost
  360. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  361. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  362. return nodeInfo
  363. }
  364. //------------------------------------------------------------------------------
  365. func (n *Node) NodeInfo() *p2p.NodeInfo {
  366. return n.sw.NodeInfo()
  367. }
  368. func (n *Node) DialSeeds(seeds []string) error {
  369. return n.sw.DialSeeds(n.addrBook, seeds)
  370. }
  371. // Defaults to tcp
  372. func ProtocolAndAddress(listenAddr string) (string, string) {
  373. protocol, address := "tcp", listenAddr
  374. parts := strings.SplitN(address, "://", 2)
  375. if len(parts) == 2 {
  376. protocol, address = parts[0], parts[1]
  377. }
  378. return protocol, address
  379. }
  380. //------------------------------------------------------------------------------