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.

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