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.

428 lines
12 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. abci "github.com/tendermint/abci/types"
  9. cmn "github.com/tendermint/go-common"
  10. cfg "github.com/tendermint/go-config"
  11. crypto "github.com/tendermint/go-crypto"
  12. dbm "github.com/tendermint/go-db"
  13. p2p "github.com/tendermint/go-p2p"
  14. rpc "github.com/tendermint/go-rpc"
  15. rpcserver "github.com/tendermint/go-rpc/server"
  16. wire "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/state/txindex"
  25. "github.com/tendermint/tendermint/state/txindex/kv"
  26. "github.com/tendermint/tendermint/state/txindex/null"
  27. "github.com/tendermint/tendermint/types"
  28. "github.com/tendermint/tendermint/version"
  29. _ "net/http/pprof"
  30. )
  31. type Node struct {
  32. cmn.BaseService
  33. // config
  34. config cfg.Config // 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 cfg.Config) *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 cfg.Config, 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. sw := p2p.NewSwitch(config.GetConfig("p2p"))
  116. sw.AddReactor("MEMPOOL", mempoolReactor)
  117. sw.AddReactor("BLOCKCHAIN", bcReactor)
  118. sw.AddReactor("CONSENSUS", consensusReactor)
  119. // Optionally, start the pex reactor
  120. var addrBook *p2p.AddrBook
  121. if config.GetBool("pex_reactor") {
  122. addrBook = p2p.NewAddrBook(config.GetString("addrbook_file"), config.GetBool("addrbook_strict"))
  123. pexReactor := p2p.NewPEXReactor(addrBook)
  124. sw.AddReactor("PEX", pexReactor)
  125. }
  126. // Filter peers by addr or pubkey with an ABCI query.
  127. // If the query return code is OK, add peer.
  128. // XXX: Query format subject to change
  129. if config.GetBool("filter_peers") {
  130. // NOTE: addr is ip:port
  131. sw.SetAddrFilter(func(addr net.Addr) error {
  132. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  133. if err != nil {
  134. return err
  135. }
  136. if resQuery.Code.IsOK() {
  137. return nil
  138. }
  139. return errors.New(resQuery.Code.String())
  140. })
  141. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  142. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  143. if err != nil {
  144. return err
  145. }
  146. if resQuery.Code.IsOK() {
  147. return nil
  148. }
  149. return errors.New(resQuery.Code.String())
  150. })
  151. }
  152. // add the event switch to all services
  153. // they should all satisfy events.Eventable
  154. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  155. // run the profile server
  156. profileHost := config.GetString("prof_laddr")
  157. if profileHost != "" {
  158. go func() {
  159. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  160. }()
  161. }
  162. node := &Node{
  163. config: config,
  164. genesisDoc: state.GenesisDoc,
  165. privValidator: privValidator,
  166. privKey: privKey,
  167. sw: sw,
  168. addrBook: addrBook,
  169. evsw: eventSwitch,
  170. blockStore: blockStore,
  171. bcReactor: bcReactor,
  172. mempoolReactor: mempoolReactor,
  173. consensusState: consensusState,
  174. consensusReactor: consensusReactor,
  175. proxyApp: proxyApp,
  176. txIndexer: txIndexer,
  177. }
  178. node.BaseService = *cmn.NewBaseService(log, "Node", node)
  179. return node
  180. }
  181. func (n *Node) OnStart() error {
  182. // Create & add listener
  183. protocol, address := ProtocolAndAddress(n.config.GetString("node_laddr"))
  184. l := p2p.NewDefaultListener(protocol, address, n.config.GetBool("skip_upnp"))
  185. n.sw.AddListener(l)
  186. // Start the switch
  187. n.sw.SetNodeInfo(n.makeNodeInfo())
  188. n.sw.SetNodePrivKey(n.privKey)
  189. _, err := n.sw.Start()
  190. if err != nil {
  191. return err
  192. }
  193. // If seeds exist, add them to the address book and dial out
  194. if n.config.GetString("seeds") != "" {
  195. // dial out
  196. seeds := strings.Split(n.config.GetString("seeds"), ",")
  197. if err := n.DialSeeds(seeds); err != nil {
  198. return err
  199. }
  200. }
  201. // Run the RPC server
  202. if n.config.GetString("rpc_laddr") != "" {
  203. listeners, err := n.startRPC()
  204. if err != nil {
  205. return err
  206. }
  207. n.rpcListeners = listeners
  208. }
  209. return nil
  210. }
  211. func (n *Node) OnStop() {
  212. n.BaseService.OnStop()
  213. log.Notice("Stopping Node")
  214. // TODO: gracefully disconnect from peers.
  215. n.sw.Stop()
  216. for _, l := range n.rpcListeners {
  217. log.Info("Closing rpc listener", "listener", l)
  218. if err := l.Close(); err != nil {
  219. log.Error("Error closing listener", "listener", l, "error", err)
  220. }
  221. }
  222. }
  223. func (n *Node) RunForever() {
  224. // Sleep forever and then...
  225. cmn.TrapSignal(func() {
  226. n.Stop()
  227. })
  228. }
  229. // Add the event switch to reactors, mempool, etc.
  230. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  231. for _, e := range eventables {
  232. e.SetEventSwitch(evsw)
  233. }
  234. }
  235. // Add a Listener to accept inbound peer connections.
  236. // Add listeners before starting the Node.
  237. // The first listener is the primary listener (in NodeInfo)
  238. func (n *Node) AddListener(l p2p.Listener) {
  239. n.sw.AddListener(l)
  240. }
  241. // ConfigureRPC sets all variables in rpccore so they will serve
  242. // rpc calls from this node
  243. func (n *Node) ConfigureRPC() {
  244. rpccore.SetConfig(n.config)
  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. }
  256. func (n *Node) startRPC() ([]net.Listener, error) {
  257. n.ConfigureRPC()
  258. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  259. // we may expose the rpc over both a unix and tcp socket
  260. listeners := make([]net.Listener, len(listenAddrs))
  261. for i, listenAddr := range listenAddrs {
  262. mux := http.NewServeMux()
  263. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  264. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  265. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  266. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  267. if err != nil {
  268. return nil, err
  269. }
  270. listeners[i] = listener
  271. }
  272. // we expose a simplified api over grpc for convenience to app devs
  273. grpcListenAddr := n.config.GetString("grpc_laddr")
  274. if grpcListenAddr != "" {
  275. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  276. if err != nil {
  277. return nil, err
  278. }
  279. listeners = append(listeners, listener)
  280. }
  281. return listeners, nil
  282. }
  283. func (n *Node) Switch() *p2p.Switch {
  284. return n.sw
  285. }
  286. func (n *Node) BlockStore() *bc.BlockStore {
  287. return n.blockStore
  288. }
  289. func (n *Node) ConsensusState() *consensus.ConsensusState {
  290. return n.consensusState
  291. }
  292. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  293. return n.consensusReactor
  294. }
  295. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  296. return n.mempoolReactor
  297. }
  298. func (n *Node) EventSwitch() types.EventSwitch {
  299. return n.evsw
  300. }
  301. // XXX: for convenience
  302. func (n *Node) PrivValidator() *types.PrivValidator {
  303. return n.privValidator
  304. }
  305. func (n *Node) GenesisDoc() *types.GenesisDoc {
  306. return n.genesisDoc
  307. }
  308. func (n *Node) ProxyApp() proxy.AppConns {
  309. return n.proxyApp
  310. }
  311. func (n *Node) makeNodeInfo() *p2p.NodeInfo {
  312. txIndexerStatus := "on"
  313. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  314. txIndexerStatus = "off"
  315. }
  316. nodeInfo := &p2p.NodeInfo{
  317. PubKey: n.privKey.PubKey().(crypto.PubKeyEd25519),
  318. Moniker: n.config.GetString("moniker"),
  319. Network: n.config.GetString("chain_id"),
  320. Version: version.Version,
  321. Other: []string{
  322. cmn.Fmt("wire_version=%v", wire.Version),
  323. cmn.Fmt("p2p_version=%v", p2p.Version),
  324. cmn.Fmt("consensus_version=%v", consensus.Version),
  325. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  326. cmn.Fmt("tx_index=%v", txIndexerStatus),
  327. },
  328. }
  329. // include git hash in the nodeInfo if available
  330. if rev, err := cmn.ReadFile(n.config.GetString("revision_file")); err == nil {
  331. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev)))
  332. }
  333. if !n.sw.IsListening() {
  334. return nodeInfo
  335. }
  336. p2pListener := n.sw.Listeners()[0]
  337. p2pHost := p2pListener.ExternalAddress().IP.String()
  338. p2pPort := p2pListener.ExternalAddress().Port
  339. rpcListenAddr := n.config.GetString("rpc_laddr")
  340. // We assume that the rpcListener has the same ExternalAddress.
  341. // This is probably true because both P2P and RPC listeners use UPnP,
  342. // except of course if the rpc is only bound to localhost
  343. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  344. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  345. return nodeInfo
  346. }
  347. //------------------------------------------------------------------------------
  348. func (n *Node) NodeInfo() *p2p.NodeInfo {
  349. return n.sw.NodeInfo()
  350. }
  351. func (n *Node) DialSeeds(seeds []string) error {
  352. return n.sw.DialSeeds(n.addrBook, seeds)
  353. }
  354. // Defaults to tcp
  355. func ProtocolAndAddress(listenAddr string) (string, string) {
  356. protocol, address := "tcp", listenAddr
  357. parts := strings.SplitN(address, "://", 2)
  358. if len(parts) == 2 {
  359. protocol, address = parts[0], parts[1]
  360. }
  361. return protocol, address
  362. }