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.

1458 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(proxyApp.Snapshot(), proxyApp.Query(),
  712. config.StateSync.TempDir)
  713. stateSyncReactor.SetLogger(logger.With("module", "statesync"))
  714. nodeInfo, err := makeNodeInfo(config, nodeKey, txIndexer, genDoc, state)
  715. if err != nil {
  716. return nil, err
  717. }
  718. // Setup Transport.
  719. transport, peerFilters := createTransport(config, nodeInfo, nodeKey, proxyApp)
  720. // Setup Switch.
  721. p2pLogger := logger.With("module", "p2p")
  722. sw := createSwitch(
  723. config, transport, p2pMetrics, peerFilters, mempoolReactor, bcReactor,
  724. stateSyncReactor, consensusReactor, evidenceReactor, nodeInfo, nodeKey, p2pLogger,
  725. )
  726. err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
  727. if err != nil {
  728. return nil, fmt.Errorf("could not add peers from persistent_peers field: %w", err)
  729. }
  730. err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  731. if err != nil {
  732. return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
  733. }
  734. addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
  735. if err != nil {
  736. return nil, fmt.Errorf("could not create addrbook: %w", err)
  737. }
  738. // Optionally, start the pex reactor
  739. //
  740. // TODO:
  741. //
  742. // We need to set Seeds and PersistentPeers on the switch,
  743. // since it needs to be able to use these (and their DNS names)
  744. // even if the PEX is off. We can include the DNS name in the NetAddress,
  745. // but it would still be nice to have a clear list of the current "PersistentPeers"
  746. // somewhere that we can return with net_info.
  747. //
  748. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  749. // Note we currently use the addrBook regardless at least for AddOurAddress
  750. var pexReactor *pex.Reactor
  751. if config.P2P.PexReactor {
  752. pexReactor = createPEXReactorAndAddToSwitch(addrBook, config, sw, logger)
  753. }
  754. if config.RPC.PprofListenAddress != "" {
  755. go func() {
  756. logger.Info("Starting pprof server", "laddr", config.RPC.PprofListenAddress)
  757. logger.Error("pprof server error", "err", http.ListenAndServe(config.RPC.PprofListenAddress, nil))
  758. }()
  759. }
  760. node := &Node{
  761. config: config,
  762. genesisDoc: genDoc,
  763. privValidator: privValidator,
  764. transport: transport,
  765. sw: sw,
  766. addrBook: addrBook,
  767. nodeInfo: nodeInfo,
  768. nodeKey: nodeKey,
  769. stateStore: stateStore,
  770. blockStore: blockStore,
  771. bcReactor: bcReactor,
  772. mempoolReactor: mempoolReactor,
  773. mempool: mempool,
  774. consensusState: consensusState,
  775. consensusReactor: consensusReactor,
  776. stateSyncReactor: stateSyncReactor,
  777. stateSync: stateSync,
  778. stateSyncGenesis: state, // Shouldn't be necessary, but need a way to pass the genesis state
  779. pexReactor: pexReactor,
  780. evidencePool: evidencePool,
  781. proxyApp: proxyApp,
  782. txIndexer: txIndexer,
  783. indexerService: indexerService,
  784. blockIndexer: blockIndexer,
  785. eventBus: eventBus,
  786. }
  787. node.BaseService = *service.NewBaseService(logger, "Node", node)
  788. for _, option := range options {
  789. option(node)
  790. }
  791. return node, nil
  792. }
  793. // OnStart starts the Node. It implements service.Service.
  794. func (n *Node) OnStart() error {
  795. now := tmtime.Now()
  796. genTime := n.genesisDoc.GenesisTime
  797. if genTime.After(now) {
  798. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  799. time.Sleep(genTime.Sub(now))
  800. }
  801. // Add private IDs to addrbook to block those peers being added
  802. n.addrBook.AddPrivateIDs(splitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  803. // Start the RPC server before the P2P server
  804. // so we can eg. receive txs for the first block
  805. if n.config.RPC.ListenAddress != "" {
  806. listeners, err := n.startRPC()
  807. if err != nil {
  808. return err
  809. }
  810. n.rpcListeners = listeners
  811. }
  812. if n.config.Instrumentation.Prometheus &&
  813. n.config.Instrumentation.PrometheusListenAddr != "" {
  814. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  815. }
  816. // Start the transport.
  817. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(n.nodeKey.ID(), n.config.P2P.ListenAddress))
  818. if err != nil {
  819. return err
  820. }
  821. if err := n.transport.Listen(*addr); err != nil {
  822. return err
  823. }
  824. n.isListening = true
  825. if n.config.Mempool.WalEnabled() {
  826. err = n.mempool.InitWAL()
  827. if err != nil {
  828. return fmt.Errorf("init mempool WAL: %w", err)
  829. }
  830. }
  831. // Start the switch (the P2P server).
  832. err = n.sw.Start()
  833. if err != nil {
  834. return err
  835. }
  836. // Always connect to persistent peers
  837. err = n.sw.DialPeersAsync(splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "))
  838. if err != nil {
  839. return fmt.Errorf("could not dial peers from persistent_peers field: %w", err)
  840. }
  841. // Run state sync
  842. if n.stateSync {
  843. bcR, ok := n.bcReactor.(fastSyncReactor)
  844. if !ok {
  845. return fmt.Errorf("this blockchain reactor does not support switching from state sync")
  846. }
  847. err := startStateSync(n.stateSyncReactor, bcR, n.consensusReactor, n.stateSyncProvider,
  848. n.config.StateSync, n.config.FastSyncMode, n.stateStore, n.blockStore, n.stateSyncGenesis)
  849. if err != nil {
  850. return fmt.Errorf("failed to start state sync: %w", err)
  851. }
  852. }
  853. return nil
  854. }
  855. // OnStop stops the Node. It implements service.Service.
  856. func (n *Node) OnStop() {
  857. n.BaseService.OnStop()
  858. n.Logger.Info("Stopping Node")
  859. // first stop the non-reactor services
  860. if err := n.eventBus.Stop(); err != nil {
  861. n.Logger.Error("Error closing eventBus", "err", err)
  862. }
  863. if err := n.indexerService.Stop(); err != nil {
  864. n.Logger.Error("Error closing indexerService", "err", err)
  865. }
  866. // now stop the reactors
  867. if err := n.sw.Stop(); err != nil {
  868. n.Logger.Error("Error closing switch", "err", err)
  869. }
  870. // stop mempool WAL
  871. if n.config.Mempool.WalEnabled() {
  872. n.mempool.CloseWAL()
  873. }
  874. if err := n.transport.Close(); err != nil {
  875. n.Logger.Error("Error closing transport", "err", err)
  876. }
  877. n.isListening = false
  878. // finally stop the listeners / external services
  879. for _, l := range n.rpcListeners {
  880. n.Logger.Info("Closing rpc listener", "listener", l)
  881. if err := l.Close(); err != nil {
  882. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  883. }
  884. }
  885. if pvsc, ok := n.privValidator.(service.Service); ok {
  886. if err := pvsc.Stop(); err != nil {
  887. n.Logger.Error("Error closing private validator", "err", err)
  888. }
  889. }
  890. if n.prometheusSrv != nil {
  891. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  892. // Error from closing listeners, or context timeout:
  893. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  894. }
  895. }
  896. }
  897. // ConfigureRPC makes sure RPC has all the objects it needs to operate.
  898. func (n *Node) ConfigureRPC() error {
  899. pubKey, err := n.privValidator.GetPubKey()
  900. if err != nil {
  901. return fmt.Errorf("can't get pubkey: %w", err)
  902. }
  903. rpccore.SetEnvironment(&rpccore.Environment{
  904. ProxyAppQuery: n.proxyApp.Query(),
  905. ProxyAppMempool: n.proxyApp.Mempool(),
  906. StateStore: n.stateStore,
  907. BlockStore: n.blockStore,
  908. EvidencePool: n.evidencePool,
  909. ConsensusState: n.consensusState,
  910. P2PPeers: n.sw,
  911. P2PTransport: n,
  912. PubKey: pubKey,
  913. GenDoc: n.genesisDoc,
  914. TxIndexer: n.txIndexer,
  915. BlockIndexer: n.blockIndexer,
  916. ConsensusReactor: &consensus.Reactor{},
  917. EventBus: n.eventBus,
  918. Mempool: n.mempool,
  919. Logger: n.Logger.With("module", "rpc"),
  920. Config: *n.config.RPC,
  921. })
  922. return nil
  923. }
  924. func (n *Node) startRPC() ([]net.Listener, error) {
  925. err := n.ConfigureRPC()
  926. if err != nil {
  927. return nil, err
  928. }
  929. listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  930. if n.config.RPC.Unsafe {
  931. rpccore.AddUnsafeRoutes()
  932. }
  933. config := rpcserver.DefaultConfig()
  934. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  935. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  936. config.MaxOpenConnections = n.config.RPC.MaxOpenConnections
  937. // If necessary adjust global WriteTimeout to ensure it's greater than
  938. // TimeoutBroadcastTxCommit.
  939. // See https://github.com/tendermint/tendermint/issues/3435
  940. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  941. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  942. }
  943. // we may expose the rpc over both a unix and tcp socket
  944. listeners := make([]net.Listener, len(listenAddrs))
  945. for i, listenAddr := range listenAddrs {
  946. mux := http.NewServeMux()
  947. rpcLogger := n.Logger.With("module", "rpc-server")
  948. wmLogger := rpcLogger.With("protocol", "websocket")
  949. wm := rpcserver.NewWebsocketManager(rpccore.Routes,
  950. rpcserver.OnDisconnect(func(remoteAddr string) {
  951. err := n.eventBus.UnsubscribeAll(context.Background(), remoteAddr)
  952. if err != nil && err != tmpubsub.ErrSubscriptionNotFound {
  953. wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err)
  954. }
  955. }),
  956. rpcserver.ReadLimit(config.MaxBodyBytes),
  957. )
  958. wm.SetLogger(wmLogger)
  959. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  960. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  961. listener, err := rpcserver.Listen(
  962. listenAddr,
  963. config,
  964. )
  965. if err != nil {
  966. return nil, err
  967. }
  968. var rootHandler http.Handler = mux
  969. if n.config.RPC.IsCorsEnabled() {
  970. corsMiddleware := cors.New(cors.Options{
  971. AllowedOrigins: n.config.RPC.CORSAllowedOrigins,
  972. AllowedMethods: n.config.RPC.CORSAllowedMethods,
  973. AllowedHeaders: n.config.RPC.CORSAllowedHeaders,
  974. })
  975. rootHandler = corsMiddleware.Handler(mux)
  976. }
  977. if n.config.RPC.IsTLSEnabled() {
  978. go func() {
  979. if err := rpcserver.ServeTLS(
  980. listener,
  981. rootHandler,
  982. n.config.RPC.CertFile(),
  983. n.config.RPC.KeyFile(),
  984. rpcLogger,
  985. config,
  986. ); err != nil {
  987. n.Logger.Error("Error serving server with TLS", "err", err)
  988. }
  989. }()
  990. } else {
  991. go func() {
  992. if err := rpcserver.Serve(
  993. listener,
  994. rootHandler,
  995. rpcLogger,
  996. config,
  997. ); err != nil {
  998. n.Logger.Error("Error serving server", "err", err)
  999. }
  1000. }()
  1001. }
  1002. listeners[i] = listener
  1003. }
  1004. // we expose a simplified api over grpc for convenience to app devs
  1005. grpcListenAddr := n.config.RPC.GRPCListenAddress
  1006. if grpcListenAddr != "" {
  1007. config := rpcserver.DefaultConfig()
  1008. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  1009. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  1010. // NOTE: GRPCMaxOpenConnections is used, not MaxOpenConnections
  1011. config.MaxOpenConnections = n.config.RPC.GRPCMaxOpenConnections
  1012. // If necessary adjust global WriteTimeout to ensure it's greater than
  1013. // TimeoutBroadcastTxCommit.
  1014. // See https://github.com/tendermint/tendermint/issues/3435
  1015. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  1016. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  1017. }
  1018. listener, err := rpcserver.Listen(grpcListenAddr, config)
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. go func() {
  1023. if err := grpccore.StartGRPCServer(listener); err != nil {
  1024. n.Logger.Error("Error starting gRPC server", "err", err)
  1025. }
  1026. }()
  1027. listeners = append(listeners, listener)
  1028. }
  1029. return listeners, nil
  1030. }
  1031. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  1032. // collectors on addr.
  1033. func (n *Node) startPrometheusServer(addr string) *http.Server {
  1034. srv := &http.Server{
  1035. Addr: addr,
  1036. Handler: promhttp.InstrumentMetricHandler(
  1037. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  1038. prometheus.DefaultGatherer,
  1039. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  1040. ),
  1041. ),
  1042. }
  1043. go func() {
  1044. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  1045. // Error starting or closing listener:
  1046. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  1047. }
  1048. }()
  1049. return srv
  1050. }
  1051. // Switch returns the Node's Switch.
  1052. func (n *Node) Switch() *p2p.Switch {
  1053. return n.sw
  1054. }
  1055. // BlockStore returns the Node's BlockStore.
  1056. func (n *Node) BlockStore() *store.BlockStore {
  1057. return n.blockStore
  1058. }
  1059. // ConsensusState returns the Node's ConsensusState.
  1060. func (n *Node) ConsensusState() *cs.State {
  1061. return n.consensusState
  1062. }
  1063. // ConsensusReactor returns the Node's ConsensusReactor.
  1064. func (n *Node) ConsensusReactor() *cs.Reactor {
  1065. return n.consensusReactor
  1066. }
  1067. // MempoolReactor returns the Node's mempool reactor.
  1068. func (n *Node) MempoolReactor() *mempl.Reactor {
  1069. return n.mempoolReactor
  1070. }
  1071. // Mempool returns the Node's mempool.
  1072. func (n *Node) Mempool() mempl.Mempool {
  1073. return n.mempool
  1074. }
  1075. // PEXReactor returns the Node's PEXReactor. It returns nil if PEX is disabled.
  1076. func (n *Node) PEXReactor() *pex.Reactor {
  1077. return n.pexReactor
  1078. }
  1079. // EvidencePool returns the Node's EvidencePool.
  1080. func (n *Node) EvidencePool() *evidence.Pool {
  1081. return n.evidencePool
  1082. }
  1083. // EventBus returns the Node's EventBus.
  1084. func (n *Node) EventBus() *types.EventBus {
  1085. return n.eventBus
  1086. }
  1087. // PrivValidator returns the Node's PrivValidator.
  1088. // XXX: for convenience only!
  1089. func (n *Node) PrivValidator() types.PrivValidator {
  1090. return n.privValidator
  1091. }
  1092. // GenesisDoc returns the Node's GenesisDoc.
  1093. func (n *Node) GenesisDoc() *types.GenesisDoc {
  1094. return n.genesisDoc
  1095. }
  1096. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  1097. func (n *Node) ProxyApp() proxy.AppConns {
  1098. return n.proxyApp
  1099. }
  1100. // Config returns the Node's config.
  1101. func (n *Node) Config() *cfg.Config {
  1102. return n.config
  1103. }
  1104. //------------------------------------------------------------------------------
  1105. func (n *Node) Listeners() []string {
  1106. return []string{
  1107. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  1108. }
  1109. }
  1110. func (n *Node) IsListening() bool {
  1111. return n.isListening
  1112. }
  1113. // NodeInfo returns the Node's Info from the Switch.
  1114. func (n *Node) NodeInfo() p2p.NodeInfo {
  1115. return n.nodeInfo
  1116. }
  1117. func makeNodeInfo(
  1118. config *cfg.Config,
  1119. nodeKey *p2p.NodeKey,
  1120. txIndexer txindex.TxIndexer,
  1121. genDoc *types.GenesisDoc,
  1122. state sm.State,
  1123. ) (p2p.NodeInfo, error) {
  1124. txIndexerStatus := "on"
  1125. if _, ok := txIndexer.(*null.TxIndex); ok {
  1126. txIndexerStatus = "off"
  1127. }
  1128. var bcChannel byte
  1129. switch config.FastSync.Version {
  1130. case "v0":
  1131. bcChannel = bcv0.BlockchainChannel
  1132. case "v1":
  1133. bcChannel = bcv1.BlockchainChannel
  1134. case "v2":
  1135. bcChannel = bcv2.BlockchainChannel
  1136. default:
  1137. return nil, fmt.Errorf("unknown fastsync version %s", config.FastSync.Version)
  1138. }
  1139. nodeInfo := p2p.DefaultNodeInfo{
  1140. ProtocolVersion: p2p.NewProtocolVersion(
  1141. version.P2PProtocol, // global
  1142. state.Version.Consensus.Block,
  1143. state.Version.Consensus.App,
  1144. ),
  1145. DefaultNodeID: nodeKey.ID(),
  1146. Network: genDoc.ChainID,
  1147. Version: version.TMCoreSemVer,
  1148. Channels: []byte{
  1149. bcChannel,
  1150. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  1151. mempl.MempoolChannel,
  1152. evidence.EvidenceChannel,
  1153. statesync.SnapshotChannel, statesync.ChunkChannel,
  1154. },
  1155. Moniker: config.Moniker,
  1156. Other: p2p.DefaultNodeInfoOther{
  1157. TxIndex: txIndexerStatus,
  1158. RPCAddress: config.RPC.ListenAddress,
  1159. },
  1160. }
  1161. if config.P2P.PexReactor {
  1162. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  1163. }
  1164. lAddr := config.P2P.ExternalAddress
  1165. if lAddr == "" {
  1166. lAddr = config.P2P.ListenAddress
  1167. }
  1168. nodeInfo.ListenAddr = lAddr
  1169. err := nodeInfo.Validate()
  1170. return nodeInfo, err
  1171. }
  1172. //------------------------------------------------------------------------------
  1173. var (
  1174. genesisDocKey = []byte("genesisDoc")
  1175. )
  1176. // LoadStateFromDBOrGenesisDocProvider attempts to load the state from the
  1177. // database, or creates one using the given genesisDocProvider and persists the
  1178. // result to the database. On success this also returns the genesis doc loaded
  1179. // through the given provider.
  1180. func LoadStateFromDBOrGenesisDocProvider(
  1181. stateDB dbm.DB,
  1182. genesisDocProvider GenesisDocProvider,
  1183. ) (sm.State, *types.GenesisDoc, error) {
  1184. // Get genesis doc
  1185. genDoc, err := loadGenesisDoc(stateDB)
  1186. if err != nil {
  1187. genDoc, err = genesisDocProvider()
  1188. if err != nil {
  1189. return sm.State{}, nil, err
  1190. }
  1191. // save genesis doc to prevent a certain class of user errors (e.g. when it
  1192. // was changed, accidentally or not). Also good for audit trail.
  1193. saveGenesisDoc(stateDB, genDoc)
  1194. }
  1195. stateStore := sm.NewStore(stateDB)
  1196. state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc)
  1197. if err != nil {
  1198. return sm.State{}, nil, err
  1199. }
  1200. return state, genDoc, nil
  1201. }
  1202. // panics if failed to unmarshal bytes
  1203. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  1204. b, err := db.Get(genesisDocKey)
  1205. if err != nil {
  1206. panic(err)
  1207. }
  1208. if len(b) == 0 {
  1209. return nil, errors.New("genesis doc not found")
  1210. }
  1211. var genDoc *types.GenesisDoc
  1212. err = tmjson.Unmarshal(b, &genDoc)
  1213. if err != nil {
  1214. panic(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, b))
  1215. }
  1216. return genDoc, nil
  1217. }
  1218. // panics if failed to marshal the given genesis document
  1219. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  1220. b, err := tmjson.Marshal(genDoc)
  1221. if err != nil {
  1222. panic(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  1223. }
  1224. if err := db.SetSync(genesisDocKey, b); err != nil {
  1225. panic(fmt.Sprintf("Failed to save genesis doc: %v", err))
  1226. }
  1227. }
  1228. func createAndStartPrivValidatorSocketClient(
  1229. listenAddr,
  1230. chainID string,
  1231. logger log.Logger,
  1232. ) (types.PrivValidator, error) {
  1233. pve, err := privval.NewSignerListener(listenAddr, logger)
  1234. if err != nil {
  1235. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1236. }
  1237. pvsc, err := privval.NewSignerClient(pve, chainID)
  1238. if err != nil {
  1239. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1240. }
  1241. // try to get a pubkey from private validate first time
  1242. _, err = pvsc.GetPubKey()
  1243. if err != nil {
  1244. return nil, fmt.Errorf("can't get pubkey: %w", err)
  1245. }
  1246. const (
  1247. retries = 50 // 50 * 100ms = 5s total
  1248. timeout = 100 * time.Millisecond
  1249. )
  1250. pvscWithRetries := privval.NewRetrySignerClient(pvsc, retries, timeout)
  1251. return pvscWithRetries, nil
  1252. }
  1253. // splitAndTrimEmpty slices s into all subslices separated by sep and returns a
  1254. // slice of the string s with all leading and trailing Unicode code points
  1255. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  1256. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  1257. // -1. also filter out empty strings, only return non-empty strings.
  1258. func splitAndTrimEmpty(s, sep, cutset string) []string {
  1259. if s == "" {
  1260. return []string{}
  1261. }
  1262. spl := strings.Split(s, sep)
  1263. nonEmptyStrings := make([]string, 0, len(spl))
  1264. for i := 0; i < len(spl); i++ {
  1265. element := strings.Trim(spl[i], cutset)
  1266. if element != "" {
  1267. nonEmptyStrings = append(nonEmptyStrings, element)
  1268. }
  1269. }
  1270. return nonEmptyStrings
  1271. }