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.

840 lines
25 KiB

max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. _ "net/http/pprof"
  10. "strings"
  11. "time"
  12. "github.com/prometheus/client_golang/prometheus"
  13. "github.com/prometheus/client_golang/prometheus/promhttp"
  14. amino "github.com/tendermint/go-amino"
  15. abci "github.com/tendermint/tendermint/abci/types"
  16. bc "github.com/tendermint/tendermint/blockchain"
  17. cfg "github.com/tendermint/tendermint/config"
  18. cs "github.com/tendermint/tendermint/consensus"
  19. "github.com/tendermint/tendermint/crypto/ed25519"
  20. "github.com/tendermint/tendermint/evidence"
  21. cmn "github.com/tendermint/tendermint/libs/common"
  22. dbm "github.com/tendermint/tendermint/libs/db"
  23. "github.com/tendermint/tendermint/libs/log"
  24. mempl "github.com/tendermint/tendermint/mempool"
  25. "github.com/tendermint/tendermint/p2p"
  26. "github.com/tendermint/tendermint/p2p/pex"
  27. "github.com/tendermint/tendermint/privval"
  28. "github.com/tendermint/tendermint/proxy"
  29. rpccore "github.com/tendermint/tendermint/rpc/core"
  30. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  31. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  32. rpc "github.com/tendermint/tendermint/rpc/lib"
  33. rpcserver "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)
  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) {
  94. if config.Prometheus {
  95. return cs.PrometheusMetrics(config.Namespace), p2p.PrometheusMetrics(config.Namespace), mempl.PrometheusMetrics(config.Namespace)
  96. }
  97. return cs.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics()
  98. }
  99. }
  100. //------------------------------------------------------------------------------
  101. // Node is the highest level interface to a full Tendermint node.
  102. // It includes all configuration information and running services.
  103. type Node struct {
  104. cmn.BaseService
  105. // config
  106. config *cfg.Config
  107. genesisDoc *types.GenesisDoc // initial validator set
  108. privValidator types.PrivValidator // local node's validator key
  109. // network
  110. transport *p2p.MultiplexTransport
  111. sw *p2p.Switch // p2p connections
  112. addrBook pex.AddrBook // known peers
  113. nodeInfo p2p.NodeInfo
  114. nodeKey *p2p.NodeKey // our node privkey
  115. isListening bool
  116. // services
  117. eventBus *types.EventBus // pub/sub for services
  118. stateDB dbm.DB
  119. blockStore *bc.BlockStore // store the blockchain to disk
  120. bcReactor *bc.BlockchainReactor // for fast-syncing
  121. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  122. consensusState *cs.ConsensusState // latest consensus state
  123. consensusReactor *cs.ConsensusReactor // for participating in the consensus
  124. evidencePool *evidence.EvidencePool // tracking evidence
  125. proxyApp proxy.AppConns // connection to the application
  126. rpcListeners []net.Listener // rpc servers
  127. txIndexer txindex.TxIndexer
  128. indexerService *txindex.IndexerService
  129. prometheusSrv *http.Server
  130. }
  131. // NewNode returns a new, ready to go, Tendermint Node.
  132. func NewNode(config *cfg.Config,
  133. privValidator types.PrivValidator,
  134. nodeKey *p2p.NodeKey,
  135. clientCreator proxy.ClientCreator,
  136. genesisDocProvider GenesisDocProvider,
  137. dbProvider DBProvider,
  138. metricsProvider MetricsProvider,
  139. logger log.Logger) (*Node, error) {
  140. // Get BlockStore
  141. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  142. if err != nil {
  143. return nil, err
  144. }
  145. blockStore := bc.NewBlockStore(blockStoreDB)
  146. // Get State
  147. stateDB, err := dbProvider(&DBContext{"state", config})
  148. if err != nil {
  149. return nil, err
  150. }
  151. // Get genesis doc
  152. // TODO: move to state package?
  153. genDoc, err := loadGenesisDoc(stateDB)
  154. if err != nil {
  155. genDoc, err = genesisDocProvider()
  156. if err != nil {
  157. return nil, err
  158. }
  159. // save genesis doc to prevent a certain class of user errors (e.g. when it
  160. // was changed, accidentally or not). Also good for audit trail.
  161. saveGenesisDoc(stateDB, genDoc)
  162. }
  163. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  164. if err != nil {
  165. return nil, err
  166. }
  167. // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query).
  168. proxyApp := proxy.NewAppConns(clientCreator)
  169. proxyApp.SetLogger(logger.With("module", "proxy"))
  170. if err := proxyApp.Start(); err != nil {
  171. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  172. }
  173. // Create the handshaker, which calls RequestInfo and replays any blocks
  174. // as necessary to sync tendermint with the app.
  175. consensusLogger := logger.With("module", "consensus")
  176. handshaker := cs.NewHandshaker(stateDB, state, blockStore, genDoc)
  177. handshaker.SetLogger(consensusLogger)
  178. if err := handshaker.Handshake(proxyApp); err != nil {
  179. return nil, fmt.Errorf("Error during handshake: %v", err)
  180. }
  181. // reload the state (it may have been updated by the handshake)
  182. state = sm.LoadState(stateDB)
  183. // If an address is provided, listen on the socket for a
  184. // connection from an external signing process.
  185. if config.PrivValidatorListenAddr != "" {
  186. var (
  187. // TODO: persist this key so external signer
  188. // can actually authenticate us
  189. privKey = ed25519.GenPrivKey()
  190. pvsc = privval.NewSocketPV(
  191. logger.With("module", "privval"),
  192. config.PrivValidatorListenAddr,
  193. privKey,
  194. )
  195. )
  196. if err := pvsc.Start(); err != nil {
  197. return nil, fmt.Errorf("Error starting private validator client: %v", err)
  198. }
  199. privValidator = pvsc
  200. }
  201. // Decide whether to fast-sync or not
  202. // We don't fast-sync when the only validator is us.
  203. fastSync := config.FastSync
  204. if state.Validators.Size() == 1 {
  205. addr, _ := state.Validators.GetByIndex(0)
  206. if bytes.Equal(privValidator.GetAddress(), addr) {
  207. fastSync = false
  208. }
  209. }
  210. // Log whether this node is a validator or an observer
  211. if state.Validators.HasAddress(privValidator.GetAddress()) {
  212. consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  213. } else {
  214. consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  215. }
  216. csMetrics, p2pMetrics, memplMetrics := metricsProvider()
  217. // Make MempoolReactor
  218. mempool := mempl.NewMempool(
  219. config.Mempool,
  220. proxyApp.Mempool(),
  221. state.LastBlockHeight,
  222. mempl.WithMetrics(memplMetrics),
  223. mempl.WithPreCheck(
  224. mempl.PreCheckAminoMaxBytes(
  225. types.MaxDataBytesUnknownEvidence(
  226. state.ConsensusParams.BlockSize.MaxBytes,
  227. state.Validators.Size(),
  228. ),
  229. ),
  230. ),
  231. mempl.WithPostCheck(
  232. mempl.PostCheckMaxGas(state.ConsensusParams.BlockSize.MaxGas),
  233. ),
  234. )
  235. mempoolLogger := logger.With("module", "mempool")
  236. mempool.SetLogger(mempoolLogger)
  237. mempool.InitWAL() // no need to have the mempool wal during tests
  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(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  257. // Make BlockchainReactor
  258. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  259. bcReactor.SetLogger(logger.With("module", "blockchain"))
  260. // Make ConsensusReactor
  261. consensusState := cs.NewConsensusState(
  262. config.Consensus,
  263. state.Copy(),
  264. blockExec,
  265. blockStore,
  266. mempool,
  267. evidencePool,
  268. cs.StateMetrics(csMetrics),
  269. )
  270. consensusState.SetLogger(consensusLogger)
  271. if privValidator != nil {
  272. consensusState.SetPrivValidator(privValidator)
  273. }
  274. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync, cs.ReactorMetrics(csMetrics))
  275. consensusReactor.SetLogger(consensusLogger)
  276. eventBus := types.NewEventBus()
  277. eventBus.SetLogger(logger.With("module", "events"))
  278. // services which will be publishing and/or subscribing for messages (events)
  279. // consensusReactor will set it on consensusState and blockExecutor
  280. consensusReactor.SetEventBus(eventBus)
  281. // Transaction indexing
  282. var txIndexer txindex.TxIndexer
  283. switch config.TxIndex.Indexer {
  284. case "kv":
  285. store, err := dbProvider(&DBContext{"tx_index", config})
  286. if err != nil {
  287. return nil, err
  288. }
  289. if config.TxIndex.IndexTags != "" {
  290. txIndexer = kv.NewTxIndex(store, kv.IndexTags(splitAndTrimEmpty(config.TxIndex.IndexTags, ",", " ")))
  291. } else if config.TxIndex.IndexAllTags {
  292. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  293. } else {
  294. txIndexer = kv.NewTxIndex(store)
  295. }
  296. default:
  297. txIndexer = &null.TxIndex{}
  298. }
  299. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  300. indexerService.SetLogger(logger.With("module", "txindex"))
  301. var (
  302. p2pLogger = logger.With("module", "p2p")
  303. nodeInfo = makeNodeInfo(config, nodeKey.ID(), txIndexer, genDoc.ChainID)
  304. )
  305. // Setup Transport.
  306. var (
  307. transport = p2p.NewMultiplexTransport(nodeInfo, *nodeKey)
  308. connFilters = []p2p.ConnFilterFunc{}
  309. peerFilters = []p2p.PeerFilterFunc{}
  310. )
  311. if !config.P2P.AllowDuplicateIP {
  312. connFilters = append(connFilters, p2p.ConnDuplicateIPFilter())
  313. }
  314. // Filter peers by addr or pubkey with an ABCI query.
  315. // If the query return code is OK, add peer.
  316. if config.FilterPeers {
  317. connFilters = append(
  318. connFilters,
  319. // ABCI query for address filtering.
  320. func(_ p2p.ConnSet, c net.Conn, _ []net.IP) error {
  321. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  322. Path: fmt.Sprintf("/p2p/filter/addr/%s", c.RemoteAddr().String()),
  323. })
  324. if err != nil {
  325. return err
  326. }
  327. if res.IsErr() {
  328. return fmt.Errorf("Error querying abci app: %v", res)
  329. }
  330. return nil
  331. },
  332. )
  333. peerFilters = append(
  334. peerFilters,
  335. // ABCI query for ID filtering.
  336. func(_ p2p.IPeerSet, p p2p.Peer) error {
  337. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  338. Path: fmt.Sprintf("/p2p/filter/id/%s", p.ID()),
  339. })
  340. if err != nil {
  341. return err
  342. }
  343. if res.IsErr() {
  344. return fmt.Errorf("Error querying abci app: %v", res)
  345. }
  346. return nil
  347. },
  348. )
  349. }
  350. p2p.MultiplexTransportConnFilters(connFilters...)(transport)
  351. // Setup Switch.
  352. sw := p2p.NewSwitch(
  353. config.P2P,
  354. transport,
  355. p2p.WithMetrics(p2pMetrics),
  356. p2p.SwitchPeerFilters(peerFilters...),
  357. )
  358. sw.SetLogger(p2pLogger)
  359. sw.AddReactor("MEMPOOL", mempoolReactor)
  360. sw.AddReactor("BLOCKCHAIN", bcReactor)
  361. sw.AddReactor("CONSENSUS", consensusReactor)
  362. sw.AddReactor("EVIDENCE", evidenceReactor)
  363. sw.SetNodeInfo(nodeInfo)
  364. sw.SetNodeKey(nodeKey)
  365. p2pLogger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", config.NodeKeyFile())
  366. // Optionally, start the pex reactor
  367. //
  368. // TODO:
  369. //
  370. // We need to set Seeds and PersistentPeers on the switch,
  371. // since it needs to be able to use these (and their DNS names)
  372. // even if the PEX is off. We can include the DNS name in the NetAddress,
  373. // but it would still be nice to have a clear list of the current "PersistentPeers"
  374. // somewhere that we can return with net_info.
  375. //
  376. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  377. // Note we currently use the addrBook regardless at least for AddOurAddress
  378. addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  379. // Add ourselves to addrbook to prevent dialing ourselves
  380. addrBook.AddOurAddress(nodeInfo.NetAddress())
  381. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  382. if config.P2P.PexReactor {
  383. // TODO persistent peers ? so we can have their DNS addrs saved
  384. pexReactor := pex.NewPEXReactor(addrBook,
  385. &pex.PEXReactorConfig{
  386. Seeds: splitAndTrimEmpty(config.P2P.Seeds, ",", " "),
  387. SeedMode: config.P2P.SeedMode,
  388. })
  389. pexReactor.SetLogger(p2pLogger)
  390. sw.AddReactor("PEX", pexReactor)
  391. }
  392. sw.SetAddrBook(addrBook)
  393. // run the profile server
  394. profileHost := config.ProfListenAddress
  395. if profileHost != "" {
  396. go func() {
  397. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  398. }()
  399. }
  400. node := &Node{
  401. config: config,
  402. genesisDoc: genDoc,
  403. privValidator: privValidator,
  404. transport: transport,
  405. sw: sw,
  406. addrBook: addrBook,
  407. nodeInfo: nodeInfo,
  408. nodeKey: nodeKey,
  409. stateDB: stateDB,
  410. blockStore: blockStore,
  411. bcReactor: bcReactor,
  412. mempoolReactor: mempoolReactor,
  413. consensusState: consensusState,
  414. consensusReactor: consensusReactor,
  415. evidencePool: evidencePool,
  416. proxyApp: proxyApp,
  417. txIndexer: txIndexer,
  418. indexerService: indexerService,
  419. eventBus: eventBus,
  420. }
  421. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  422. return node, nil
  423. }
  424. // OnStart starts the Node. It implements cmn.Service.
  425. func (n *Node) OnStart() error {
  426. now := tmtime.Now()
  427. genTime := n.genesisDoc.GenesisTime
  428. if genTime.After(now) {
  429. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  430. time.Sleep(genTime.Sub(now))
  431. }
  432. err := n.eventBus.Start()
  433. if err != nil {
  434. return err
  435. }
  436. // Add private IDs to addrbook to block those peers being added
  437. n.addrBook.AddPrivateIDs(splitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  438. // Start the RPC server before the P2P server
  439. // so we can eg. receive txs for the first block
  440. if n.config.RPC.ListenAddress != "" {
  441. listeners, err := n.startRPC()
  442. if err != nil {
  443. return err
  444. }
  445. n.rpcListeners = listeners
  446. }
  447. if n.config.Instrumentation.Prometheus &&
  448. n.config.Instrumentation.PrometheusListenAddr != "" {
  449. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  450. }
  451. // Start the transport.
  452. addr, err := p2p.NewNetAddressStringWithOptionalID(n.config.P2P.ListenAddress)
  453. if err != nil {
  454. return err
  455. }
  456. if err := n.transport.Listen(*addr); err != nil {
  457. return err
  458. }
  459. n.isListening = true
  460. // Start the switch (the P2P server).
  461. err = n.sw.Start()
  462. if err != nil {
  463. return err
  464. }
  465. // Always connect to persistent peers
  466. if n.config.P2P.PersistentPeers != "" {
  467. err = n.sw.DialPeersAsync(n.addrBook, splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "), true)
  468. if err != nil {
  469. return err
  470. }
  471. }
  472. // start tx indexer
  473. return n.indexerService.Start()
  474. }
  475. // OnStop stops the Node. It implements cmn.Service.
  476. func (n *Node) OnStop() {
  477. n.BaseService.OnStop()
  478. n.Logger.Info("Stopping Node")
  479. // first stop the non-reactor services
  480. n.eventBus.Stop()
  481. n.indexerService.Stop()
  482. // now stop the reactors
  483. // TODO: gracefully disconnect from peers.
  484. n.sw.Stop()
  485. if err := n.transport.Close(); err != nil {
  486. n.Logger.Error("Error closing transport", "err", err)
  487. }
  488. n.isListening = false
  489. // finally stop the listeners / external services
  490. for _, l := range n.rpcListeners {
  491. n.Logger.Info("Closing rpc listener", "listener", l)
  492. if err := l.Close(); err != nil {
  493. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  494. }
  495. }
  496. if pvsc, ok := n.privValidator.(*privval.SocketPV); ok {
  497. if err := pvsc.Stop(); err != nil {
  498. n.Logger.Error("Error stopping priv validator socket client", "err", err)
  499. }
  500. }
  501. if n.prometheusSrv != nil {
  502. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  503. // Error from closing listeners, or context timeout:
  504. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  505. }
  506. }
  507. }
  508. // ConfigureRPC sets all variables in rpccore so they will serve
  509. // rpc calls from this node
  510. func (n *Node) ConfigureRPC() {
  511. rpccore.SetStateDB(n.stateDB)
  512. rpccore.SetBlockStore(n.blockStore)
  513. rpccore.SetConsensusState(n.consensusState)
  514. rpccore.SetMempool(n.mempoolReactor.Mempool)
  515. rpccore.SetEvidencePool(n.evidencePool)
  516. rpccore.SetP2PPeers(n.sw)
  517. rpccore.SetP2PTransport(n)
  518. rpccore.SetPubKey(n.privValidator.GetPubKey())
  519. rpccore.SetGenesisDoc(n.genesisDoc)
  520. rpccore.SetAddrBook(n.addrBook)
  521. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  522. rpccore.SetTxIndexer(n.txIndexer)
  523. rpccore.SetConsensusReactor(n.consensusReactor)
  524. rpccore.SetEventBus(n.eventBus)
  525. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  526. }
  527. func (n *Node) startRPC() ([]net.Listener, error) {
  528. n.ConfigureRPC()
  529. listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  530. coreCodec := amino.NewCodec()
  531. ctypes.RegisterAmino(coreCodec)
  532. if n.config.RPC.Unsafe {
  533. rpccore.AddUnsafeRoutes()
  534. }
  535. // we may expose the rpc over both a unix and tcp socket
  536. listeners := make([]net.Listener, len(listenAddrs))
  537. for i, listenAddr := range listenAddrs {
  538. mux := http.NewServeMux()
  539. rpcLogger := n.Logger.With("module", "rpc-server")
  540. wm := rpcserver.NewWebsocketManager(rpccore.Routes, coreCodec, rpcserver.EventSubscriber(n.eventBus))
  541. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  542. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  543. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, coreCodec, rpcLogger)
  544. listener, err := rpcserver.StartHTTPServer(
  545. listenAddr,
  546. mux,
  547. rpcLogger,
  548. rpcserver.Config{MaxOpenConnections: n.config.RPC.MaxOpenConnections},
  549. )
  550. if err != nil {
  551. return nil, err
  552. }
  553. listeners[i] = listener
  554. }
  555. // we expose a simplified api over grpc for convenience to app devs
  556. grpcListenAddr := n.config.RPC.GRPCListenAddress
  557. if grpcListenAddr != "" {
  558. listener, err := grpccore.StartGRPCServer(
  559. grpcListenAddr,
  560. grpccore.Config{
  561. MaxOpenConnections: n.config.RPC.GRPCMaxOpenConnections,
  562. },
  563. )
  564. if err != nil {
  565. return nil, err
  566. }
  567. listeners = append(listeners, listener)
  568. }
  569. return listeners, nil
  570. }
  571. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  572. // collectors on addr.
  573. func (n *Node) startPrometheusServer(addr string) *http.Server {
  574. srv := &http.Server{
  575. Addr: addr,
  576. Handler: promhttp.InstrumentMetricHandler(
  577. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  578. prometheus.DefaultGatherer,
  579. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  580. ),
  581. ),
  582. }
  583. go func() {
  584. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  585. // Error starting or closing listener:
  586. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  587. }
  588. }()
  589. return srv
  590. }
  591. // Switch returns the Node's Switch.
  592. func (n *Node) Switch() *p2p.Switch {
  593. return n.sw
  594. }
  595. // BlockStore returns the Node's BlockStore.
  596. func (n *Node) BlockStore() *bc.BlockStore {
  597. return n.blockStore
  598. }
  599. // ConsensusState returns the Node's ConsensusState.
  600. func (n *Node) ConsensusState() *cs.ConsensusState {
  601. return n.consensusState
  602. }
  603. // ConsensusReactor returns the Node's ConsensusReactor.
  604. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  605. return n.consensusReactor
  606. }
  607. // MempoolReactor returns the Node's MempoolReactor.
  608. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  609. return n.mempoolReactor
  610. }
  611. // EvidencePool returns the Node's EvidencePool.
  612. func (n *Node) EvidencePool() *evidence.EvidencePool {
  613. return n.evidencePool
  614. }
  615. // EventBus returns the Node's EventBus.
  616. func (n *Node) EventBus() *types.EventBus {
  617. return n.eventBus
  618. }
  619. // PrivValidator returns the Node's PrivValidator.
  620. // XXX: for convenience only!
  621. func (n *Node) PrivValidator() types.PrivValidator {
  622. return n.privValidator
  623. }
  624. // GenesisDoc returns the Node's GenesisDoc.
  625. func (n *Node) GenesisDoc() *types.GenesisDoc {
  626. return n.genesisDoc
  627. }
  628. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  629. func (n *Node) ProxyApp() proxy.AppConns {
  630. return n.proxyApp
  631. }
  632. //------------------------------------------------------------------------------
  633. func (n *Node) Listeners() []string {
  634. return []string{
  635. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  636. }
  637. }
  638. func (n *Node) IsListening() bool {
  639. return n.isListening
  640. }
  641. // NodeInfo returns the Node's Info from the Switch.
  642. func (n *Node) NodeInfo() p2p.NodeInfo {
  643. return n.nodeInfo
  644. }
  645. func makeNodeInfo(
  646. config *cfg.Config,
  647. nodeID p2p.ID,
  648. txIndexer txindex.TxIndexer,
  649. chainID string,
  650. ) p2p.NodeInfo {
  651. txIndexerStatus := "on"
  652. if _, ok := txIndexer.(*null.TxIndex); ok {
  653. txIndexerStatus = "off"
  654. }
  655. nodeInfo := p2p.NodeInfo{
  656. ID: nodeID,
  657. Network: chainID,
  658. Version: version.Version,
  659. Channels: []byte{
  660. bc.BlockchainChannel,
  661. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  662. mempl.MempoolChannel,
  663. evidence.EvidenceChannel,
  664. },
  665. Moniker: config.Moniker,
  666. Other: p2p.NodeInfoOther{
  667. AminoVersion: amino.Version,
  668. P2PVersion: p2p.Version,
  669. ConsensusVersion: cs.Version,
  670. RPCVersion: fmt.Sprintf("%v/%v", rpc.Version, rpccore.Version),
  671. TxIndex: txIndexerStatus,
  672. RPCAddress: config.RPC.ListenAddress,
  673. },
  674. }
  675. if config.P2P.PexReactor {
  676. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  677. }
  678. lAddr := config.P2P.ExternalAddress
  679. if lAddr == "" {
  680. lAddr = config.P2P.ListenAddress
  681. }
  682. nodeInfo.ListenAddr = lAddr
  683. return nodeInfo
  684. }
  685. //------------------------------------------------------------------------------
  686. var (
  687. genesisDocKey = []byte("genesisDoc")
  688. )
  689. // panics if failed to unmarshal bytes
  690. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  691. bytes := db.Get(genesisDocKey)
  692. if len(bytes) == 0 {
  693. return nil, errors.New("Genesis doc not found")
  694. }
  695. var genDoc *types.GenesisDoc
  696. err := cdc.UnmarshalJSON(bytes, &genDoc)
  697. if err != nil {
  698. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  699. }
  700. return genDoc, nil
  701. }
  702. // panics if failed to marshal the given genesis document
  703. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  704. bytes, err := cdc.MarshalJSON(genDoc)
  705. if err != nil {
  706. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  707. }
  708. db.SetSync(genesisDocKey, bytes)
  709. }
  710. // splitAndTrimEmpty slices s into all subslices separated by sep and returns a
  711. // slice of the string s with all leading and trailing Unicode code points
  712. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  713. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  714. // -1. also filter out empty strings, only return non-empty strings.
  715. func splitAndTrimEmpty(s, sep, cutset string) []string {
  716. if s == "" {
  717. return []string{}
  718. }
  719. spl := strings.Split(s, sep)
  720. nonEmptyStrings := make([]string, 0, len(spl))
  721. for i := 0; i < len(spl); i++ {
  722. element := strings.Trim(spl[i], cutset)
  723. if element != "" {
  724. nonEmptyStrings = append(nonEmptyStrings, element)
  725. }
  726. }
  727. return nonEmptyStrings
  728. }