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.

740 lines
22 KiB

  1. package node
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "github.com/prometheus/client_golang/prometheus/promhttp"
  10. abci "github.com/tendermint/tendermint/abci/types"
  11. amino "github.com/tendermint/go-amino"
  12. cmn "github.com/tendermint/tmlibs/common"
  13. dbm "github.com/tendermint/tmlibs/db"
  14. "github.com/tendermint/tmlibs/log"
  15. bc "github.com/tendermint/tendermint/blockchain"
  16. cfg "github.com/tendermint/tendermint/config"
  17. cs "github.com/tendermint/tendermint/consensus"
  18. "github.com/tendermint/tendermint/crypto"
  19. "github.com/tendermint/tendermint/evidence"
  20. mempl "github.com/tendermint/tendermint/mempool"
  21. "github.com/tendermint/tendermint/p2p"
  22. "github.com/tendermint/tendermint/p2p/pex"
  23. "github.com/tendermint/tendermint/privval"
  24. "github.com/tendermint/tendermint/proxy"
  25. rpccore "github.com/tendermint/tendermint/rpc/core"
  26. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  27. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  28. rpc "github.com/tendermint/tendermint/rpc/lib"
  29. rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
  30. sm "github.com/tendermint/tendermint/state"
  31. "github.com/tendermint/tendermint/state/txindex"
  32. "github.com/tendermint/tendermint/state/txindex/kv"
  33. "github.com/tendermint/tendermint/state/txindex/null"
  34. "github.com/tendermint/tendermint/types"
  35. "github.com/tendermint/tendermint/version"
  36. _ "net/http/pprof"
  37. )
  38. //------------------------------------------------------------------------------
  39. // DBContext specifies config information for loading a new DB.
  40. type DBContext struct {
  41. ID string
  42. Config *cfg.Config
  43. }
  44. // DBProvider takes a DBContext and returns an instantiated DB.
  45. type DBProvider func(*DBContext) (dbm.DB, error)
  46. // DefaultDBProvider returns a database using the DBBackend and DBDir
  47. // specified in the ctx.Config.
  48. func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) {
  49. dbType := dbm.DBBackendType(ctx.Config.DBBackend)
  50. return dbm.NewDB(ctx.ID, dbType, ctx.Config.DBDir()), nil
  51. }
  52. // GenesisDocProvider returns a GenesisDoc.
  53. // It allows the GenesisDoc to be pulled from sources other than the
  54. // filesystem, for instance from a distributed key-value store cluster.
  55. type GenesisDocProvider func() (*types.GenesisDoc, error)
  56. // DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  57. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  58. func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider {
  59. return func() (*types.GenesisDoc, error) {
  60. return types.GenesisDocFromFile(config.GenesisFile())
  61. }
  62. }
  63. // NodeProvider takes a config and a logger and returns a ready to go Node.
  64. type NodeProvider func(*cfg.Config, log.Logger) (*Node, error)
  65. // DefaultNewNode returns a Tendermint node with default settings for the
  66. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  67. // It implements NodeProvider.
  68. func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) {
  69. return NewNode(config,
  70. privval.LoadOrGenFilePV(config.PrivValidatorFile()),
  71. proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()),
  72. DefaultGenesisDocProviderFunc(config),
  73. DefaultDBProvider,
  74. DefaultMetricsProvider,
  75. logger,
  76. )
  77. }
  78. // MetricsProvider returns a consensus, p2p and mempool Metrics.
  79. type MetricsProvider func() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics)
  80. // DefaultMetricsProvider returns consensus, p2p and mempool Metrics build
  81. // using Prometheus client library.
  82. func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) {
  83. return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics()
  84. }
  85. // NopMetricsProvider returns consensus, p2p and mempool Metrics as no-op.
  86. func NopMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) {
  87. return cs.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics()
  88. }
  89. //------------------------------------------------------------------------------
  90. // Node is the highest level interface to a full Tendermint node.
  91. // It includes all configuration information and running services.
  92. type Node struct {
  93. cmn.BaseService
  94. // config
  95. config *cfg.Config
  96. genesisDoc *types.GenesisDoc // initial validator set
  97. privValidator types.PrivValidator // local node's validator key
  98. // network
  99. sw *p2p.Switch // p2p connections
  100. addrBook pex.AddrBook // known peers
  101. // services
  102. eventBus *types.EventBus // pub/sub for services
  103. stateDB dbm.DB
  104. blockStore *bc.BlockStore // store the blockchain to disk
  105. bcReactor *bc.BlockchainReactor // for fast-syncing
  106. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  107. consensusState *cs.ConsensusState // latest consensus state
  108. consensusReactor *cs.ConsensusReactor // for participating in the consensus
  109. evidencePool *evidence.EvidencePool // tracking evidence
  110. proxyApp proxy.AppConns // connection to the application
  111. rpcListeners []net.Listener // rpc servers
  112. txIndexer txindex.TxIndexer
  113. indexerService *txindex.IndexerService
  114. prometheusSrv *http.Server
  115. }
  116. // NewNode returns a new, ready to go, Tendermint Node.
  117. func NewNode(config *cfg.Config,
  118. privValidator types.PrivValidator,
  119. clientCreator proxy.ClientCreator,
  120. genesisDocProvider GenesisDocProvider,
  121. dbProvider DBProvider,
  122. metricsProvider MetricsProvider,
  123. logger log.Logger) (*Node, error) {
  124. // Get BlockStore
  125. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  126. if err != nil {
  127. return nil, err
  128. }
  129. blockStore := bc.NewBlockStore(blockStoreDB)
  130. // Get State
  131. stateDB, err := dbProvider(&DBContext{"state", config})
  132. if err != nil {
  133. return nil, err
  134. }
  135. // Get genesis doc
  136. // TODO: move to state package?
  137. genDoc, err := loadGenesisDoc(stateDB)
  138. if err != nil {
  139. genDoc, err = genesisDocProvider()
  140. if err != nil {
  141. return nil, err
  142. }
  143. // save genesis doc to prevent a certain class of user errors (e.g. when it
  144. // was changed, accidentally or not). Also good for audit trail.
  145. saveGenesisDoc(stateDB, genDoc)
  146. }
  147. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  148. if err != nil {
  149. return nil, err
  150. }
  151. // Create the proxyApp, which manages connections (consensus, mempool, query)
  152. // and sync tendermint and the app by performing a handshake
  153. // and replaying any necessary blocks
  154. consensusLogger := logger.With("module", "consensus")
  155. handshaker := cs.NewHandshaker(stateDB, state, blockStore, genDoc)
  156. handshaker.SetLogger(consensusLogger)
  157. proxyApp := proxy.NewAppConns(clientCreator, handshaker)
  158. proxyApp.SetLogger(logger.With("module", "proxy"))
  159. if err := proxyApp.Start(); err != nil {
  160. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  161. }
  162. // reload the state (it may have been updated by the handshake)
  163. state = sm.LoadState(stateDB)
  164. // If an address is provided, listen on the socket for a
  165. // connection from an external signing process.
  166. if config.PrivValidatorListenAddr != "" {
  167. var (
  168. // TODO: persist this key so external signer
  169. // can actually authenticate us
  170. privKey = crypto.GenPrivKeyEd25519()
  171. pvsc = privval.NewSocketPV(
  172. logger.With("module", "privval"),
  173. config.PrivValidatorListenAddr,
  174. privKey,
  175. )
  176. )
  177. if err := pvsc.Start(); err != nil {
  178. return nil, fmt.Errorf("Error starting private validator client: %v", err)
  179. }
  180. privValidator = pvsc
  181. }
  182. // Decide whether to fast-sync or not
  183. // We don't fast-sync when the only validator is us.
  184. fastSync := config.FastSync
  185. if state.Validators.Size() == 1 {
  186. addr, _ := state.Validators.GetByIndex(0)
  187. if bytes.Equal(privValidator.GetAddress(), addr) {
  188. fastSync = false
  189. }
  190. }
  191. // Log whether this node is a validator or an observer
  192. if state.Validators.HasAddress(privValidator.GetAddress()) {
  193. consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  194. } else {
  195. consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  196. }
  197. // metrics
  198. var (
  199. csMetrics *cs.Metrics
  200. p2pMetrics *p2p.Metrics
  201. memplMetrics *mempl.Metrics
  202. )
  203. if config.Instrumentation.Prometheus {
  204. csMetrics, p2pMetrics, memplMetrics = metricsProvider()
  205. } else {
  206. csMetrics, p2pMetrics, memplMetrics = NopMetricsProvider()
  207. }
  208. // Make MempoolReactor
  209. mempoolLogger := logger.With("module", "mempool")
  210. mempool := mempl.NewMempool(
  211. config.Mempool,
  212. proxyApp.Mempool(),
  213. state.LastBlockHeight,
  214. mempl.WithMetrics(memplMetrics),
  215. )
  216. mempool.SetLogger(mempoolLogger)
  217. mempool.InitWAL() // no need to have the mempool wal during tests
  218. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  219. mempoolReactor.SetLogger(mempoolLogger)
  220. if config.Consensus.WaitForTxs() {
  221. mempool.EnableTxsAvailable()
  222. }
  223. // Make Evidence Reactor
  224. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  225. if err != nil {
  226. return nil, err
  227. }
  228. evidenceLogger := logger.With("module", "evidence")
  229. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  230. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  231. evidencePool.SetLogger(evidenceLogger)
  232. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  233. evidenceReactor.SetLogger(evidenceLogger)
  234. blockExecLogger := logger.With("module", "state")
  235. // make block executor for consensus and blockchain reactors to execute blocks
  236. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  237. // Make BlockchainReactor
  238. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  239. bcReactor.SetLogger(logger.With("module", "blockchain"))
  240. // Make ConsensusReactor
  241. consensusState := cs.NewConsensusState(
  242. config.Consensus,
  243. state.Copy(),
  244. blockExec,
  245. blockStore,
  246. mempool,
  247. evidencePool,
  248. cs.WithMetrics(csMetrics),
  249. )
  250. consensusState.SetLogger(consensusLogger)
  251. if privValidator != nil {
  252. consensusState.SetPrivValidator(privValidator)
  253. }
  254. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync)
  255. consensusReactor.SetLogger(consensusLogger)
  256. p2pLogger := logger.With("module", "p2p")
  257. sw := p2p.NewSwitch(config.P2P, p2p.WithMetrics(p2pMetrics))
  258. sw.SetLogger(p2pLogger)
  259. sw.AddReactor("MEMPOOL", mempoolReactor)
  260. sw.AddReactor("BLOCKCHAIN", bcReactor)
  261. sw.AddReactor("CONSENSUS", consensusReactor)
  262. sw.AddReactor("EVIDENCE", evidenceReactor)
  263. // Optionally, start the pex reactor
  264. //
  265. // TODO:
  266. //
  267. // We need to set Seeds and PersistentPeers on the switch,
  268. // since it needs to be able to use these (and their DNS names)
  269. // even if the PEX is off. We can include the DNS name in the NetAddress,
  270. // but it would still be nice to have a clear list of the current "PersistentPeers"
  271. // somewhere that we can return with net_info.
  272. //
  273. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  274. // Note we currently use the addrBook regardless at least for AddOurAddress
  275. addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  276. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  277. if config.P2P.PexReactor {
  278. // TODO persistent peers ? so we can have their DNS addrs saved
  279. pexReactor := pex.NewPEXReactor(addrBook,
  280. &pex.PEXReactorConfig{
  281. Seeds: cmn.SplitAndTrim(config.P2P.Seeds, ",", " "),
  282. SeedMode: config.P2P.SeedMode,
  283. PrivatePeerIDs: cmn.SplitAndTrim(config.P2P.PrivatePeerIDs, ",", " ")})
  284. pexReactor.SetLogger(p2pLogger)
  285. sw.AddReactor("PEX", pexReactor)
  286. }
  287. sw.SetAddrBook(addrBook)
  288. // Filter peers by addr or pubkey with an ABCI query.
  289. // If the query return code is OK, add peer.
  290. // XXX: Query format subject to change
  291. if config.FilterPeers {
  292. // NOTE: addr is ip:port
  293. sw.SetAddrFilter(func(addr net.Addr) error {
  294. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  295. if err != nil {
  296. return err
  297. }
  298. if resQuery.IsErr() {
  299. return fmt.Errorf("Error querying abci app: %v", resQuery)
  300. }
  301. return nil
  302. })
  303. sw.SetIDFilter(func(id p2p.ID) error {
  304. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/id/%s", id)})
  305. if err != nil {
  306. return err
  307. }
  308. if resQuery.IsErr() {
  309. return fmt.Errorf("Error querying abci app: %v", resQuery)
  310. }
  311. return nil
  312. })
  313. }
  314. eventBus := types.NewEventBus()
  315. eventBus.SetLogger(logger.With("module", "events"))
  316. // services which will be publishing and/or subscribing for messages (events)
  317. // consensusReactor will set it on consensusState and blockExecutor
  318. consensusReactor.SetEventBus(eventBus)
  319. // Transaction indexing
  320. var txIndexer txindex.TxIndexer
  321. switch config.TxIndex.Indexer {
  322. case "kv":
  323. store, err := dbProvider(&DBContext{"tx_index", config})
  324. if err != nil {
  325. return nil, err
  326. }
  327. if config.TxIndex.IndexTags != "" {
  328. txIndexer = kv.NewTxIndex(store, kv.IndexTags(cmn.SplitAndTrim(config.TxIndex.IndexTags, ",", " ")))
  329. } else if config.TxIndex.IndexAllTags {
  330. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  331. } else {
  332. txIndexer = kv.NewTxIndex(store)
  333. }
  334. default:
  335. txIndexer = &null.TxIndex{}
  336. }
  337. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  338. indexerService.SetLogger(logger.With("module", "txindex"))
  339. // run the profile server
  340. profileHost := config.ProfListenAddress
  341. if profileHost != "" {
  342. go func() {
  343. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  344. }()
  345. }
  346. node := &Node{
  347. config: config,
  348. genesisDoc: genDoc,
  349. privValidator: privValidator,
  350. sw: sw,
  351. addrBook: addrBook,
  352. stateDB: stateDB,
  353. blockStore: blockStore,
  354. bcReactor: bcReactor,
  355. mempoolReactor: mempoolReactor,
  356. consensusState: consensusState,
  357. consensusReactor: consensusReactor,
  358. evidencePool: evidencePool,
  359. proxyApp: proxyApp,
  360. txIndexer: txIndexer,
  361. indexerService: indexerService,
  362. eventBus: eventBus,
  363. }
  364. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  365. return node, nil
  366. }
  367. // OnStart starts the Node. It implements cmn.Service.
  368. func (n *Node) OnStart() error {
  369. err := n.eventBus.Start()
  370. if err != nil {
  371. return err
  372. }
  373. // Create & add listener
  374. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  375. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  376. n.sw.AddListener(l)
  377. // Generate node PrivKey
  378. // TODO: pass in like privValidator
  379. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  380. if err != nil {
  381. return err
  382. }
  383. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  384. nodeInfo := n.makeNodeInfo(nodeKey.ID())
  385. n.sw.SetNodeInfo(nodeInfo)
  386. n.sw.SetNodeKey(nodeKey)
  387. // Add ourselves to addrbook to prevent dialing ourselves
  388. n.addrBook.AddOurAddress(nodeInfo.NetAddress())
  389. // Start the RPC server before the P2P server
  390. // so we can eg. receive txs for the first block
  391. if n.config.RPC.ListenAddress != "" {
  392. listeners, err := n.startRPC()
  393. if err != nil {
  394. return err
  395. }
  396. n.rpcListeners = listeners
  397. }
  398. if n.config.Instrumentation.Prometheus {
  399. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  400. }
  401. // Start the switch (the P2P server).
  402. err = n.sw.Start()
  403. if err != nil {
  404. return err
  405. }
  406. // Always connect to persistent peers
  407. if n.config.P2P.PersistentPeers != "" {
  408. err = n.sw.DialPeersAsync(n.addrBook, cmn.SplitAndTrim(n.config.P2P.PersistentPeers, ",", " "), true)
  409. if err != nil {
  410. return err
  411. }
  412. }
  413. // start tx indexer
  414. return n.indexerService.Start()
  415. }
  416. // OnStop stops the Node. It implements cmn.Service.
  417. func (n *Node) OnStop() {
  418. n.BaseService.OnStop()
  419. n.Logger.Info("Stopping Node")
  420. // TODO: gracefully disconnect from peers.
  421. n.sw.Stop()
  422. for _, l := range n.rpcListeners {
  423. n.Logger.Info("Closing rpc listener", "listener", l)
  424. if err := l.Close(); err != nil {
  425. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  426. }
  427. }
  428. n.eventBus.Stop()
  429. n.indexerService.Stop()
  430. if pvsc, ok := n.privValidator.(*privval.SocketPV); ok {
  431. if err := pvsc.Stop(); err != nil {
  432. n.Logger.Error("Error stopping priv validator socket client", "err", err)
  433. }
  434. }
  435. if n.prometheusSrv != nil {
  436. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  437. // Error from closing listeners, or context timeout:
  438. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  439. }
  440. }
  441. }
  442. // RunForever waits for an interrupt signal and stops the node.
  443. func (n *Node) RunForever() {
  444. // Sleep forever and then...
  445. cmn.TrapSignal(func() {
  446. n.Stop()
  447. })
  448. }
  449. // AddListener adds a listener to accept inbound peer connections.
  450. // It should be called before starting the Node.
  451. // The first listener is the primary listener (in NodeInfo)
  452. func (n *Node) AddListener(l p2p.Listener) {
  453. n.sw.AddListener(l)
  454. }
  455. // ConfigureRPC sets all variables in rpccore so they will serve
  456. // rpc calls from this node
  457. func (n *Node) ConfigureRPC() {
  458. rpccore.SetStateDB(n.stateDB)
  459. rpccore.SetBlockStore(n.blockStore)
  460. rpccore.SetConsensusState(n.consensusState)
  461. rpccore.SetMempool(n.mempoolReactor.Mempool)
  462. rpccore.SetEvidencePool(n.evidencePool)
  463. rpccore.SetSwitch(n.sw)
  464. rpccore.SetPubKey(n.privValidator.GetPubKey())
  465. rpccore.SetGenesisDoc(n.genesisDoc)
  466. rpccore.SetAddrBook(n.addrBook)
  467. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  468. rpccore.SetTxIndexer(n.txIndexer)
  469. rpccore.SetConsensusReactor(n.consensusReactor)
  470. rpccore.SetEventBus(n.eventBus)
  471. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  472. }
  473. func (n *Node) startRPC() ([]net.Listener, error) {
  474. n.ConfigureRPC()
  475. listenAddrs := cmn.SplitAndTrim(n.config.RPC.ListenAddress, ",", " ")
  476. coreCodec := amino.NewCodec()
  477. ctypes.RegisterAmino(coreCodec)
  478. if n.config.RPC.Unsafe {
  479. rpccore.AddUnsafeRoutes()
  480. }
  481. // we may expose the rpc over both a unix and tcp socket
  482. listeners := make([]net.Listener, len(listenAddrs))
  483. for i, listenAddr := range listenAddrs {
  484. mux := http.NewServeMux()
  485. rpcLogger := n.Logger.With("module", "rpc-server")
  486. wm := rpcserver.NewWebsocketManager(rpccore.Routes, coreCodec, rpcserver.EventSubscriber(n.eventBus))
  487. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  488. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  489. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, coreCodec, rpcLogger)
  490. listener, err := rpcserver.StartHTTPServer(
  491. listenAddr,
  492. mux,
  493. rpcLogger,
  494. rpcserver.Config{MaxOpenConnections: n.config.RPC.MaxOpenConnections},
  495. )
  496. if err != nil {
  497. return nil, err
  498. }
  499. listeners[i] = listener
  500. }
  501. // we expose a simplified api over grpc for convenience to app devs
  502. grpcListenAddr := n.config.RPC.GRPCListenAddress
  503. if grpcListenAddr != "" {
  504. listener, err := grpccore.StartGRPCServer(
  505. grpcListenAddr,
  506. grpccore.Config{
  507. MaxOpenConnections: n.config.RPC.GRPCMaxOpenConnections,
  508. },
  509. )
  510. if err != nil {
  511. return nil, err
  512. }
  513. listeners = append(listeners, listener)
  514. }
  515. return listeners, nil
  516. }
  517. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  518. // collectors on addr.
  519. func (n *Node) startPrometheusServer(addr string) *http.Server {
  520. srv := &http.Server{
  521. Addr: addr,
  522. Handler: promhttp.Handler(),
  523. }
  524. go func() {
  525. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  526. // Error starting or closing listener:
  527. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  528. }
  529. }()
  530. return srv
  531. }
  532. // Switch returns the Node's Switch.
  533. func (n *Node) Switch() *p2p.Switch {
  534. return n.sw
  535. }
  536. // BlockStore returns the Node's BlockStore.
  537. func (n *Node) BlockStore() *bc.BlockStore {
  538. return n.blockStore
  539. }
  540. // ConsensusState returns the Node's ConsensusState.
  541. func (n *Node) ConsensusState() *cs.ConsensusState {
  542. return n.consensusState
  543. }
  544. // ConsensusReactor returns the Node's ConsensusReactor.
  545. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  546. return n.consensusReactor
  547. }
  548. // MempoolReactor returns the Node's MempoolReactor.
  549. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  550. return n.mempoolReactor
  551. }
  552. // EvidencePool returns the Node's EvidencePool.
  553. func (n *Node) EvidencePool() *evidence.EvidencePool {
  554. return n.evidencePool
  555. }
  556. // EventBus returns the Node's EventBus.
  557. func (n *Node) EventBus() *types.EventBus {
  558. return n.eventBus
  559. }
  560. // PrivValidator returns the Node's PrivValidator.
  561. // XXX: for convenience only!
  562. func (n *Node) PrivValidator() types.PrivValidator {
  563. return n.privValidator
  564. }
  565. // GenesisDoc returns the Node's GenesisDoc.
  566. func (n *Node) GenesisDoc() *types.GenesisDoc {
  567. return n.genesisDoc
  568. }
  569. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  570. func (n *Node) ProxyApp() proxy.AppConns {
  571. return n.proxyApp
  572. }
  573. func (n *Node) makeNodeInfo(nodeID p2p.ID) p2p.NodeInfo {
  574. txIndexerStatus := "on"
  575. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  576. txIndexerStatus = "off"
  577. }
  578. nodeInfo := p2p.NodeInfo{
  579. ID: nodeID,
  580. Network: n.genesisDoc.ChainID,
  581. Version: version.Version,
  582. Channels: []byte{
  583. bc.BlockchainChannel,
  584. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  585. mempl.MempoolChannel,
  586. evidence.EvidenceChannel,
  587. },
  588. Moniker: n.config.Moniker,
  589. Other: []string{
  590. cmn.Fmt("amino_version=%v", amino.Version),
  591. cmn.Fmt("p2p_version=%v", p2p.Version),
  592. cmn.Fmt("consensus_version=%v", cs.Version),
  593. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  594. cmn.Fmt("tx_index=%v", txIndexerStatus),
  595. },
  596. }
  597. if n.config.P2P.PexReactor {
  598. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  599. }
  600. rpcListenAddr := n.config.RPC.ListenAddress
  601. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  602. if !n.sw.IsListening() {
  603. return nodeInfo
  604. }
  605. p2pListener := n.sw.Listeners()[0]
  606. p2pHost := p2pListener.ExternalAddress().IP.String()
  607. p2pPort := p2pListener.ExternalAddress().Port
  608. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  609. return nodeInfo
  610. }
  611. //------------------------------------------------------------------------------
  612. // NodeInfo returns the Node's Info from the Switch.
  613. func (n *Node) NodeInfo() p2p.NodeInfo {
  614. return n.sw.NodeInfo()
  615. }
  616. //------------------------------------------------------------------------------
  617. var (
  618. genesisDocKey = []byte("genesisDoc")
  619. )
  620. // panics if failed to unmarshal bytes
  621. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  622. bytes := db.Get(genesisDocKey)
  623. if len(bytes) == 0 {
  624. return nil, errors.New("Genesis doc not found")
  625. }
  626. var genDoc *types.GenesisDoc
  627. err := cdc.UnmarshalJSON(bytes, &genDoc)
  628. if err != nil {
  629. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  630. }
  631. return genDoc, nil
  632. }
  633. // panics if failed to marshal the given genesis document
  634. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  635. bytes, err := cdc.MarshalJSON(genDoc)
  636. if err != nil {
  637. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  638. }
  639. db.SetSync(genesisDocKey, bytes)
  640. }