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.

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