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.

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