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.

1462 lines
45 KiB

  1. package node
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. _ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/prometheus/client_golang/prometheus"
  14. "github.com/prometheus/client_golang/prometheus/promhttp"
  15. "github.com/rs/cors"
  16. dbm "github.com/tendermint/tm-db"
  17. abci "github.com/tendermint/tendermint/abci/types"
  18. bcv0 "github.com/tendermint/tendermint/blockchain/v0"
  19. bcv1 "github.com/tendermint/tendermint/blockchain/v1"
  20. bcv2 "github.com/tendermint/tendermint/blockchain/v2"
  21. cfg "github.com/tendermint/tendermint/config"
  22. "github.com/tendermint/tendermint/consensus"
  23. "github.com/tendermint/tendermint/crypto"
  24. "github.com/tendermint/tendermint/evidence"
  25. tmjson "github.com/tendermint/tendermint/libs/json"
  26. "github.com/tendermint/tendermint/libs/log"
  27. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  28. "github.com/tendermint/tendermint/libs/service"
  29. "github.com/tendermint/tendermint/light"
  30. mempl "github.com/tendermint/tendermint/mempool"
  31. "github.com/tendermint/tendermint/p2p"
  32. "github.com/tendermint/tendermint/p2p/pex"
  33. "github.com/tendermint/tendermint/privval"
  34. "github.com/tendermint/tendermint/proxy"
  35. rpccore "github.com/tendermint/tendermint/rpc/core"
  36. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  37. rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  38. sm "github.com/tendermint/tendermint/state"
  39. "github.com/tendermint/tendermint/state/indexer"
  40. blockidxkv "github.com/tendermint/tendermint/state/indexer/block/kv"
  41. blockidxnull "github.com/tendermint/tendermint/state/indexer/block/null"
  42. "github.com/tendermint/tendermint/state/txindex"
  43. "github.com/tendermint/tendermint/state/txindex/kv"
  44. "github.com/tendermint/tendermint/state/txindex/null"
  45. "github.com/tendermint/tendermint/statesync"
  46. "github.com/tendermint/tendermint/store"
  47. cs "github.com/tendermint/tendermint/test/maverick/consensus"
  48. "github.com/tendermint/tendermint/types"
  49. tmtime "github.com/tendermint/tendermint/types/time"
  50. "github.com/tendermint/tendermint/version"
  51. )
  52. //------------------------------------------------------------------------------
  53. // ParseMisbehaviors is a util function that converts a comma separated string into
  54. // a map of misbehaviors to be executed by the maverick node
  55. func ParseMisbehaviors(str string) (map[int64]cs.Misbehavior, error) {
  56. // check if string is empty in which case we run a normal node
  57. var misbehaviors = make(map[int64]cs.Misbehavior)
  58. if str == "" {
  59. return misbehaviors, nil
  60. }
  61. strs := strings.Split(str, ",")
  62. if len(strs)%2 != 0 {
  63. return misbehaviors, errors.New("missing either height or misbehavior name in the misbehavior flag")
  64. }
  65. OUTER_LOOP:
  66. for i := 0; i < len(strs); i += 2 {
  67. height, err := strconv.ParseInt(strs[i+1], 10, 64)
  68. if err != nil {
  69. return misbehaviors, fmt.Errorf("failed to parse misbehavior height: %w", err)
  70. }
  71. for key, misbehavior := range cs.MisbehaviorList {
  72. if key == strs[i] {
  73. misbehaviors[height] = misbehavior
  74. continue OUTER_LOOP
  75. }
  76. }
  77. return misbehaviors, fmt.Errorf("received unknown misbehavior: %s. Did you forget to add it?", strs[i])
  78. }
  79. return misbehaviors, nil
  80. }
  81. // DBContext specifies config information for loading a new DB.
  82. type DBContext struct {
  83. ID string
  84. Config *cfg.Config
  85. }
  86. // DBProvider takes a DBContext and returns an instantiated DB.
  87. type DBProvider func(*DBContext) (dbm.DB, error)
  88. // DefaultDBProvider returns a database using the DBBackend and DBDir
  89. // specified in the ctx.Config.
  90. func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) {
  91. dbType := dbm.BackendType(ctx.Config.DBBackend)
  92. return dbm.NewDB(ctx.ID, dbType, ctx.Config.DBDir())
  93. }
  94. // GenesisDocProvider returns a GenesisDoc.
  95. // It allows the GenesisDoc to be pulled from sources other than the
  96. // filesystem, for instance from a distributed key-value store cluster.
  97. type GenesisDocProvider func() (*types.GenesisDoc, error)
  98. // DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  99. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  100. func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider {
  101. return func() (*types.GenesisDoc, error) {
  102. return types.GenesisDocFromFile(config.GenesisFile())
  103. }
  104. }
  105. // Provider takes a config and a logger and returns a ready to go Node.
  106. type Provider func(*cfg.Config, log.Logger) (*Node, error)
  107. // DefaultNewNode returns a Tendermint node with default settings for the
  108. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  109. // It implements NodeProvider.
  110. func DefaultNewNode(config *cfg.Config, logger log.Logger, misbehaviors map[int64]cs.Misbehavior) (*Node, error) {
  111. nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
  112. if err != nil {
  113. return nil, fmt.Errorf("failed to load or gen node key %s, err: %w", config.NodeKeyFile(), err)
  114. }
  115. return NewNode(config,
  116. LoadOrGenFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()),
  117. nodeKey,
  118. proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()),
  119. DefaultGenesisDocProviderFunc(config),
  120. DefaultDBProvider,
  121. DefaultMetricsProvider(config.Instrumentation),
  122. logger,
  123. misbehaviors,
  124. )
  125. }
  126. // MetricsProvider returns a consensus, p2p and mempool Metrics.
  127. type MetricsProvider func(chainID string) (*consensus.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics)
  128. // DefaultMetricsProvider returns Metrics build using Prometheus client library
  129. // if Prometheus is enabled. Otherwise, it returns no-op Metrics.
  130. func DefaultMetricsProvider(config *cfg.InstrumentationConfig) MetricsProvider {
  131. return func(chainID string) (*consensus.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics) {
  132. if config.Prometheus {
  133. return consensus.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  134. p2p.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  135. mempl.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  136. sm.PrometheusMetrics(config.Namespace, "chain_id", chainID)
  137. }
  138. return consensus.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics(), sm.NopMetrics()
  139. }
  140. }
  141. // Option sets a parameter for the node.
  142. type Option func(*Node)
  143. // Temporary interface for switching to fast sync, we should get rid of v0 and v1 reactors.
  144. // See: https://github.com/tendermint/tendermint/issues/4595
  145. type fastSyncReactor interface {
  146. SwitchToFastSync(sm.State) error
  147. }
  148. // CustomReactors allows you to add custom reactors (name -> p2p.Reactor) to
  149. // the node's Switch.
  150. //
  151. // WARNING: using any name from the below list of the existing reactors will
  152. // result in replacing it with the custom one.
  153. //
  154. // - MEMPOOL
  155. // - BLOCKCHAIN
  156. // - CONSENSUS
  157. // - EVIDENCE
  158. // - PEX
  159. // - STATESYNC
  160. func CustomReactors(reactors map[string]p2p.Reactor) Option {
  161. return func(n *Node) {
  162. for name, reactor := range reactors {
  163. if existingReactor := n.sw.Reactor(name); existingReactor != nil {
  164. n.sw.Logger.Info("Replacing existing reactor with a custom one",
  165. "name", name, "existing", existingReactor, "custom", reactor)
  166. n.sw.RemoveReactor(name, existingReactor)
  167. }
  168. n.sw.AddReactor(name, reactor)
  169. }
  170. }
  171. }
  172. func CustomReactorsAsConstructors(reactors map[string]func(n *Node) p2p.Reactor) Option {
  173. return func(n *Node) {
  174. for name, customReactor := range reactors {
  175. if existingReactor := n.sw.Reactor(name); existingReactor != nil {
  176. n.sw.Logger.Info("Replacing existing reactor with a custom one",
  177. "name", name)
  178. n.sw.RemoveReactor(name, existingReactor)
  179. }
  180. n.sw.AddReactor(name, customReactor(n))
  181. }
  182. }
  183. }
  184. // StateProvider overrides the state provider used by state sync to retrieve trusted app hashes and
  185. // build a State object for bootstrapping the node.
  186. // WARNING: this interface is considered unstable and subject to change.
  187. func StateProvider(stateProvider statesync.StateProvider) Option {
  188. return func(n *Node) {
  189. n.stateSyncProvider = stateProvider
  190. }
  191. }
  192. //------------------------------------------------------------------------------
  193. // Node is the highest level interface to a full Tendermint node.
  194. // It includes all configuration information and running services.
  195. type Node struct {
  196. service.BaseService
  197. // config
  198. config *cfg.Config
  199. genesisDoc *types.GenesisDoc // initial validator set
  200. privValidator types.PrivValidator // local node's validator key
  201. // network
  202. transport *p2p.MultiplexTransport
  203. sw *p2p.Switch // p2p connections
  204. addrBook pex.AddrBook // known peers
  205. nodeInfo p2p.NodeInfo
  206. nodeKey *p2p.NodeKey // our node privkey
  207. isListening bool
  208. // services
  209. eventBus *types.EventBus // pub/sub for services
  210. stateStore sm.Store
  211. blockStore *store.BlockStore // store the blockchain to disk
  212. bcReactor p2p.Reactor // for fast-syncing
  213. mempoolReactor *mempl.Reactor // for gossipping transactions
  214. mempool mempl.Mempool
  215. stateSync bool // whether the node should state sync on startup
  216. stateSyncReactor *statesync.Reactor // for hosting and restoring state sync snapshots
  217. stateSyncProvider statesync.StateProvider // provides state data for bootstrapping a node
  218. stateSyncGenesis sm.State // provides the genesis state for state sync
  219. consensusState *cs.State // latest consensus state
  220. consensusReactor *cs.Reactor // for participating in the consensus
  221. pexReactor *pex.Reactor // for exchanging peer addresses
  222. evidencePool *evidence.Pool // tracking evidence
  223. proxyApp proxy.AppConns // connection to the application
  224. rpcListeners []net.Listener // rpc servers
  225. txIndexer txindex.TxIndexer
  226. blockIndexer indexer.BlockIndexer
  227. indexerService *txindex.IndexerService
  228. prometheusSrv *http.Server
  229. }
  230. func initDBs(config *cfg.Config, dbProvider DBProvider) (blockStore *store.BlockStore, stateDB dbm.DB, err error) {
  231. var blockStoreDB dbm.DB
  232. blockStoreDB, err = dbProvider(&DBContext{"blockstore", config})
  233. if err != nil {
  234. return
  235. }
  236. blockStore = store.NewBlockStore(blockStoreDB)
  237. stateDB, err = dbProvider(&DBContext{"state", config})
  238. if err != nil {
  239. return
  240. }
  241. return
  242. }
  243. func createAndStartProxyAppConns(clientCreator proxy.ClientCreator, logger log.Logger) (proxy.AppConns, error) {
  244. proxyApp := proxy.NewAppConns(clientCreator)
  245. proxyApp.SetLogger(logger.With("module", "proxy"))
  246. if err := proxyApp.Start(); err != nil {
  247. return nil, fmt.Errorf("error starting proxy app connections: %v", err)
  248. }
  249. return proxyApp, nil
  250. }
  251. func createAndStartEventBus(logger log.Logger) (*types.EventBus, error) {
  252. eventBus := types.NewEventBus()
  253. eventBus.SetLogger(logger.With("module", "events"))
  254. if err := eventBus.Start(); err != nil {
  255. return nil, err
  256. }
  257. return eventBus, nil
  258. }
  259. func createAndStartIndexerService(
  260. config *cfg.Config,
  261. dbProvider DBProvider,
  262. eventBus *types.EventBus,
  263. logger log.Logger,
  264. ) (*txindex.IndexerService, txindex.TxIndexer, indexer.BlockIndexer, error) {
  265. var (
  266. txIndexer txindex.TxIndexer
  267. blockIndexer indexer.BlockIndexer
  268. )
  269. switch config.TxIndex.Indexer {
  270. case "kv":
  271. store, err := dbProvider(&DBContext{"tx_index", config})
  272. if err != nil {
  273. return nil, nil, nil, err
  274. }
  275. txIndexer = kv.NewTxIndex(store)
  276. blockIndexer = blockidxkv.New(dbm.NewPrefixDB(store, []byte("block_events")))
  277. default:
  278. txIndexer = &null.TxIndex{}
  279. blockIndexer = &blockidxnull.BlockerIndexer{}
  280. }
  281. indexerService := txindex.NewIndexerService(txIndexer, blockIndexer, eventBus)
  282. indexerService.SetLogger(logger.With("module", "txindex"))
  283. if err := indexerService.Start(); err != nil {
  284. return nil, nil, nil, err
  285. }
  286. return indexerService, txIndexer, blockIndexer, nil
  287. }
  288. func doHandshake(
  289. stateStore sm.Store,
  290. state sm.State,
  291. blockStore sm.BlockStore,
  292. genDoc *types.GenesisDoc,
  293. eventBus types.BlockEventPublisher,
  294. proxyApp proxy.AppConns,
  295. consensusLogger log.Logger) error {
  296. handshaker := cs.NewHandshaker(stateStore, state, blockStore, genDoc)
  297. handshaker.SetLogger(consensusLogger)
  298. handshaker.SetEventBus(eventBus)
  299. if err := handshaker.Handshake(proxyApp); err != nil {
  300. return fmt.Errorf("error during handshake: %v", err)
  301. }
  302. return nil
  303. }
  304. func logNodeStartupInfo(state sm.State, pubKey crypto.PubKey, logger, consensusLogger log.Logger) {
  305. // Log the version info.
  306. logger.Info("Version info",
  307. "software", version.TMCoreSemVer,
  308. "block", version.BlockProtocol,
  309. "p2p", version.P2PProtocol,
  310. )
  311. // If the state and software differ in block version, at least log it.
  312. if state.Version.Consensus.Block != version.BlockProtocol {
  313. logger.Info("Software and state have different block protocols",
  314. "software", version.BlockProtocol,
  315. "state", state.Version.Consensus.Block,
  316. )
  317. }
  318. addr := pubKey.Address()
  319. // Log whether this node is a validator or an observer
  320. if state.Validators.HasAddress(addr) {
  321. consensusLogger.Info("This node is a validator", "addr", addr, "pubKey", pubKey)
  322. } else {
  323. consensusLogger.Info("This node is not a validator", "addr", addr, "pubKey", pubKey)
  324. }
  325. }
  326. func onlyValidatorIsUs(state sm.State, pubKey crypto.PubKey) bool {
  327. if state.Validators.Size() > 1 {
  328. return false
  329. }
  330. addr, _ := state.Validators.GetByIndex(0)
  331. return bytes.Equal(pubKey.Address(), addr)
  332. }
  333. func createMempoolAndMempoolReactor(config *cfg.Config, proxyApp proxy.AppConns,
  334. state sm.State, memplMetrics *mempl.Metrics, logger log.Logger) (*mempl.Reactor, *mempl.CListMempool) {
  335. mempool := mempl.NewCListMempool(
  336. config.Mempool,
  337. proxyApp.Mempool(),
  338. state.LastBlockHeight,
  339. mempl.WithMetrics(memplMetrics),
  340. mempl.WithPreCheck(sm.TxPreCheck(state)),
  341. mempl.WithPostCheck(sm.TxPostCheck(state)),
  342. )
  343. mempoolLogger := logger.With("module", "mempool")
  344. mempoolReactor := mempl.NewReactor(config.Mempool, mempool)
  345. mempoolReactor.SetLogger(mempoolLogger)
  346. if config.Consensus.WaitForTxs() {
  347. mempool.EnableTxsAvailable()
  348. }
  349. return mempoolReactor, mempool
  350. }
  351. func createEvidenceReactor(config *cfg.Config, dbProvider DBProvider,
  352. stateDB dbm.DB, blockStore *store.BlockStore, logger log.Logger) (*evidence.Reactor, *evidence.Pool, error) {
  353. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  354. if err != nil {
  355. return nil, nil, err
  356. }
  357. evidenceLogger := logger.With("module", "evidence")
  358. evidencePool, err := evidence.NewPool(evidenceDB, sm.NewStore(stateDB), blockStore)
  359. if err != nil {
  360. return nil, nil, err
  361. }
  362. evidenceReactor := evidence.NewReactor(evidencePool)
  363. evidenceReactor.SetLogger(evidenceLogger)
  364. return evidenceReactor, evidencePool, nil
  365. }
  366. func createBlockchainReactor(config *cfg.Config,
  367. state sm.State,
  368. blockExec *sm.BlockExecutor,
  369. blockStore *store.BlockStore,
  370. fastSync bool,
  371. logger log.Logger) (bcReactor p2p.Reactor, err error) {
  372. switch config.FastSync.Version {
  373. case "v0":
  374. bcReactor = bcv0.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  375. case "v1":
  376. bcReactor = bcv1.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  377. case "v2":
  378. bcReactor = bcv2.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  379. default:
  380. return nil, fmt.Errorf("unknown fastsync version %s", config.FastSync.Version)
  381. }
  382. bcReactor.SetLogger(logger.With("module", "blockchain"))
  383. return bcReactor, nil
  384. }
  385. func createConsensusReactor(config *cfg.Config,
  386. state sm.State,
  387. blockExec *sm.BlockExecutor,
  388. blockStore sm.BlockStore,
  389. mempool *mempl.CListMempool,
  390. evidencePool *evidence.Pool,
  391. privValidator types.PrivValidator,
  392. csMetrics *consensus.Metrics,
  393. waitSync bool,
  394. eventBus *types.EventBus,
  395. consensusLogger log.Logger,
  396. misbehaviors map[int64]cs.Misbehavior) (*cs.Reactor, *cs.State) {
  397. consensusState := cs.NewState(
  398. config.Consensus,
  399. state.Copy(),
  400. blockExec,
  401. blockStore,
  402. mempool,
  403. evidencePool,
  404. misbehaviors,
  405. cs.StateMetrics(csMetrics),
  406. )
  407. consensusState.SetLogger(consensusLogger)
  408. if privValidator != nil {
  409. consensusState.SetPrivValidator(privValidator)
  410. }
  411. consensusReactor := cs.NewReactor(consensusState, waitSync, cs.ReactorMetrics(csMetrics))
  412. consensusReactor.SetLogger(consensusLogger)
  413. // services which will be publishing and/or subscribing for messages (events)
  414. // consensusReactor will set it on consensusState and blockExecutor
  415. consensusReactor.SetEventBus(eventBus)
  416. return consensusReactor, consensusState
  417. }
  418. func createTransport(
  419. config *cfg.Config,
  420. nodeInfo p2p.NodeInfo,
  421. nodeKey *p2p.NodeKey,
  422. proxyApp proxy.AppConns,
  423. ) (
  424. *p2p.MultiplexTransport,
  425. []p2p.PeerFilterFunc,
  426. ) {
  427. var (
  428. mConnConfig = p2p.MConnConfig(config.P2P)
  429. transport = p2p.NewMultiplexTransport(nodeInfo, *nodeKey, mConnConfig)
  430. connFilters = []p2p.ConnFilterFunc{}
  431. peerFilters = []p2p.PeerFilterFunc{}
  432. )
  433. if !config.P2P.AllowDuplicateIP {
  434. connFilters = append(connFilters, p2p.ConnDuplicateIPFilter())
  435. }
  436. // Filter peers by addr or pubkey with an ABCI query.
  437. // If the query return code is OK, add peer.
  438. if config.FilterPeers {
  439. connFilters = append(
  440. connFilters,
  441. // ABCI query for address filtering.
  442. func(_ p2p.ConnSet, c net.Conn, _ []net.IP) error {
  443. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  444. Path: fmt.Sprintf("/p2p/filter/addr/%s", c.RemoteAddr().String()),
  445. })
  446. if err != nil {
  447. return err
  448. }
  449. if res.IsErr() {
  450. return fmt.Errorf("error querying abci app: %v", res)
  451. }
  452. return nil
  453. },
  454. )
  455. peerFilters = append(
  456. peerFilters,
  457. // ABCI query for ID filtering.
  458. func(_ p2p.IPeerSet, p p2p.Peer) error {
  459. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  460. Path: fmt.Sprintf("/p2p/filter/id/%s", p.ID()),
  461. })
  462. if err != nil {
  463. return err
  464. }
  465. if res.IsErr() {
  466. return fmt.Errorf("error querying abci app: %v", res)
  467. }
  468. return nil
  469. },
  470. )
  471. }
  472. p2p.MultiplexTransportConnFilters(connFilters...)(transport)
  473. // Limit the number of incoming connections.
  474. max := config.P2P.MaxNumInboundPeers + len(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  475. p2p.MultiplexTransportMaxIncomingConnections(max)(transport)
  476. return transport, peerFilters
  477. }
  478. func createSwitch(config *cfg.Config,
  479. transport p2p.Transport,
  480. p2pMetrics *p2p.Metrics,
  481. peerFilters []p2p.PeerFilterFunc,
  482. mempoolReactor *mempl.Reactor,
  483. bcReactor p2p.Reactor,
  484. stateSyncReactor *statesync.Reactor,
  485. consensusReactor *cs.Reactor,
  486. evidenceReactor *evidence.Reactor,
  487. nodeInfo p2p.NodeInfo,
  488. nodeKey *p2p.NodeKey,
  489. p2pLogger log.Logger) *p2p.Switch {
  490. sw := p2p.NewSwitch(
  491. config.P2P,
  492. transport,
  493. p2p.WithMetrics(p2pMetrics),
  494. p2p.SwitchPeerFilters(peerFilters...),
  495. )
  496. sw.SetLogger(p2pLogger)
  497. sw.AddReactor("MEMPOOL", mempoolReactor)
  498. sw.AddReactor("BLOCKCHAIN", bcReactor)
  499. sw.AddReactor("CONSENSUS", consensusReactor)
  500. sw.AddReactor("EVIDENCE", evidenceReactor)
  501. sw.AddReactor("STATESYNC", stateSyncReactor)
  502. sw.SetNodeInfo(nodeInfo)
  503. sw.SetNodeKey(nodeKey)
  504. p2pLogger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", config.NodeKeyFile())
  505. return sw
  506. }
  507. func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch,
  508. p2pLogger log.Logger, nodeKey *p2p.NodeKey) (pex.AddrBook, error) {
  509. addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  510. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  511. // Add ourselves to addrbook to prevent dialing ourselves
  512. if config.P2P.ExternalAddress != "" {
  513. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ExternalAddress))
  514. if err != nil {
  515. return nil, fmt.Errorf("p2p.external_address is incorrect: %w", err)
  516. }
  517. addrBook.AddOurAddress(addr)
  518. }
  519. if config.P2P.ListenAddress != "" {
  520. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID(), config.P2P.ListenAddress))
  521. if err != nil {
  522. return nil, fmt.Errorf("p2p.laddr is incorrect: %w", err)
  523. }
  524. addrBook.AddOurAddress(addr)
  525. }
  526. sw.SetAddrBook(addrBook)
  527. return addrBook, nil
  528. }
  529. func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config,
  530. sw *p2p.Switch, logger log.Logger) *pex.Reactor {
  531. // TODO persistent peers ? so we can have their DNS addrs saved
  532. pexReactor := pex.NewReactor(addrBook,
  533. &pex.ReactorConfig{
  534. Seeds: splitAndTrimEmpty(config.P2P.Seeds, ",", " "),
  535. SeedMode: config.P2P.SeedMode,
  536. // See consensus/reactor.go: blocksToContributeToBecomeGoodPeer 10000
  537. // blocks assuming 10s blocks ~ 28 hours.
  538. // TODO (melekes): make it dynamic based on the actual block latencies
  539. // from the live network.
  540. // https://github.com/tendermint/tendermint/issues/3523
  541. SeedDisconnectWaitPeriod: 28 * time.Hour,
  542. PersistentPeersMaxDialPeriod: config.P2P.PersistentPeersMaxDialPeriod,
  543. })
  544. pexReactor.SetLogger(logger.With("module", "pex"))
  545. sw.AddReactor("PEX", pexReactor)
  546. return pexReactor
  547. }
  548. // startStateSync starts an asynchronous state sync process, then switches to fast sync mode.
  549. func startStateSync(ssR *statesync.Reactor, bcR fastSyncReactor, conR *cs.Reactor,
  550. stateProvider statesync.StateProvider, config *cfg.StateSyncConfig, fastSync bool,
  551. stateStore sm.Store, blockStore *store.BlockStore, state sm.State) error {
  552. ssR.Logger.Info("Starting state sync")
  553. if stateProvider == nil {
  554. var err error
  555. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  556. defer cancel()
  557. stateProvider, err = statesync.NewLightClientStateProvider(
  558. ctx,
  559. state.ChainID, state.Version, state.InitialHeight,
  560. config.RPCServers, light.TrustOptions{
  561. Period: config.TrustPeriod,
  562. Height: config.TrustHeight,
  563. Hash: config.TrustHashBytes(),
  564. }, ssR.Logger.With("module", "light"))
  565. if err != nil {
  566. return fmt.Errorf("failed to set up light client state provider: %w", err)
  567. }
  568. }
  569. go func() {
  570. state, commit, err := ssR.Sync(stateProvider, config.DiscoveryTime)
  571. if err != nil {
  572. ssR.Logger.Error("State sync failed", "err", err)
  573. return
  574. }
  575. err = stateStore.Bootstrap(state)
  576. if err != nil {
  577. ssR.Logger.Error("Failed to bootstrap node with new state", "err", err)
  578. return
  579. }
  580. err = blockStore.SaveSeenCommit(state.LastBlockHeight, commit)
  581. if err != nil {
  582. ssR.Logger.Error("Failed to store last seen commit", "err", err)
  583. return
  584. }
  585. if fastSync {
  586. // FIXME Very ugly to have these metrics bleed through here.
  587. conR.Metrics.StateSyncing.Set(0)
  588. conR.Metrics.FastSyncing.Set(1)
  589. err = bcR.SwitchToFastSync(state)
  590. if err != nil {
  591. ssR.Logger.Error("Failed to switch to fast sync", "err", err)
  592. return
  593. }
  594. } else {
  595. conR.SwitchToConsensus(state, true)
  596. }
  597. }()
  598. return nil
  599. }
  600. // NewNode returns a new, ready to go, Tendermint Node.
  601. func NewNode(config *cfg.Config,
  602. privValidator types.PrivValidator,
  603. nodeKey *p2p.NodeKey,
  604. clientCreator proxy.ClientCreator,
  605. genesisDocProvider GenesisDocProvider,
  606. dbProvider DBProvider,
  607. metricsProvider MetricsProvider,
  608. logger log.Logger,
  609. misbehaviors map[int64]cs.Misbehavior,
  610. options ...Option) (*Node, error) {
  611. blockStore, stateDB, err := initDBs(config, dbProvider)
  612. if err != nil {
  613. return nil, err
  614. }
  615. stateStore := sm.NewStore(stateDB)
  616. state, genDoc, err := LoadStateFromDBOrGenesisDocProvider(stateDB, genesisDocProvider)
  617. if err != nil {
  618. return nil, err
  619. }
  620. // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query).
  621. proxyApp, err := createAndStartProxyAppConns(clientCreator, logger)
  622. if err != nil {
  623. return nil, err
  624. }
  625. // EventBus and IndexerService must be started before the handshake because
  626. // we might need to index the txs of the replayed block as this might not have happened
  627. // when the node stopped last time (i.e. the node stopped after it saved the block
  628. // but before it indexed the txs, or, endblocker panicked)
  629. eventBus, err := createAndStartEventBus(logger)
  630. if err != nil {
  631. return nil, err
  632. }
  633. indexerService, txIndexer, blockIndexer, err := createAndStartIndexerService(config, dbProvider, eventBus, logger)
  634. if err != nil {
  635. return nil, err
  636. }
  637. // If an address is provided, listen on the socket for a connection from an
  638. // external signing process.
  639. if config.PrivValidatorListenAddr != "" {
  640. // FIXME: we should start services inside OnStart
  641. privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, genDoc.ChainID, logger)
  642. if err != nil {
  643. return nil, fmt.Errorf("error with private validator socket client: %w", err)
  644. }
  645. }
  646. pubKey, err := privValidator.GetPubKey()
  647. if err != nil {
  648. return nil, fmt.Errorf("can't get pubkey: %w", err)
  649. }
  650. // Determine whether we should do state and/or fast sync.
  651. // We don't fast-sync when the only validator is us.
  652. fastSync := config.FastSyncMode && !onlyValidatorIsUs(state, pubKey)
  653. stateSync := config.StateSync.Enable && !onlyValidatorIsUs(state, pubKey)
  654. if stateSync && state.LastBlockHeight > 0 {
  655. logger.Info("Found local state with non-zero height, skipping state sync")
  656. stateSync = false
  657. }
  658. // Create the handshaker, which calls RequestInfo, sets the AppVersion on the state,
  659. // and replays any blocks as necessary to sync tendermint with the app.
  660. consensusLogger := logger.With("module", "consensus")
  661. if !stateSync {
  662. if err := doHandshake(stateStore, state, blockStore, genDoc, eventBus, proxyApp, consensusLogger); err != nil {
  663. return nil, err
  664. }
  665. // Reload the state. It will have the Version.Consensus.App set by the
  666. // Handshake, and may have other modifications as well (ie. depending on
  667. // what happened during block replay).
  668. state, err = stateStore.Load()
  669. if err != nil {
  670. return nil, fmt.Errorf("cannot load state: %w", err)
  671. }
  672. }
  673. logNodeStartupInfo(state, pubKey, logger, consensusLogger)
  674. csMetrics, p2pMetrics, memplMetrics, smMetrics := metricsProvider(genDoc.ChainID)
  675. // Make MempoolReactor
  676. mempoolReactor, mempool := createMempoolAndMempoolReactor(config, proxyApp, state, memplMetrics, logger)
  677. // Make Evidence Reactor
  678. evidenceReactor, evidencePool, err := createEvidenceReactor(config, dbProvider, stateDB, blockStore, logger)
  679. if err != nil {
  680. return nil, err
  681. }
  682. // make block executor for consensus and blockchain reactors to execute blocks
  683. blockExec := sm.NewBlockExecutor(
  684. stateStore,
  685. logger.With("module", "state"),
  686. proxyApp.Consensus(),
  687. mempool,
  688. evidencePool,
  689. sm.BlockExecutorWithMetrics(smMetrics),
  690. )
  691. // Make BlockchainReactor. Don't start fast sync if we're doing a state sync first.
  692. bcReactor, err := createBlockchainReactor(config, state, blockExec, blockStore, fastSync && !stateSync, logger)
  693. if err != nil {
  694. return nil, fmt.Errorf("could not create blockchain reactor: %w", err)
  695. }
  696. // Make ConsensusReactor. Don't enable fully if doing a state sync and/or fast sync first.
  697. // FIXME We need to update metrics here, since other reactors don't have access to them.
  698. if stateSync {
  699. csMetrics.StateSyncing.Set(1)
  700. } else if fastSync {
  701. csMetrics.FastSyncing.Set(1)
  702. }
  703. logger.Info("Setting up maverick consensus reactor", "Misbehaviors", misbehaviors)
  704. consensusReactor, consensusState := createConsensusReactor(
  705. config, state, blockExec, blockStore, mempool, evidencePool,
  706. privValidator, csMetrics, stateSync || fastSync, eventBus, consensusLogger, misbehaviors)
  707. // Set up state sync reactor, and schedule a sync if requested.
  708. // FIXME The way we do phased startups (e.g. replay -> fast sync -> consensus) is very messy,
  709. // we should clean this whole thing up. See:
  710. // https://github.com/tendermint/tendermint/issues/4644
  711. stateSyncReactor := statesync.NewReactor(
  712. *config.StateSync,
  713. proxyApp.Snapshot(),
  714. proxyApp.Query(),
  715. config.StateSync.TempDir,
  716. )
  717. stateSyncReactor.SetLogger(logger.With("module", "statesync"))
  718. nodeInfo, err := makeNodeInfo(config, nodeKey, txIndexer, genDoc, state)
  719. if err != nil {
  720. return nil, err
  721. }
  722. // Setup Transport.
  723. transport, peerFilters := createTransport(config, nodeInfo, nodeKey, proxyApp)
  724. // Setup Switch.
  725. p2pLogger := logger.With("module", "p2p")
  726. sw := createSwitch(
  727. config, transport, p2pMetrics, peerFilters, mempoolReactor, bcReactor,
  728. stateSyncReactor, consensusReactor, evidenceReactor, nodeInfo, nodeKey, p2pLogger,
  729. )
  730. err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
  731. if err != nil {
  732. return nil, fmt.Errorf("could not add peers from persistent_peers field: %w", err)
  733. }
  734. err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  735. if err != nil {
  736. return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
  737. }
  738. addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
  739. if err != nil {
  740. return nil, fmt.Errorf("could not create addrbook: %w", err)
  741. }
  742. // Optionally, start the pex reactor
  743. //
  744. // TODO:
  745. //
  746. // We need to set Seeds and PersistentPeers on the switch,
  747. // since it needs to be able to use these (and their DNS names)
  748. // even if the PEX is off. We can include the DNS name in the NetAddress,
  749. // but it would still be nice to have a clear list of the current "PersistentPeers"
  750. // somewhere that we can return with net_info.
  751. //
  752. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  753. // Note we currently use the addrBook regardless at least for AddOurAddress
  754. var pexReactor *pex.Reactor
  755. if config.P2P.PexReactor {
  756. pexReactor = createPEXReactorAndAddToSwitch(addrBook, config, sw, logger)
  757. }
  758. if config.RPC.PprofListenAddress != "" {
  759. go func() {
  760. logger.Info("Starting pprof server", "laddr", config.RPC.PprofListenAddress)
  761. logger.Error("pprof server error", "err", http.ListenAndServe(config.RPC.PprofListenAddress, nil))
  762. }()
  763. }
  764. node := &Node{
  765. config: config,
  766. genesisDoc: genDoc,
  767. privValidator: privValidator,
  768. transport: transport,
  769. sw: sw,
  770. addrBook: addrBook,
  771. nodeInfo: nodeInfo,
  772. nodeKey: nodeKey,
  773. stateStore: stateStore,
  774. blockStore: blockStore,
  775. bcReactor: bcReactor,
  776. mempoolReactor: mempoolReactor,
  777. mempool: mempool,
  778. consensusState: consensusState,
  779. consensusReactor: consensusReactor,
  780. stateSyncReactor: stateSyncReactor,
  781. stateSync: stateSync,
  782. stateSyncGenesis: state, // Shouldn't be necessary, but need a way to pass the genesis state
  783. pexReactor: pexReactor,
  784. evidencePool: evidencePool,
  785. proxyApp: proxyApp,
  786. txIndexer: txIndexer,
  787. indexerService: indexerService,
  788. blockIndexer: blockIndexer,
  789. eventBus: eventBus,
  790. }
  791. node.BaseService = *service.NewBaseService(logger, "Node", node)
  792. for _, option := range options {
  793. option(node)
  794. }
  795. return node, nil
  796. }
  797. // OnStart starts the Node. It implements service.Service.
  798. func (n *Node) OnStart() error {
  799. now := tmtime.Now()
  800. genTime := n.genesisDoc.GenesisTime
  801. if genTime.After(now) {
  802. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  803. time.Sleep(genTime.Sub(now))
  804. }
  805. // Add private IDs to addrbook to block those peers being added
  806. n.addrBook.AddPrivateIDs(splitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  807. // Start the RPC server before the P2P server
  808. // so we can eg. receive txs for the first block
  809. if n.config.RPC.ListenAddress != "" {
  810. listeners, err := n.startRPC()
  811. if err != nil {
  812. return err
  813. }
  814. n.rpcListeners = listeners
  815. }
  816. if n.config.Instrumentation.Prometheus &&
  817. n.config.Instrumentation.PrometheusListenAddr != "" {
  818. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  819. }
  820. // Start the transport.
  821. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(n.nodeKey.ID(), n.config.P2P.ListenAddress))
  822. if err != nil {
  823. return err
  824. }
  825. if err := n.transport.Listen(*addr); err != nil {
  826. return err
  827. }
  828. n.isListening = true
  829. if n.config.Mempool.WalEnabled() {
  830. err = n.mempool.InitWAL()
  831. if err != nil {
  832. return fmt.Errorf("init mempool WAL: %w", err)
  833. }
  834. }
  835. // Start the switch (the P2P server).
  836. err = n.sw.Start()
  837. if err != nil {
  838. return err
  839. }
  840. // Always connect to persistent peers
  841. err = n.sw.DialPeersAsync(splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "))
  842. if err != nil {
  843. return fmt.Errorf("could not dial peers from persistent_peers field: %w", err)
  844. }
  845. // Run state sync
  846. if n.stateSync {
  847. bcR, ok := n.bcReactor.(fastSyncReactor)
  848. if !ok {
  849. return fmt.Errorf("this blockchain reactor does not support switching from state sync")
  850. }
  851. err := startStateSync(n.stateSyncReactor, bcR, n.consensusReactor, n.stateSyncProvider,
  852. n.config.StateSync, n.config.FastSyncMode, n.stateStore, n.blockStore, n.stateSyncGenesis)
  853. if err != nil {
  854. return fmt.Errorf("failed to start state sync: %w", err)
  855. }
  856. }
  857. return nil
  858. }
  859. // OnStop stops the Node. It implements service.Service.
  860. func (n *Node) OnStop() {
  861. n.BaseService.OnStop()
  862. n.Logger.Info("Stopping Node")
  863. // first stop the non-reactor services
  864. if err := n.eventBus.Stop(); err != nil {
  865. n.Logger.Error("Error closing eventBus", "err", err)
  866. }
  867. if err := n.indexerService.Stop(); err != nil {
  868. n.Logger.Error("Error closing indexerService", "err", err)
  869. }
  870. // now stop the reactors
  871. if err := n.sw.Stop(); err != nil {
  872. n.Logger.Error("Error closing switch", "err", err)
  873. }
  874. // stop mempool WAL
  875. if n.config.Mempool.WalEnabled() {
  876. n.mempool.CloseWAL()
  877. }
  878. if err := n.transport.Close(); err != nil {
  879. n.Logger.Error("Error closing transport", "err", err)
  880. }
  881. n.isListening = false
  882. // finally stop the listeners / external services
  883. for _, l := range n.rpcListeners {
  884. n.Logger.Info("Closing rpc listener", "listener", l)
  885. if err := l.Close(); err != nil {
  886. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  887. }
  888. }
  889. if pvsc, ok := n.privValidator.(service.Service); ok {
  890. if err := pvsc.Stop(); err != nil {
  891. n.Logger.Error("Error closing private validator", "err", err)
  892. }
  893. }
  894. if n.prometheusSrv != nil {
  895. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  896. // Error from closing listeners, or context timeout:
  897. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  898. }
  899. }
  900. }
  901. // ConfigureRPC makes sure RPC has all the objects it needs to operate.
  902. func (n *Node) ConfigureRPC() error {
  903. pubKey, err := n.privValidator.GetPubKey()
  904. if err != nil {
  905. return fmt.Errorf("can't get pubkey: %w", err)
  906. }
  907. rpccore.SetEnvironment(&rpccore.Environment{
  908. ProxyAppQuery: n.proxyApp.Query(),
  909. ProxyAppMempool: n.proxyApp.Mempool(),
  910. StateStore: n.stateStore,
  911. BlockStore: n.blockStore,
  912. EvidencePool: n.evidencePool,
  913. ConsensusState: n.consensusState,
  914. P2PPeers: n.sw,
  915. P2PTransport: n,
  916. PubKey: pubKey,
  917. GenDoc: n.genesisDoc,
  918. TxIndexer: n.txIndexer,
  919. BlockIndexer: n.blockIndexer,
  920. ConsensusReactor: &consensus.Reactor{},
  921. EventBus: n.eventBus,
  922. Mempool: n.mempool,
  923. Logger: n.Logger.With("module", "rpc"),
  924. Config: *n.config.RPC,
  925. })
  926. return nil
  927. }
  928. func (n *Node) startRPC() ([]net.Listener, error) {
  929. err := n.ConfigureRPC()
  930. if err != nil {
  931. return nil, err
  932. }
  933. listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  934. if n.config.RPC.Unsafe {
  935. rpccore.AddUnsafeRoutes()
  936. }
  937. config := rpcserver.DefaultConfig()
  938. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  939. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  940. config.MaxOpenConnections = n.config.RPC.MaxOpenConnections
  941. // If necessary adjust global WriteTimeout to ensure it's greater than
  942. // TimeoutBroadcastTxCommit.
  943. // See https://github.com/tendermint/tendermint/issues/3435
  944. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  945. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  946. }
  947. // we may expose the rpc over both a unix and tcp socket
  948. listeners := make([]net.Listener, len(listenAddrs))
  949. for i, listenAddr := range listenAddrs {
  950. mux := http.NewServeMux()
  951. rpcLogger := n.Logger.With("module", "rpc-server")
  952. wmLogger := rpcLogger.With("protocol", "websocket")
  953. wm := rpcserver.NewWebsocketManager(rpccore.Routes,
  954. rpcserver.OnDisconnect(func(remoteAddr string) {
  955. err := n.eventBus.UnsubscribeAll(context.Background(), remoteAddr)
  956. if err != nil && err != tmpubsub.ErrSubscriptionNotFound {
  957. wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err)
  958. }
  959. }),
  960. rpcserver.ReadLimit(config.MaxBodyBytes),
  961. )
  962. wm.SetLogger(wmLogger)
  963. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  964. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  965. listener, err := rpcserver.Listen(
  966. listenAddr,
  967. config,
  968. )
  969. if err != nil {
  970. return nil, err
  971. }
  972. var rootHandler http.Handler = mux
  973. if n.config.RPC.IsCorsEnabled() {
  974. corsMiddleware := cors.New(cors.Options{
  975. AllowedOrigins: n.config.RPC.CORSAllowedOrigins,
  976. AllowedMethods: n.config.RPC.CORSAllowedMethods,
  977. AllowedHeaders: n.config.RPC.CORSAllowedHeaders,
  978. })
  979. rootHandler = corsMiddleware.Handler(mux)
  980. }
  981. if n.config.RPC.IsTLSEnabled() {
  982. go func() {
  983. if err := rpcserver.ServeTLS(
  984. listener,
  985. rootHandler,
  986. n.config.RPC.CertFile(),
  987. n.config.RPC.KeyFile(),
  988. rpcLogger,
  989. config,
  990. ); err != nil {
  991. n.Logger.Error("Error serving server with TLS", "err", err)
  992. }
  993. }()
  994. } else {
  995. go func() {
  996. if err := rpcserver.Serve(
  997. listener,
  998. rootHandler,
  999. rpcLogger,
  1000. config,
  1001. ); err != nil {
  1002. n.Logger.Error("Error serving server", "err", err)
  1003. }
  1004. }()
  1005. }
  1006. listeners[i] = listener
  1007. }
  1008. // we expose a simplified api over grpc for convenience to app devs
  1009. grpcListenAddr := n.config.RPC.GRPCListenAddress
  1010. if grpcListenAddr != "" {
  1011. config := rpcserver.DefaultConfig()
  1012. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  1013. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  1014. // NOTE: GRPCMaxOpenConnections is used, not MaxOpenConnections
  1015. config.MaxOpenConnections = n.config.RPC.GRPCMaxOpenConnections
  1016. // If necessary adjust global WriteTimeout to ensure it's greater than
  1017. // TimeoutBroadcastTxCommit.
  1018. // See https://github.com/tendermint/tendermint/issues/3435
  1019. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  1020. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  1021. }
  1022. listener, err := rpcserver.Listen(grpcListenAddr, config)
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. go func() {
  1027. if err := grpccore.StartGRPCServer(listener); err != nil {
  1028. n.Logger.Error("Error starting gRPC server", "err", err)
  1029. }
  1030. }()
  1031. listeners = append(listeners, listener)
  1032. }
  1033. return listeners, nil
  1034. }
  1035. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  1036. // collectors on addr.
  1037. func (n *Node) startPrometheusServer(addr string) *http.Server {
  1038. srv := &http.Server{
  1039. Addr: addr,
  1040. Handler: promhttp.InstrumentMetricHandler(
  1041. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  1042. prometheus.DefaultGatherer,
  1043. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  1044. ),
  1045. ),
  1046. }
  1047. go func() {
  1048. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  1049. // Error starting or closing listener:
  1050. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  1051. }
  1052. }()
  1053. return srv
  1054. }
  1055. // Switch returns the Node's Switch.
  1056. func (n *Node) Switch() *p2p.Switch {
  1057. return n.sw
  1058. }
  1059. // BlockStore returns the Node's BlockStore.
  1060. func (n *Node) BlockStore() *store.BlockStore {
  1061. return n.blockStore
  1062. }
  1063. // ConsensusState returns the Node's ConsensusState.
  1064. func (n *Node) ConsensusState() *cs.State {
  1065. return n.consensusState
  1066. }
  1067. // ConsensusReactor returns the Node's ConsensusReactor.
  1068. func (n *Node) ConsensusReactor() *cs.Reactor {
  1069. return n.consensusReactor
  1070. }
  1071. // MempoolReactor returns the Node's mempool reactor.
  1072. func (n *Node) MempoolReactor() *mempl.Reactor {
  1073. return n.mempoolReactor
  1074. }
  1075. // Mempool returns the Node's mempool.
  1076. func (n *Node) Mempool() mempl.Mempool {
  1077. return n.mempool
  1078. }
  1079. // PEXReactor returns the Node's PEXReactor. It returns nil if PEX is disabled.
  1080. func (n *Node) PEXReactor() *pex.Reactor {
  1081. return n.pexReactor
  1082. }
  1083. // EvidencePool returns the Node's EvidencePool.
  1084. func (n *Node) EvidencePool() *evidence.Pool {
  1085. return n.evidencePool
  1086. }
  1087. // EventBus returns the Node's EventBus.
  1088. func (n *Node) EventBus() *types.EventBus {
  1089. return n.eventBus
  1090. }
  1091. // PrivValidator returns the Node's PrivValidator.
  1092. // XXX: for convenience only!
  1093. func (n *Node) PrivValidator() types.PrivValidator {
  1094. return n.privValidator
  1095. }
  1096. // GenesisDoc returns the Node's GenesisDoc.
  1097. func (n *Node) GenesisDoc() *types.GenesisDoc {
  1098. return n.genesisDoc
  1099. }
  1100. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  1101. func (n *Node) ProxyApp() proxy.AppConns {
  1102. return n.proxyApp
  1103. }
  1104. // Config returns the Node's config.
  1105. func (n *Node) Config() *cfg.Config {
  1106. return n.config
  1107. }
  1108. //------------------------------------------------------------------------------
  1109. func (n *Node) Listeners() []string {
  1110. return []string{
  1111. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  1112. }
  1113. }
  1114. func (n *Node) IsListening() bool {
  1115. return n.isListening
  1116. }
  1117. // NodeInfo returns the Node's Info from the Switch.
  1118. func (n *Node) NodeInfo() p2p.NodeInfo {
  1119. return n.nodeInfo
  1120. }
  1121. func makeNodeInfo(
  1122. config *cfg.Config,
  1123. nodeKey *p2p.NodeKey,
  1124. txIndexer txindex.TxIndexer,
  1125. genDoc *types.GenesisDoc,
  1126. state sm.State,
  1127. ) (p2p.NodeInfo, error) {
  1128. txIndexerStatus := "on"
  1129. if _, ok := txIndexer.(*null.TxIndex); ok {
  1130. txIndexerStatus = "off"
  1131. }
  1132. var bcChannel byte
  1133. switch config.FastSync.Version {
  1134. case "v0":
  1135. bcChannel = bcv0.BlockchainChannel
  1136. case "v1":
  1137. bcChannel = bcv1.BlockchainChannel
  1138. case "v2":
  1139. bcChannel = bcv2.BlockchainChannel
  1140. default:
  1141. return nil, fmt.Errorf("unknown fastsync version %s", config.FastSync.Version)
  1142. }
  1143. nodeInfo := p2p.DefaultNodeInfo{
  1144. ProtocolVersion: p2p.NewProtocolVersion(
  1145. version.P2PProtocol, // global
  1146. state.Version.Consensus.Block,
  1147. state.Version.Consensus.App,
  1148. ),
  1149. DefaultNodeID: nodeKey.ID(),
  1150. Network: genDoc.ChainID,
  1151. Version: version.TMCoreSemVer,
  1152. Channels: []byte{
  1153. bcChannel,
  1154. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  1155. mempl.MempoolChannel,
  1156. evidence.EvidenceChannel,
  1157. statesync.SnapshotChannel, statesync.ChunkChannel,
  1158. },
  1159. Moniker: config.Moniker,
  1160. Other: p2p.DefaultNodeInfoOther{
  1161. TxIndex: txIndexerStatus,
  1162. RPCAddress: config.RPC.ListenAddress,
  1163. },
  1164. }
  1165. if config.P2P.PexReactor {
  1166. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  1167. }
  1168. lAddr := config.P2P.ExternalAddress
  1169. if lAddr == "" {
  1170. lAddr = config.P2P.ListenAddress
  1171. }
  1172. nodeInfo.ListenAddr = lAddr
  1173. err := nodeInfo.Validate()
  1174. return nodeInfo, err
  1175. }
  1176. //------------------------------------------------------------------------------
  1177. var (
  1178. genesisDocKey = []byte("genesisDoc")
  1179. )
  1180. // LoadStateFromDBOrGenesisDocProvider attempts to load the state from the
  1181. // database, or creates one using the given genesisDocProvider and persists the
  1182. // result to the database. On success this also returns the genesis doc loaded
  1183. // through the given provider.
  1184. func LoadStateFromDBOrGenesisDocProvider(
  1185. stateDB dbm.DB,
  1186. genesisDocProvider GenesisDocProvider,
  1187. ) (sm.State, *types.GenesisDoc, error) {
  1188. // Get genesis doc
  1189. genDoc, err := loadGenesisDoc(stateDB)
  1190. if err != nil {
  1191. genDoc, err = genesisDocProvider()
  1192. if err != nil {
  1193. return sm.State{}, nil, err
  1194. }
  1195. // save genesis doc to prevent a certain class of user errors (e.g. when it
  1196. // was changed, accidentally or not). Also good for audit trail.
  1197. saveGenesisDoc(stateDB, genDoc)
  1198. }
  1199. stateStore := sm.NewStore(stateDB)
  1200. state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc)
  1201. if err != nil {
  1202. return sm.State{}, nil, err
  1203. }
  1204. return state, genDoc, nil
  1205. }
  1206. // panics if failed to unmarshal bytes
  1207. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  1208. b, err := db.Get(genesisDocKey)
  1209. if err != nil {
  1210. panic(err)
  1211. }
  1212. if len(b) == 0 {
  1213. return nil, errors.New("genesis doc not found")
  1214. }
  1215. var genDoc *types.GenesisDoc
  1216. err = tmjson.Unmarshal(b, &genDoc)
  1217. if err != nil {
  1218. panic(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, b))
  1219. }
  1220. return genDoc, nil
  1221. }
  1222. // panics if failed to marshal the given genesis document
  1223. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  1224. b, err := tmjson.Marshal(genDoc)
  1225. if err != nil {
  1226. panic(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  1227. }
  1228. if err := db.SetSync(genesisDocKey, b); err != nil {
  1229. panic(fmt.Sprintf("Failed to save genesis doc: %v", err))
  1230. }
  1231. }
  1232. func createAndStartPrivValidatorSocketClient(
  1233. listenAddr,
  1234. chainID string,
  1235. logger log.Logger,
  1236. ) (types.PrivValidator, error) {
  1237. pve, err := privval.NewSignerListener(listenAddr, logger)
  1238. if err != nil {
  1239. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1240. }
  1241. pvsc, err := privval.NewSignerClient(pve, chainID)
  1242. if err != nil {
  1243. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1244. }
  1245. // try to get a pubkey from private validate first time
  1246. _, err = pvsc.GetPubKey()
  1247. if err != nil {
  1248. return nil, fmt.Errorf("can't get pubkey: %w", err)
  1249. }
  1250. const (
  1251. retries = 50 // 50 * 100ms = 5s total
  1252. timeout = 100 * time.Millisecond
  1253. )
  1254. pvscWithRetries := privval.NewRetrySignerClient(pvsc, retries, timeout)
  1255. return pvscWithRetries, nil
  1256. }
  1257. // splitAndTrimEmpty slices s into all subslices separated by sep and returns a
  1258. // slice of the string s with all leading and trailing Unicode code points
  1259. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  1260. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  1261. // -1. also filter out empty strings, only return non-empty strings.
  1262. func splitAndTrimEmpty(s, sep, cutset string) []string {
  1263. if s == "" {
  1264. return []string{}
  1265. }
  1266. spl := strings.Split(s, sep)
  1267. nonEmptyStrings := make([]string, 0, len(spl))
  1268. for i := 0; i < len(spl); i++ {
  1269. element := strings.Trim(spl[i], cutset)
  1270. if element != "" {
  1271. nonEmptyStrings = append(nonEmptyStrings, element)
  1272. }
  1273. }
  1274. return nonEmptyStrings
  1275. }