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.

841 lines
25 KiB

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