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.

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