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.

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