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.

425 lines
12 KiB

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