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.

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