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.

939 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. rpcserver "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. // EventBus and IndexerService must be started before the handshake because
  194. // we might need to index the txs of the replayed block as this might not have happened
  195. // when the node stopped last time (i.e. the node stopped after it saved the block
  196. // but before it indexed the txs, or, endblocker panicked)
  197. eventBus := types.NewEventBus()
  198. eventBus.SetLogger(logger.With("module", "events"))
  199. err = eventBus.Start()
  200. if err != nil {
  201. return nil, err
  202. }
  203. // Transaction indexing
  204. var txIndexer txindex.TxIndexer
  205. switch config.TxIndex.Indexer {
  206. case "kv":
  207. store, err := dbProvider(&DBContext{"tx_index", config})
  208. if err != nil {
  209. return nil, err
  210. }
  211. if config.TxIndex.IndexTags != "" {
  212. txIndexer = kv.NewTxIndex(store, kv.IndexTags(splitAndTrimEmpty(config.TxIndex.IndexTags, ",", " ")))
  213. } else if config.TxIndex.IndexAllTags {
  214. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  215. } else {
  216. txIndexer = kv.NewTxIndex(store)
  217. }
  218. default:
  219. txIndexer = &null.TxIndex{}
  220. }
  221. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  222. indexerService.SetLogger(logger.With("module", "txindex"))
  223. err = indexerService.Start()
  224. if err != nil {
  225. return nil, err
  226. }
  227. // Create the handshaker, which calls RequestInfo, sets the AppVersion on the state,
  228. // and replays any blocks as necessary to sync tendermint with the app.
  229. consensusLogger := logger.With("module", "consensus")
  230. handshaker := cs.NewHandshaker(stateDB, state, blockStore, genDoc)
  231. handshaker.SetLogger(consensusLogger)
  232. handshaker.SetEventBus(eventBus)
  233. if err := handshaker.Handshake(proxyApp); err != nil {
  234. return nil, fmt.Errorf("Error during handshake: %v", err)
  235. }
  236. // Reload the state. It will have the Version.Consensus.App set by the
  237. // Handshake, and may have other modifications as well (ie. depending on
  238. // what happened during block replay).
  239. state = sm.LoadState(stateDB)
  240. // Log the version info.
  241. logger.Info("Version info",
  242. "software", version.TMCoreSemVer,
  243. "block", version.BlockProtocol,
  244. "p2p", version.P2PProtocol,
  245. )
  246. // If the state and software differ in block version, at least log it.
  247. if state.Version.Consensus.Block != version.BlockProtocol {
  248. logger.Info("Software and state have different block protocols",
  249. "software", version.BlockProtocol,
  250. "state", state.Version.Consensus.Block,
  251. )
  252. }
  253. if config.PrivValidatorListenAddr != "" {
  254. // If an address is provided, listen on the socket for a connection from an
  255. // external signing process.
  256. // FIXME: we should start services inside OnStart
  257. privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, logger)
  258. if err != nil {
  259. return nil, errors.Wrap(err, "Error with private validator socket client")
  260. }
  261. }
  262. // Decide whether to fast-sync or not
  263. // We don't fast-sync when the only validator is us.
  264. fastSync := config.FastSync
  265. if state.Validators.Size() == 1 {
  266. addr, _ := state.Validators.GetByIndex(0)
  267. privValAddr := privValidator.GetPubKey().Address()
  268. if bytes.Equal(privValAddr, addr) {
  269. fastSync = false
  270. }
  271. }
  272. pubKey := privValidator.GetPubKey()
  273. addr := pubKey.Address()
  274. // Log whether this node is a validator or an observer
  275. if state.Validators.HasAddress(addr) {
  276. consensusLogger.Info("This node is a validator", "addr", addr, "pubKey", pubKey)
  277. } else {
  278. consensusLogger.Info("This node is not a validator", "addr", addr, "pubKey", pubKey)
  279. }
  280. csMetrics, p2pMetrics, memplMetrics, smMetrics := metricsProvider(genDoc.ChainID)
  281. // Make MempoolReactor
  282. mempool := mempl.NewMempool(
  283. config.Mempool,
  284. proxyApp.Mempool(),
  285. state.LastBlockHeight,
  286. mempl.WithMetrics(memplMetrics),
  287. mempl.WithPreCheck(sm.TxPreCheck(state)),
  288. mempl.WithPostCheck(sm.TxPostCheck(state)),
  289. )
  290. mempoolLogger := logger.With("module", "mempool")
  291. mempool.SetLogger(mempoolLogger)
  292. if config.Mempool.WalEnabled() {
  293. mempool.InitWAL() // no need to have the mempool wal during tests
  294. }
  295. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  296. mempoolReactor.SetLogger(mempoolLogger)
  297. if config.Consensus.WaitForTxs() {
  298. mempool.EnableTxsAvailable()
  299. }
  300. // Make Evidence Reactor
  301. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  302. if err != nil {
  303. return nil, err
  304. }
  305. evidenceLogger := logger.With("module", "evidence")
  306. evidencePool := evidence.NewEvidencePool(stateDB, evidenceDB)
  307. evidencePool.SetLogger(evidenceLogger)
  308. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  309. evidenceReactor.SetLogger(evidenceLogger)
  310. blockExecLogger := logger.With("module", "state")
  311. // make block executor for consensus and blockchain reactors to execute blocks
  312. blockExec := sm.NewBlockExecutor(
  313. stateDB,
  314. blockExecLogger,
  315. proxyApp.Consensus(),
  316. mempool,
  317. evidencePool,
  318. sm.BlockExecutorWithMetrics(smMetrics),
  319. )
  320. // Make BlockchainReactor
  321. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  322. bcReactor.SetLogger(logger.With("module", "blockchain"))
  323. // Make ConsensusReactor
  324. consensusState := cs.NewConsensusState(
  325. config.Consensus,
  326. state.Copy(),
  327. blockExec,
  328. blockStore,
  329. mempool,
  330. evidencePool,
  331. cs.StateMetrics(csMetrics),
  332. )
  333. consensusState.SetLogger(consensusLogger)
  334. if privValidator != nil {
  335. consensusState.SetPrivValidator(privValidator)
  336. }
  337. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync, cs.ReactorMetrics(csMetrics))
  338. consensusReactor.SetLogger(consensusLogger)
  339. // services which will be publishing and/or subscribing for messages (events)
  340. // consensusReactor will set it on consensusState and blockExecutor
  341. consensusReactor.SetEventBus(eventBus)
  342. p2pLogger := logger.With("module", "p2p")
  343. nodeInfo, err := makeNodeInfo(
  344. config,
  345. nodeKey.ID(),
  346. txIndexer,
  347. genDoc.ChainID,
  348. p2p.NewProtocolVersion(
  349. version.P2PProtocol, // global
  350. state.Version.Consensus.Block,
  351. state.Version.Consensus.App,
  352. ),
  353. )
  354. if err != nil {
  355. return nil, err
  356. }
  357. // Setup Transport.
  358. var (
  359. mConnConfig = p2p.MConnConfig(config.P2P)
  360. transport = p2p.NewMultiplexTransport(nodeInfo, *nodeKey, mConnConfig)
  361. connFilters = []p2p.ConnFilterFunc{}
  362. peerFilters = []p2p.PeerFilterFunc{}
  363. )
  364. if !config.P2P.AllowDuplicateIP {
  365. connFilters = append(connFilters, p2p.ConnDuplicateIPFilter())
  366. }
  367. // Filter peers by addr or pubkey with an ABCI query.
  368. // If the query return code is OK, add peer.
  369. if config.FilterPeers {
  370. connFilters = append(
  371. connFilters,
  372. // ABCI query for address filtering.
  373. func(_ p2p.ConnSet, c net.Conn, _ []net.IP) error {
  374. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  375. Path: fmt.Sprintf("/p2p/filter/addr/%s", c.RemoteAddr().String()),
  376. })
  377. if err != nil {
  378. return err
  379. }
  380. if res.IsErr() {
  381. return fmt.Errorf("Error querying abci app: %v", res)
  382. }
  383. return nil
  384. },
  385. )
  386. peerFilters = append(
  387. peerFilters,
  388. // ABCI query for ID filtering.
  389. func(_ p2p.IPeerSet, p p2p.Peer) error {
  390. res, err := proxyApp.Query().QuerySync(abci.RequestQuery{
  391. Path: fmt.Sprintf("/p2p/filter/id/%s", p.ID()),
  392. })
  393. if err != nil {
  394. return err
  395. }
  396. if res.IsErr() {
  397. return fmt.Errorf("Error querying abci app: %v", res)
  398. }
  399. return nil
  400. },
  401. )
  402. }
  403. p2p.MultiplexTransportConnFilters(connFilters...)(transport)
  404. // Setup Switch.
  405. sw := p2p.NewSwitch(
  406. config.P2P,
  407. transport,
  408. p2p.WithMetrics(p2pMetrics),
  409. p2p.SwitchPeerFilters(peerFilters...),
  410. )
  411. sw.SetLogger(p2pLogger)
  412. sw.AddReactor("MEMPOOL", mempoolReactor)
  413. sw.AddReactor("BLOCKCHAIN", bcReactor)
  414. sw.AddReactor("CONSENSUS", consensusReactor)
  415. sw.AddReactor("EVIDENCE", evidenceReactor)
  416. sw.SetNodeInfo(nodeInfo)
  417. sw.SetNodeKey(nodeKey)
  418. p2pLogger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", config.NodeKeyFile())
  419. // Optionally, start the pex reactor
  420. //
  421. // TODO:
  422. //
  423. // We need to set Seeds and PersistentPeers on the switch,
  424. // since it needs to be able to use these (and their DNS names)
  425. // even if the PEX is off. We can include the DNS name in the NetAddress,
  426. // but it would still be nice to have a clear list of the current "PersistentPeers"
  427. // somewhere that we can return with net_info.
  428. //
  429. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  430. // Note we currently use the addrBook regardless at least for AddOurAddress
  431. addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  432. // Add ourselves to addrbook to prevent dialing ourselves
  433. addrBook.AddOurAddress(nodeInfo.NetAddress())
  434. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  435. if config.P2P.PexReactor {
  436. // TODO persistent peers ? so we can have their DNS addrs saved
  437. pexReactor := pex.NewPEXReactor(addrBook,
  438. &pex.PEXReactorConfig{
  439. Seeds: splitAndTrimEmpty(config.P2P.Seeds, ",", " "),
  440. SeedMode: config.P2P.SeedMode,
  441. })
  442. pexReactor.SetLogger(logger.With("module", "pex"))
  443. sw.AddReactor("PEX", pexReactor)
  444. }
  445. sw.SetAddrBook(addrBook)
  446. // run the profile server
  447. profileHost := config.ProfListenAddress
  448. if profileHost != "" {
  449. go func() {
  450. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  451. }()
  452. }
  453. node := &Node{
  454. config: config,
  455. genesisDoc: genDoc,
  456. privValidator: privValidator,
  457. transport: transport,
  458. sw: sw,
  459. addrBook: addrBook,
  460. nodeInfo: nodeInfo,
  461. nodeKey: nodeKey,
  462. stateDB: stateDB,
  463. blockStore: blockStore,
  464. bcReactor: bcReactor,
  465. mempoolReactor: mempoolReactor,
  466. consensusState: consensusState,
  467. consensusReactor: consensusReactor,
  468. evidencePool: evidencePool,
  469. proxyApp: proxyApp,
  470. txIndexer: txIndexer,
  471. indexerService: indexerService,
  472. eventBus: eventBus,
  473. }
  474. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  475. return node, nil
  476. }
  477. // OnStart starts the Node. It implements cmn.Service.
  478. func (n *Node) OnStart() error {
  479. now := tmtime.Now()
  480. genTime := n.genesisDoc.GenesisTime
  481. if genTime.After(now) {
  482. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  483. time.Sleep(genTime.Sub(now))
  484. }
  485. // Add private IDs to addrbook to block those peers being added
  486. n.addrBook.AddPrivateIDs(splitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  487. // Start the RPC server before the P2P server
  488. // so we can eg. receive txs for the first block
  489. if n.config.RPC.ListenAddress != "" {
  490. listeners, err := n.startRPC()
  491. if err != nil {
  492. return err
  493. }
  494. n.rpcListeners = listeners
  495. }
  496. if n.config.Instrumentation.Prometheus &&
  497. n.config.Instrumentation.PrometheusListenAddr != "" {
  498. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  499. }
  500. // Start the transport.
  501. addr, err := p2p.NewNetAddressStringWithOptionalID(n.config.P2P.ListenAddress)
  502. if err != nil {
  503. return err
  504. }
  505. if err := n.transport.Listen(*addr); err != nil {
  506. return err
  507. }
  508. n.isListening = true
  509. // Start the switch (the P2P server).
  510. err = n.sw.Start()
  511. if err != nil {
  512. return err
  513. }
  514. // Always connect to persistent peers
  515. if n.config.P2P.PersistentPeers != "" {
  516. err = n.sw.DialPeersAsync(n.addrBook, splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "), true)
  517. if err != nil {
  518. return err
  519. }
  520. }
  521. return nil
  522. }
  523. // OnStop stops the Node. It implements cmn.Service.
  524. func (n *Node) OnStop() {
  525. n.BaseService.OnStop()
  526. n.Logger.Info("Stopping Node")
  527. // first stop the non-reactor services
  528. n.eventBus.Stop()
  529. n.indexerService.Stop()
  530. // now stop the reactors
  531. // TODO: gracefully disconnect from peers.
  532. n.sw.Stop()
  533. // stop mempool WAL
  534. if n.config.Mempool.WalEnabled() {
  535. n.mempoolReactor.Mempool.CloseWAL()
  536. }
  537. if err := n.transport.Close(); err != nil {
  538. n.Logger.Error("Error closing transport", "err", err)
  539. }
  540. n.isListening = false
  541. // finally stop the listeners / external services
  542. for _, l := range n.rpcListeners {
  543. n.Logger.Info("Closing rpc listener", "listener", l)
  544. if err := l.Close(); err != nil {
  545. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  546. }
  547. }
  548. if pvsc, ok := n.privValidator.(cmn.Service); ok {
  549. pvsc.Stop()
  550. }
  551. if n.prometheusSrv != nil {
  552. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  553. // Error from closing listeners, or context timeout:
  554. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  555. }
  556. }
  557. }
  558. // ConfigureRPC sets all variables in rpccore so they will serve
  559. // rpc calls from this node
  560. func (n *Node) ConfigureRPC() {
  561. rpccore.SetStateDB(n.stateDB)
  562. rpccore.SetBlockStore(n.blockStore)
  563. rpccore.SetConsensusState(n.consensusState)
  564. rpccore.SetMempool(n.mempoolReactor.Mempool)
  565. rpccore.SetEvidencePool(n.evidencePool)
  566. rpccore.SetP2PPeers(n.sw)
  567. rpccore.SetP2PTransport(n)
  568. pubKey := n.privValidator.GetPubKey()
  569. rpccore.SetPubKey(pubKey)
  570. rpccore.SetGenesisDoc(n.genesisDoc)
  571. rpccore.SetAddrBook(n.addrBook)
  572. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  573. rpccore.SetTxIndexer(n.txIndexer)
  574. rpccore.SetConsensusReactor(n.consensusReactor)
  575. rpccore.SetEventBus(n.eventBus)
  576. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  577. }
  578. func (n *Node) startRPC() ([]net.Listener, error) {
  579. n.ConfigureRPC()
  580. listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  581. coreCodec := amino.NewCodec()
  582. ctypes.RegisterAmino(coreCodec)
  583. if n.config.RPC.Unsafe {
  584. rpccore.AddUnsafeRoutes()
  585. }
  586. // we may expose the rpc over both a unix and tcp socket
  587. listeners := make([]net.Listener, len(listenAddrs))
  588. for i, listenAddr := range listenAddrs {
  589. mux := http.NewServeMux()
  590. rpcLogger := n.Logger.With("module", "rpc-server")
  591. wm := rpcserver.NewWebsocketManager(rpccore.Routes, coreCodec, rpcserver.EventSubscriber(n.eventBus))
  592. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  593. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  594. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, coreCodec, rpcLogger)
  595. listener, err := rpcserver.Listen(
  596. listenAddr,
  597. rpcserver.Config{MaxOpenConnections: n.config.RPC.MaxOpenConnections},
  598. )
  599. if err != nil {
  600. return nil, err
  601. }
  602. var rootHandler http.Handler = mux
  603. if n.config.RPC.IsCorsEnabled() {
  604. corsMiddleware := cors.New(cors.Options{
  605. AllowedOrigins: n.config.RPC.CORSAllowedOrigins,
  606. AllowedMethods: n.config.RPC.CORSAllowedMethods,
  607. AllowedHeaders: n.config.RPC.CORSAllowedHeaders,
  608. })
  609. rootHandler = corsMiddleware.Handler(mux)
  610. }
  611. go rpcserver.StartHTTPServer(
  612. listener,
  613. rootHandler,
  614. rpcLogger,
  615. )
  616. listeners[i] = listener
  617. }
  618. // we expose a simplified api over grpc for convenience to app devs
  619. grpcListenAddr := n.config.RPC.GRPCListenAddress
  620. if grpcListenAddr != "" {
  621. listener, err := rpcserver.Listen(
  622. grpcListenAddr, rpcserver.Config{MaxOpenConnections: n.config.RPC.GRPCMaxOpenConnections})
  623. if err != nil {
  624. return nil, err
  625. }
  626. go grpccore.StartGRPCServer(listener)
  627. listeners = append(listeners, listener)
  628. }
  629. return listeners, nil
  630. }
  631. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  632. // collectors on addr.
  633. func (n *Node) startPrometheusServer(addr string) *http.Server {
  634. srv := &http.Server{
  635. Addr: addr,
  636. Handler: promhttp.InstrumentMetricHandler(
  637. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  638. prometheus.DefaultGatherer,
  639. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  640. ),
  641. ),
  642. }
  643. go func() {
  644. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  645. // Error starting or closing listener:
  646. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  647. }
  648. }()
  649. return srv
  650. }
  651. // Switch returns the Node's Switch.
  652. func (n *Node) Switch() *p2p.Switch {
  653. return n.sw
  654. }
  655. // BlockStore returns the Node's BlockStore.
  656. func (n *Node) BlockStore() *bc.BlockStore {
  657. return n.blockStore
  658. }
  659. // ConsensusState returns the Node's ConsensusState.
  660. func (n *Node) ConsensusState() *cs.ConsensusState {
  661. return n.consensusState
  662. }
  663. // ConsensusReactor returns the Node's ConsensusReactor.
  664. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  665. return n.consensusReactor
  666. }
  667. // MempoolReactor returns the Node's MempoolReactor.
  668. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  669. return n.mempoolReactor
  670. }
  671. // EvidencePool returns the Node's EvidencePool.
  672. func (n *Node) EvidencePool() *evidence.EvidencePool {
  673. return n.evidencePool
  674. }
  675. // EventBus returns the Node's EventBus.
  676. func (n *Node) EventBus() *types.EventBus {
  677. return n.eventBus
  678. }
  679. // PrivValidator returns the Node's PrivValidator.
  680. // XXX: for convenience only!
  681. func (n *Node) PrivValidator() types.PrivValidator {
  682. return n.privValidator
  683. }
  684. // GenesisDoc returns the Node's GenesisDoc.
  685. func (n *Node) GenesisDoc() *types.GenesisDoc {
  686. return n.genesisDoc
  687. }
  688. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  689. func (n *Node) ProxyApp() proxy.AppConns {
  690. return n.proxyApp
  691. }
  692. //------------------------------------------------------------------------------
  693. func (n *Node) Listeners() []string {
  694. return []string{
  695. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  696. }
  697. }
  698. func (n *Node) IsListening() bool {
  699. return n.isListening
  700. }
  701. // NodeInfo returns the Node's Info from the Switch.
  702. func (n *Node) NodeInfo() p2p.NodeInfo {
  703. return n.nodeInfo
  704. }
  705. func makeNodeInfo(
  706. config *cfg.Config,
  707. nodeID p2p.ID,
  708. txIndexer txindex.TxIndexer,
  709. chainID string,
  710. protocolVersion p2p.ProtocolVersion,
  711. ) (p2p.NodeInfo, error) {
  712. txIndexerStatus := "on"
  713. if _, ok := txIndexer.(*null.TxIndex); ok {
  714. txIndexerStatus = "off"
  715. }
  716. nodeInfo := p2p.DefaultNodeInfo{
  717. ProtocolVersion: protocolVersion,
  718. ID_: nodeID,
  719. Network: chainID,
  720. Version: version.TMCoreSemVer,
  721. Channels: []byte{
  722. bc.BlockchainChannel,
  723. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  724. mempl.MempoolChannel,
  725. evidence.EvidenceChannel,
  726. },
  727. Moniker: config.Moniker,
  728. Other: p2p.DefaultNodeInfoOther{
  729. TxIndex: txIndexerStatus,
  730. RPCAddress: config.RPC.ListenAddress,
  731. },
  732. }
  733. if config.P2P.PexReactor {
  734. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  735. }
  736. lAddr := config.P2P.ExternalAddress
  737. if lAddr == "" {
  738. lAddr = config.P2P.ListenAddress
  739. }
  740. nodeInfo.ListenAddr = lAddr
  741. err := nodeInfo.Validate()
  742. return nodeInfo, err
  743. }
  744. //------------------------------------------------------------------------------
  745. var (
  746. genesisDocKey = []byte("genesisDoc")
  747. )
  748. // panics if failed to unmarshal bytes
  749. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  750. bytes := db.Get(genesisDocKey)
  751. if len(bytes) == 0 {
  752. return nil, errors.New("Genesis doc not found")
  753. }
  754. var genDoc *types.GenesisDoc
  755. err := cdc.UnmarshalJSON(bytes, &genDoc)
  756. if err != nil {
  757. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  758. }
  759. return genDoc, nil
  760. }
  761. // panics if failed to marshal the given genesis document
  762. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  763. bytes, err := cdc.MarshalJSON(genDoc)
  764. if err != nil {
  765. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  766. }
  767. db.SetSync(genesisDocKey, bytes)
  768. }
  769. func createAndStartPrivValidatorSocketClient(
  770. listenAddr string,
  771. logger log.Logger,
  772. ) (types.PrivValidator, error) {
  773. var listener net.Listener
  774. protocol, address := cmn.ProtocolAndAddress(listenAddr)
  775. ln, err := net.Listen(protocol, address)
  776. if err != nil {
  777. return nil, err
  778. }
  779. switch protocol {
  780. case "unix":
  781. listener = privval.NewUnixListener(ln)
  782. case "tcp":
  783. // TODO: persist this key so external signer
  784. // can actually authenticate us
  785. listener = privval.NewTCPListener(ln, ed25519.GenPrivKey())
  786. default:
  787. return nil, fmt.Errorf(
  788. "Wrong listen address: expected either 'tcp' or 'unix' protocols, got %s",
  789. protocol,
  790. )
  791. }
  792. pvsc := privval.NewSocketVal(logger.With("module", "privval"), listener)
  793. if err := pvsc.Start(); err != nil {
  794. return nil, errors.Wrap(err, "failed to start private validator")
  795. }
  796. return pvsc, nil
  797. }
  798. // splitAndTrimEmpty slices s into all subslices separated by sep and returns a
  799. // slice of the string s with all leading and trailing Unicode code points
  800. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  801. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  802. // -1. also filter out empty strings, only return non-empty strings.
  803. func splitAndTrimEmpty(s, sep, cutset string) []string {
  804. if s == "" {
  805. return []string{}
  806. }
  807. spl := strings.Split(s, sep)
  808. nonEmptyStrings := make([]string, 0, len(spl))
  809. for i := 0; i < len(spl); i++ {
  810. element := strings.Trim(spl[i], cutset)
  811. if element != "" {
  812. nonEmptyStrings = append(nonEmptyStrings, element)
  813. }
  814. }
  815. return nonEmptyStrings
  816. }