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.

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