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.

931 lines
28 KiB

max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. _ "net/http/pprof"
  9. "os"
  10. "strings"
  11. "time"
  12. "github.com/pkg/errors"
  13. "github.com/prometheus/client_golang/prometheus"
  14. "github.com/prometheus/client_golang/prometheus/promhttp"
  15. "github.com/rs/cors"
  16. amino "github.com/tendermint/go-amino"
  17. abci "github.com/tendermint/tendermint/abci/types"
  18. bc "github.com/tendermint/tendermint/blockchain"
  19. cfg "github.com/tendermint/tendermint/config"
  20. cs "github.com/tendermint/tendermint/consensus"
  21. "github.com/tendermint/tendermint/crypto/ed25519"
  22. "github.com/tendermint/tendermint/evidence"
  23. cmn "github.com/tendermint/tendermint/libs/common"
  24. dbm "github.com/tendermint/tendermint/libs/db"
  25. "github.com/tendermint/tendermint/libs/log"
  26. mempl "github.com/tendermint/tendermint/mempool"
  27. "github.com/tendermint/tendermint/p2p"
  28. "github.com/tendermint/tendermint/p2p/pex"
  29. "github.com/tendermint/tendermint/privval"
  30. "github.com/tendermint/tendermint/proxy"
  31. rpccore "github.com/tendermint/tendermint/rpc/core"
  32. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  33. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  34. "github.com/tendermint/tendermint/rpc/lib/server"
  35. sm "github.com/tendermint/tendermint/state"
  36. "github.com/tendermint/tendermint/state/txindex"
  37. "github.com/tendermint/tendermint/state/txindex/kv"
  38. "github.com/tendermint/tendermint/state/txindex/null"
  39. "github.com/tendermint/tendermint/types"
  40. tmtime "github.com/tendermint/tendermint/types/time"
  41. "github.com/tendermint/tendermint/version"
  42. )
  43. //------------------------------------------------------------------------------
  44. // DBContext specifies config information for loading a new DB.
  45. type DBContext struct {
  46. ID string
  47. Config *cfg.Config
  48. }
  49. // DBProvider takes a DBContext and returns an instantiated DB.
  50. type DBProvider func(*DBContext) (dbm.DB, error)
  51. // DefaultDBProvider returns a database using the DBBackend and DBDir
  52. // specified in the ctx.Config.
  53. func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) {
  54. dbType := dbm.DBBackendType(ctx.Config.DBBackend)
  55. return dbm.NewDB(ctx.ID, dbType, ctx.Config.DBDir()), nil
  56. }
  57. // GenesisDocProvider returns a GenesisDoc.
  58. // It allows the GenesisDoc to be pulled from sources other than the
  59. // filesystem, for instance from a distributed key-value store cluster.
  60. type GenesisDocProvider func() (*types.GenesisDoc, error)
  61. // DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  62. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  63. func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider {
  64. return func() (*types.GenesisDoc, error) {
  65. return types.GenesisDocFromFile(config.GenesisFile())
  66. }
  67. }
  68. // NodeProvider takes a config and a logger and returns a ready to go Node.
  69. type NodeProvider func(*cfg.Config, log.Logger) (*Node, error)
  70. // DefaultNewNode returns a Tendermint node with default settings for the
  71. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  72. // It implements NodeProvider.
  73. func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) {
  74. // Generate node PrivKey
  75. nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
  76. if err != nil {
  77. return nil, err
  78. }
  79. // Convert old PrivValidator if it exists.
  80. oldPrivVal := config.OldPrivValidatorFile()
  81. newPrivValKey := config.PrivValidatorKeyFile()
  82. newPrivValState := config.PrivValidatorStateFile()
  83. if _, err := os.Stat(oldPrivVal); !os.IsNotExist(err) {
  84. oldPV, err := privval.LoadOldFilePV(oldPrivVal)
  85. if err != nil {
  86. return nil, fmt.Errorf("Error reading OldPrivValidator from %v: %v\n", oldPrivVal, err)
  87. }
  88. logger.Info("Upgrading PrivValidator file",
  89. "old", oldPrivVal,
  90. "newKey", newPrivValKey,
  91. "newState", newPrivValState,
  92. )
  93. oldPV.Upgrade(newPrivValKey, newPrivValState)
  94. }
  95. return NewNode(config,
  96. privval.LoadOrGenFilePV(newPrivValKey, newPrivValState),
  97. nodeKey,
  98. proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()),
  99. DefaultGenesisDocProviderFunc(config),
  100. DefaultDBProvider,
  101. DefaultMetricsProvider(config.Instrumentation),
  102. logger,
  103. )
  104. }
  105. // MetricsProvider returns a consensus, p2p and mempool Metrics.
  106. type MetricsProvider func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics)
  107. // DefaultMetricsProvider returns Metrics build using Prometheus client library
  108. // if Prometheus is enabled. Otherwise, it returns no-op Metrics.
  109. func DefaultMetricsProvider(config *cfg.InstrumentationConfig) MetricsProvider {
  110. return func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics) {
  111. if config.Prometheus {
  112. return cs.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  113. p2p.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  114. mempl.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  115. sm.PrometheusMetrics(config.Namespace, "chain_id", chainID)
  116. }
  117. return cs.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics(), sm.NopMetrics()
  118. }
  119. }
  120. //------------------------------------------------------------------------------
  121. // Node is the highest level interface to a full Tendermint node.
  122. // It includes all configuration information and running services.
  123. type Node struct {
  124. cmn.BaseService
  125. // config
  126. config *cfg.Config
  127. genesisDoc *types.GenesisDoc // initial validator set
  128. privValidator types.PrivValidator // local node's validator key
  129. // network
  130. transport *p2p.MultiplexTransport
  131. sw *p2p.Switch // p2p connections
  132. addrBook pex.AddrBook // known peers
  133. nodeInfo p2p.NodeInfo
  134. nodeKey *p2p.NodeKey // our node privkey
  135. isListening bool
  136. // services
  137. eventBus *types.EventBus // pub/sub for services
  138. stateDB dbm.DB
  139. blockStore *bc.BlockStore // store the blockchain to disk
  140. bcReactor *bc.BlockchainReactor // for fast-syncing
  141. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  142. consensusState *cs.ConsensusState // latest consensus state
  143. consensusReactor *cs.ConsensusReactor // for participating in the consensus
  144. evidencePool *evidence.EvidencePool // tracking evidence
  145. proxyApp proxy.AppConns // connection to the application
  146. rpcListeners []net.Listener // rpc servers
  147. txIndexer txindex.TxIndexer
  148. indexerService *txindex.IndexerService
  149. prometheusSrv *http.Server
  150. }
  151. // NewNode returns a new, ready to go, Tendermint Node.
  152. func NewNode(config *cfg.Config,
  153. privValidator types.PrivValidator,
  154. nodeKey *p2p.NodeKey,
  155. clientCreator proxy.ClientCreator,
  156. genesisDocProvider GenesisDocProvider,
  157. dbProvider DBProvider,
  158. metricsProvider MetricsProvider,
  159. logger log.Logger) (*Node, error) {
  160. // Get BlockStore
  161. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  162. if err != nil {
  163. return nil, err
  164. }
  165. blockStore := bc.NewBlockStore(blockStoreDB)
  166. // Get State
  167. stateDB, err := dbProvider(&DBContext{"state", config})
  168. if err != nil {
  169. return nil, err
  170. }
  171. // Get genesis doc
  172. // TODO: move to state package?
  173. genDoc, err := loadGenesisDoc(stateDB)
  174. if err != nil {
  175. genDoc, err = genesisDocProvider()
  176. if err != nil {
  177. return nil, err
  178. }
  179. // save genesis doc to prevent a certain class of user errors (e.g. when it
  180. // was changed, accidentally or not). Also good for audit trail.
  181. saveGenesisDoc(stateDB, genDoc)
  182. }
  183. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  184. if err != nil {
  185. return nil, err
  186. }
  187. // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query).
  188. proxyApp := proxy.NewAppConns(clientCreator)
  189. proxyApp.SetLogger(logger.With("module", "proxy"))
  190. if err := proxyApp.Start(); err != nil {
  191. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  192. }
  193. // Create the handshaker, which calls RequestInfo, sets the AppVersion on the state,
  194. // and replays any blocks as necessary to sync tendermint with the app.
  195. consensusLogger := logger.With("module", "consensus")
  196. handshaker := cs.NewHandshaker(stateDB, state, blockStore, genDoc)
  197. handshaker.SetLogger(consensusLogger)
  198. if err := handshaker.Handshake(proxyApp); err != nil {
  199. return nil, fmt.Errorf("Error during handshake: %v", err)
  200. }
  201. // Reload the state. It will have the Version.Consensus.App set by the
  202. // Handshake, and may have other modifications as well (ie. depending on
  203. // what happened during block replay).
  204. state = sm.LoadState(stateDB)
  205. // Log the version info.
  206. logger.Info("Version info",
  207. "software", version.TMCoreSemVer,
  208. "block", version.BlockProtocol,
  209. "p2p", version.P2PProtocol,
  210. )
  211. // If the state and software differ in block version, at least log it.
  212. if state.Version.Consensus.Block != version.BlockProtocol {
  213. logger.Info("Software and state have different block protocols",
  214. "software", version.BlockProtocol,
  215. "state", state.Version.Consensus.Block,
  216. )
  217. }
  218. if config.PrivValidatorListenAddr != "" {
  219. // If an address is provided, listen on the socket for a connection from an
  220. // external signing process.
  221. // FIXME: we should start services inside OnStart
  222. privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, logger)
  223. if err != nil {
  224. return nil, errors.Wrap(err, "Error with private validator socket client")
  225. }
  226. }
  227. // Decide whether to fast-sync or not
  228. // We don't fast-sync when the only validator is us.
  229. fastSync := config.FastSync
  230. if state.Validators.Size() == 1 {
  231. addr, _ := state.Validators.GetByIndex(0)
  232. privValAddr := privValidator.GetPubKey().Address()
  233. if bytes.Equal(privValAddr, addr) {
  234. fastSync = false
  235. }
  236. }
  237. pubKey := privValidator.GetPubKey()
  238. addr := pubKey.Address()
  239. // Log whether this node is a validator or an observer
  240. if state.Validators.HasAddress(addr) {
  241. consensusLogger.Info("This node is a validator", "addr", addr, "pubKey", pubKey)
  242. } else {
  243. consensusLogger.Info("This node is not a validator", "addr", addr, "pubKey", pubKey)
  244. }
  245. csMetrics, p2pMetrics, memplMetrics, smMetrics := metricsProvider(genDoc.ChainID)
  246. // Make MempoolReactor
  247. mempool := mempl.NewMempool(
  248. config.Mempool,
  249. proxyApp.Mempool(),
  250. state.LastBlockHeight,
  251. mempl.WithMetrics(memplMetrics),
  252. mempl.WithPreCheck(sm.TxPreCheck(state)),
  253. mempl.WithPostCheck(sm.TxPostCheck(state)),
  254. )
  255. mempoolLogger := logger.With("module", "mempool")
  256. mempool.SetLogger(mempoolLogger)
  257. if config.Mempool.WalEnabled() {
  258. mempool.InitWAL() // no need to have the mempool wal during tests
  259. }
  260. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  261. mempoolReactor.SetLogger(mempoolLogger)
  262. if config.Consensus.WaitForTxs() {
  263. mempool.EnableTxsAvailable()
  264. }
  265. // Make Evidence Reactor
  266. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  267. if err != nil {
  268. return nil, err
  269. }
  270. evidenceLogger := logger.With("module", "evidence")
  271. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  272. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  273. evidencePool.SetLogger(evidenceLogger)
  274. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  275. evidenceReactor.SetLogger(evidenceLogger)
  276. blockExecLogger := logger.With("module", "state")
  277. // make block executor for consensus and blockchain reactors to execute blocks
  278. blockExec := sm.NewBlockExecutor(
  279. stateDB,
  280. blockExecLogger,
  281. proxyApp.Consensus(),
  282. mempool,
  283. evidencePool,
  284. sm.BlockExecutorWithMetrics(smMetrics),
  285. )
  286. // Make BlockchainReactor
  287. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  288. bcReactor.SetLogger(logger.With("module", "blockchain"))
  289. // Make ConsensusReactor
  290. consensusState := cs.NewConsensusState(
  291. config.Consensus,
  292. state.Copy(),
  293. blockExec,
  294. blockStore,
  295. mempool,
  296. evidencePool,
  297. cs.StateMetrics(csMetrics),
  298. )
  299. consensusState.SetLogger(consensusLogger)
  300. if privValidator != nil {
  301. consensusState.SetPrivValidator(privValidator)
  302. }
  303. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync, cs.ReactorMetrics(csMetrics))
  304. consensusReactor.SetLogger(consensusLogger)
  305. eventBus := types.NewEventBus()
  306. eventBus.SetLogger(logger.With("module", "events"))
  307. // services which will be publishing and/or subscribing for messages (events)
  308. // consensusReactor will set it on consensusState and blockExecutor
  309. consensusReactor.SetEventBus(eventBus)
  310. // Transaction indexing
  311. var txIndexer txindex.TxIndexer
  312. switch config.TxIndex.Indexer {
  313. case "kv":
  314. store, err := dbProvider(&DBContext{"tx_index", config})
  315. if err != nil {
  316. return nil, err
  317. }
  318. if config.TxIndex.IndexTags != "" {
  319. txIndexer = kv.NewTxIndex(store, kv.IndexTags(splitAndTrimEmpty(config.TxIndex.IndexTags, ",", " ")))
  320. } else if config.TxIndex.IndexAllTags {
  321. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  322. } else {
  323. txIndexer = kv.NewTxIndex(store)
  324. }
  325. default:
  326. txIndexer = &null.TxIndex{}
  327. }
  328. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  329. indexerService.SetLogger(logger.With("module", "txindex"))
  330. p2pLogger := logger.With("module", "p2p")
  331. nodeInfo, err := makeNodeInfo(
  332. config,
  333. nodeKey.ID(),
  334. txIndexer,
  335. genDoc.ChainID,
  336. p2p.NewProtocolVersion(
  337. version.P2PProtocol, // global
  338. state.Version.Consensus.Block,
  339. state.Version.Consensus.App,
  340. ),
  341. )
  342. if err != nil {
  343. return nil, err
  344. }
  345. // Setup Transport.
  346. var (
  347. mConnConfig = p2p.MConnConfig(config.P2P)
  348. transport = p2p.NewMultiplexTransport(nodeInfo, *nodeKey, mConnConfig)
  349. connFilters = []p2p.ConnFilterFunc{}
  350. peerFilters = []p2p.PeerFilterFunc{}
  351. )
  352. if !config.P2P.AllowDuplicateIP {
  353. connFilters = append(connFilters, p2p.ConnDuplicateIPFilter())
  354. }
  355. // Filter peers by addr or pubkey with an ABCI query.
  356. // If the query return code is OK, add peer.
  357. if config.FilterPeers {
  358. connFilters = append(
  359. connFilters,
  360. // ABCI query for address filtering.
  361. func(_ p2p.ConnSet, c net.Conn, _ []net.IP) error {
  362. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  363. Path: fmt.Sprintf("/p2p/filter/addr/%s", c.RemoteAddr().String()),
  364. })
  365. if err != nil {
  366. return err
  367. }
  368. if res.IsErr() {
  369. return fmt.Errorf("Error querying abci app: %v", res)
  370. }
  371. return nil
  372. },
  373. )
  374. peerFilters = append(
  375. peerFilters,
  376. // ABCI query for ID filtering.
  377. func(_ p2p.IPeerSet, p p2p.Peer) error {
  378. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  379. Path: fmt.Sprintf("/p2p/filter/id/%s", p.ID()),
  380. })
  381. if err != nil {
  382. return err
  383. }
  384. if res.IsErr() {
  385. return fmt.Errorf("Error querying abci app: %v", res)
  386. }
  387. return nil
  388. },
  389. )
  390. }
  391. p2p.MultiplexTransportConnFilters(connFilters...)(transport)
  392. // Setup Switch.
  393. sw := p2p.NewSwitch(
  394. config.P2P,
  395. transport,
  396. p2p.WithMetrics(p2pMetrics),
  397. p2p.SwitchPeerFilters(peerFilters...),
  398. )
  399. sw.SetLogger(p2pLogger)
  400. sw.AddReactor("MEMPOOL", mempoolReactor)
  401. sw.AddReactor("BLOCKCHAIN", bcReactor)
  402. sw.AddReactor("CONSENSUS", consensusReactor)
  403. sw.AddReactor("EVIDENCE", evidenceReactor)
  404. sw.SetNodeInfo(nodeInfo)
  405. sw.SetNodeKey(nodeKey)
  406. p2pLogger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", config.NodeKeyFile())
  407. // Optionally, start the pex reactor
  408. //
  409. // TODO:
  410. //
  411. // We need to set Seeds and PersistentPeers on the switch,
  412. // since it needs to be able to use these (and their DNS names)
  413. // even if the PEX is off. We can include the DNS name in the NetAddress,
  414. // but it would still be nice to have a clear list of the current "PersistentPeers"
  415. // somewhere that we can return with net_info.
  416. //
  417. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  418. // Note we currently use the addrBook regardless at least for AddOurAddress
  419. addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  420. // Add ourselves to addrbook to prevent dialing ourselves
  421. addrBook.AddOurAddress(nodeInfo.NetAddress())
  422. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  423. if config.P2P.PexReactor {
  424. // TODO persistent peers ? so we can have their DNS addrs saved
  425. pexReactor := pex.NewPEXReactor(addrBook,
  426. &pex.PEXReactorConfig{
  427. Seeds: splitAndTrimEmpty(config.P2P.Seeds, ",", " "),
  428. SeedMode: config.P2P.SeedMode,
  429. })
  430. pexReactor.SetLogger(logger.With("module", "pex"))
  431. sw.AddReactor("PEX", pexReactor)
  432. }
  433. sw.SetAddrBook(addrBook)
  434. // run the profile server
  435. profileHost := config.ProfListenAddress
  436. if profileHost != "" {
  437. go func() {
  438. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  439. }()
  440. }
  441. node := &Node{
  442. config: config,
  443. genesisDoc: genDoc,
  444. privValidator: privValidator,
  445. transport: transport,
  446. sw: sw,
  447. addrBook: addrBook,
  448. nodeInfo: nodeInfo,
  449. nodeKey: nodeKey,
  450. stateDB: stateDB,
  451. blockStore: blockStore,
  452. bcReactor: bcReactor,
  453. mempoolReactor: mempoolReactor,
  454. consensusState: consensusState,
  455. consensusReactor: consensusReactor,
  456. evidencePool: evidencePool,
  457. proxyApp: proxyApp,
  458. txIndexer: txIndexer,
  459. indexerService: indexerService,
  460. eventBus: eventBus,
  461. }
  462. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  463. return node, nil
  464. }
  465. // OnStart starts the Node. It implements cmn.Service.
  466. func (n *Node) OnStart() error {
  467. now := tmtime.Now()
  468. genTime := n.genesisDoc.GenesisTime
  469. if genTime.After(now) {
  470. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  471. time.Sleep(genTime.Sub(now))
  472. }
  473. err := n.eventBus.Start()
  474. if err != nil {
  475. return err
  476. }
  477. // Add private IDs to addrbook to block those peers being added
  478. n.addrBook.AddPrivateIDs(splitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  479. // Start the RPC server before the P2P server
  480. // so we can eg. receive txs for the first block
  481. if n.config.RPC.ListenAddress != "" {
  482. listeners, err := n.startRPC()
  483. if err != nil {
  484. return err
  485. }
  486. n.rpcListeners = listeners
  487. }
  488. if n.config.Instrumentation.Prometheus &&
  489. n.config.Instrumentation.PrometheusListenAddr != "" {
  490. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  491. }
  492. // Start the transport.
  493. addr, err := p2p.NewNetAddressStringWithOptionalID(n.config.P2P.ListenAddress)
  494. if err != nil {
  495. return err
  496. }
  497. if err := n.transport.Listen(*addr); err != nil {
  498. return err
  499. }
  500. n.isListening = true
  501. // Start the switch (the P2P server).
  502. err = n.sw.Start()
  503. if err != nil {
  504. return err
  505. }
  506. // Always connect to persistent peers
  507. if n.config.P2P.PersistentPeers != "" {
  508. err = n.sw.DialPeersAsync(n.addrBook, splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "), true)
  509. if err != nil {
  510. return err
  511. }
  512. }
  513. // start tx indexer
  514. return n.indexerService.Start()
  515. }
  516. // OnStop stops the Node. It implements cmn.Service.
  517. func (n *Node) OnStop() {
  518. n.BaseService.OnStop()
  519. n.Logger.Info("Stopping Node")
  520. // first stop the non-reactor services
  521. n.eventBus.Stop()
  522. n.indexerService.Stop()
  523. // now stop the reactors
  524. // TODO: gracefully disconnect from peers.
  525. n.sw.Stop()
  526. // stop mempool WAL
  527. if n.config.Mempool.WalEnabled() {
  528. n.mempoolReactor.Mempool.CloseWAL()
  529. }
  530. if err := n.transport.Close(); err != nil {
  531. n.Logger.Error("Error closing transport", "err", err)
  532. }
  533. n.isListening = false
  534. // finally stop the listeners / external services
  535. for _, l := range n.rpcListeners {
  536. n.Logger.Info("Closing rpc listener", "listener", l)
  537. if err := l.Close(); err != nil {
  538. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  539. }
  540. }
  541. if pvsc, ok := n.privValidator.(cmn.Service); ok {
  542. pvsc.Stop()
  543. }
  544. if n.prometheusSrv != nil {
  545. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  546. // Error from closing listeners, or context timeout:
  547. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  548. }
  549. }
  550. }
  551. // ConfigureRPC sets all variables in rpccore so they will serve
  552. // rpc calls from this node
  553. func (n *Node) ConfigureRPC() {
  554. rpccore.SetStateDB(n.stateDB)
  555. rpccore.SetBlockStore(n.blockStore)
  556. rpccore.SetConsensusState(n.consensusState)
  557. rpccore.SetMempool(n.mempoolReactor.Mempool)
  558. rpccore.SetEvidencePool(n.evidencePool)
  559. rpccore.SetP2PPeers(n.sw)
  560. rpccore.SetP2PTransport(n)
  561. pubKey := n.privValidator.GetPubKey()
  562. rpccore.SetPubKey(pubKey)
  563. rpccore.SetGenesisDoc(n.genesisDoc)
  564. rpccore.SetAddrBook(n.addrBook)
  565. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  566. rpccore.SetTxIndexer(n.txIndexer)
  567. rpccore.SetConsensusReactor(n.consensusReactor)
  568. rpccore.SetEventBus(n.eventBus)
  569. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  570. }
  571. func (n *Node) startRPC() ([]net.Listener, error) {
  572. n.ConfigureRPC()
  573. listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  574. coreCodec := amino.NewCodec()
  575. ctypes.RegisterAmino(coreCodec)
  576. if n.config.RPC.Unsafe {
  577. rpccore.AddUnsafeRoutes()
  578. }
  579. // we may expose the rpc over both a unix and tcp socket
  580. listeners := make([]net.Listener, len(listenAddrs))
  581. for i, listenAddr := range listenAddrs {
  582. mux := http.NewServeMux()
  583. rpcLogger := n.Logger.With("module", "rpc-server")
  584. wm := rpcserver.NewWebsocketManager(rpccore.Routes, coreCodec, rpcserver.EventSubscriber(n.eventBus))
  585. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  586. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  587. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, coreCodec, rpcLogger)
  588. listener, err := rpcserver.Listen(
  589. listenAddr,
  590. rpcserver.Config{MaxOpenConnections: n.config.RPC.MaxOpenConnections},
  591. )
  592. if err != nil {
  593. return nil, err
  594. }
  595. var rootHandler http.Handler = mux
  596. if n.config.RPC.IsCorsEnabled() {
  597. corsMiddleware := cors.New(cors.Options{
  598. AllowedOrigins: n.config.RPC.CORSAllowedOrigins,
  599. AllowedMethods: n.config.RPC.CORSAllowedMethods,
  600. AllowedHeaders: n.config.RPC.CORSAllowedHeaders,
  601. })
  602. rootHandler = corsMiddleware.Handler(mux)
  603. }
  604. go rpcserver.StartHTTPServer(
  605. listener,
  606. rootHandler,
  607. rpcLogger,
  608. )
  609. listeners[i] = listener
  610. }
  611. // we expose a simplified api over grpc for convenience to app devs
  612. grpcListenAddr := n.config.RPC.GRPCListenAddress
  613. if grpcListenAddr != "" {
  614. listener, err := rpcserver.Listen(
  615. grpcListenAddr, rpcserver.Config{MaxOpenConnections: n.config.RPC.GRPCMaxOpenConnections})
  616. if err != nil {
  617. return nil, err
  618. }
  619. go grpccore.StartGRPCServer(listener)
  620. listeners = append(listeners, listener)
  621. }
  622. return listeners, nil
  623. }
  624. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  625. // collectors on addr.
  626. func (n *Node) startPrometheusServer(addr string) *http.Server {
  627. srv := &http.Server{
  628. Addr: addr,
  629. Handler: promhttp.InstrumentMetricHandler(
  630. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  631. prometheus.DefaultGatherer,
  632. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  633. ),
  634. ),
  635. }
  636. go func() {
  637. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  638. // Error starting or closing listener:
  639. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  640. }
  641. }()
  642. return srv
  643. }
  644. // Switch returns the Node's Switch.
  645. func (n *Node) Switch() *p2p.Switch {
  646. return n.sw
  647. }
  648. // BlockStore returns the Node's BlockStore.
  649. func (n *Node) BlockStore() *bc.BlockStore {
  650. return n.blockStore
  651. }
  652. // ConsensusState returns the Node's ConsensusState.
  653. func (n *Node) ConsensusState() *cs.ConsensusState {
  654. return n.consensusState
  655. }
  656. // ConsensusReactor returns the Node's ConsensusReactor.
  657. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  658. return n.consensusReactor
  659. }
  660. // MempoolReactor returns the Node's MempoolReactor.
  661. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  662. return n.mempoolReactor
  663. }
  664. // EvidencePool returns the Node's EvidencePool.
  665. func (n *Node) EvidencePool() *evidence.EvidencePool {
  666. return n.evidencePool
  667. }
  668. // EventBus returns the Node's EventBus.
  669. func (n *Node) EventBus() *types.EventBus {
  670. return n.eventBus
  671. }
  672. // PrivValidator returns the Node's PrivValidator.
  673. // XXX: for convenience only!
  674. func (n *Node) PrivValidator() types.PrivValidator {
  675. return n.privValidator
  676. }
  677. // GenesisDoc returns the Node's GenesisDoc.
  678. func (n *Node) GenesisDoc() *types.GenesisDoc {
  679. return n.genesisDoc
  680. }
  681. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  682. func (n *Node) ProxyApp() proxy.AppConns {
  683. return n.proxyApp
  684. }
  685. //------------------------------------------------------------------------------
  686. func (n *Node) Listeners() []string {
  687. return []string{
  688. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  689. }
  690. }
  691. func (n *Node) IsListening() bool {
  692. return n.isListening
  693. }
  694. // NodeInfo returns the Node's Info from the Switch.
  695. func (n *Node) NodeInfo() p2p.NodeInfo {
  696. return n.nodeInfo
  697. }
  698. func makeNodeInfo(
  699. config *cfg.Config,
  700. nodeID p2p.ID,
  701. txIndexer txindex.TxIndexer,
  702. chainID string,
  703. protocolVersion p2p.ProtocolVersion,
  704. ) (p2p.NodeInfo, error) {
  705. txIndexerStatus := "on"
  706. if _, ok := txIndexer.(*null.TxIndex); ok {
  707. txIndexerStatus = "off"
  708. }
  709. nodeInfo := p2p.DefaultNodeInfo{
  710. ProtocolVersion: protocolVersion,
  711. ID_: nodeID,
  712. Network: chainID,
  713. Version: version.TMCoreSemVer,
  714. Channels: []byte{
  715. bc.BlockchainChannel,
  716. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  717. mempl.MempoolChannel,
  718. evidence.EvidenceChannel,
  719. },
  720. Moniker: config.Moniker,
  721. Other: p2p.DefaultNodeInfoOther{
  722. TxIndex: txIndexerStatus,
  723. RPCAddress: config.RPC.ListenAddress,
  724. },
  725. }
  726. if config.P2P.PexReactor {
  727. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  728. }
  729. lAddr := config.P2P.ExternalAddress
  730. if lAddr == "" {
  731. lAddr = config.P2P.ListenAddress
  732. }
  733. nodeInfo.ListenAddr = lAddr
  734. err := nodeInfo.Validate()
  735. return nodeInfo, err
  736. }
  737. //------------------------------------------------------------------------------
  738. var (
  739. genesisDocKey = []byte("genesisDoc")
  740. )
  741. // panics if failed to unmarshal bytes
  742. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  743. bytes := db.Get(genesisDocKey)
  744. if len(bytes) == 0 {
  745. return nil, errors.New("Genesis doc not found")
  746. }
  747. var genDoc *types.GenesisDoc
  748. err := cdc.UnmarshalJSON(bytes, &genDoc)
  749. if err != nil {
  750. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  751. }
  752. return genDoc, nil
  753. }
  754. // panics if failed to marshal the given genesis document
  755. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  756. bytes, err := cdc.MarshalJSON(genDoc)
  757. if err != nil {
  758. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  759. }
  760. db.SetSync(genesisDocKey, bytes)
  761. }
  762. func createAndStartPrivValidatorSocketClient(
  763. listenAddr string,
  764. logger log.Logger,
  765. ) (types.PrivValidator, error) {
  766. var listener net.Listener
  767. protocol, address := cmn.ProtocolAndAddress(listenAddr)
  768. ln, err := net.Listen(protocol, address)
  769. if err != nil {
  770. return nil, err
  771. }
  772. switch protocol {
  773. case "unix":
  774. listener = privval.NewUnixListener(ln)
  775. case "tcp":
  776. // TODO: persist this key so external signer
  777. // can actually authenticate us
  778. listener = privval.NewTCPListener(ln, ed25519.GenPrivKey())
  779. default:
  780. return nil, fmt.Errorf(
  781. "Wrong listen address: expected either 'tcp' or 'unix' protocols, got %s",
  782. protocol,
  783. )
  784. }
  785. pvsc := privval.NewSocketVal(logger.With("module", "privval"), listener)
  786. if err := pvsc.Start(); err != nil {
  787. return nil, errors.Wrap(err, "failed to start private validator")
  788. }
  789. return pvsc, nil
  790. }
  791. // splitAndTrimEmpty slices s into all subslices separated by sep and returns a
  792. // slice of the string s with all leading and trailing Unicode code points
  793. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  794. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  795. // -1. also filter out empty strings, only return non-empty strings.
  796. func splitAndTrimEmpty(s, sep, cutset string) []string {
  797. if s == "" {
  798. return []string{}
  799. }
  800. spl := strings.Split(s, sep)
  801. nonEmptyStrings := make([]string, 0, len(spl))
  802. for i := 0; i < len(spl); i++ {
  803. element := strings.Trim(spl[i], cutset)
  804. if element != "" {
  805. nonEmptyStrings = append(nonEmptyStrings, element)
  806. }
  807. }
  808. return nonEmptyStrings
  809. }