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.

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