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.

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