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.

610 lines
18 KiB

9 years ago
10 years ago
10 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
10 years ago
7 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
7 years ago
10 years ago
7 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
10 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
7 years ago
9 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
9 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "strings"
  10. abci "github.com/tendermint/abci/types"
  11. crypto "github.com/tendermint/go-crypto"
  12. wire "github.com/tendermint/go-wire"
  13. cmn "github.com/tendermint/tmlibs/common"
  14. dbm "github.com/tendermint/tmlibs/db"
  15. "github.com/tendermint/tmlibs/log"
  16. bc "github.com/tendermint/tendermint/blockchain"
  17. cfg "github.com/tendermint/tendermint/config"
  18. "github.com/tendermint/tendermint/consensus"
  19. "github.com/tendermint/tendermint/evidence"
  20. mempl "github.com/tendermint/tendermint/mempool"
  21. "github.com/tendermint/tendermint/p2p"
  22. "github.com/tendermint/tendermint/p2p/trust"
  23. "github.com/tendermint/tendermint/proxy"
  24. rpccore "github.com/tendermint/tendermint/rpc/core"
  25. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  26. rpc "github.com/tendermint/tendermint/rpc/lib"
  27. rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
  28. sm "github.com/tendermint/tendermint/state"
  29. "github.com/tendermint/tendermint/state/txindex"
  30. "github.com/tendermint/tendermint/state/txindex/kv"
  31. "github.com/tendermint/tendermint/state/txindex/null"
  32. "github.com/tendermint/tendermint/types"
  33. "github.com/tendermint/tendermint/version"
  34. _ "net/http/pprof"
  35. )
  36. //------------------------------------------------------------------------------
  37. // DBContext specifies config information for loading a new DB.
  38. type DBContext struct {
  39. ID string
  40. Config *cfg.Config
  41. }
  42. // DBProvider takes a DBContext and returns an instantiated DB.
  43. type DBProvider func(*DBContext) (dbm.DB, error)
  44. // DefaultDBProvider returns a database using the DBBackend and DBDir
  45. // specified in the ctx.Config.
  46. func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) {
  47. return dbm.NewDB(ctx.ID, ctx.Config.DBBackend, ctx.Config.DBDir()), nil
  48. }
  49. // GenesisDocProvider returns a GenesisDoc.
  50. // It allows the GenesisDoc to be pulled from sources other than the
  51. // filesystem, for instance from a distributed key-value store cluster.
  52. type GenesisDocProvider func() (*types.GenesisDoc, error)
  53. // DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  54. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  55. func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider {
  56. return func() (*types.GenesisDoc, error) {
  57. return types.GenesisDocFromFile(config.GenesisFile())
  58. }
  59. }
  60. // NodeProvider takes a config and a logger and returns a ready to go Node.
  61. type NodeProvider func(*cfg.Config, log.Logger) (*Node, error)
  62. // DefaultNewNode returns a Tendermint node with default settings for the
  63. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  64. // It implements NodeProvider.
  65. func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) {
  66. return NewNode(config,
  67. types.LoadOrGenPrivValidatorFS(config.PrivValidatorFile()),
  68. proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()),
  69. DefaultGenesisDocProviderFunc(config),
  70. DefaultDBProvider,
  71. logger)
  72. }
  73. //------------------------------------------------------------------------------
  74. // Node is the highest level interface to a full Tendermint node.
  75. // It includes all configuration information and running services.
  76. type Node struct {
  77. cmn.BaseService
  78. // config
  79. config *cfg.Config
  80. genesisDoc *types.GenesisDoc // initial validator set
  81. privValidator types.PrivValidator // local node's validator key
  82. // network
  83. sw *p2p.Switch // p2p connections
  84. addrBook *p2p.AddrBook // known peers
  85. trustMetricStore *trust.TrustMetricStore // trust metrics for all peers
  86. // services
  87. eventBus *types.EventBus // pub/sub for services
  88. stateDB dbm.DB
  89. blockStore *bc.BlockStore // store the blockchain to disk
  90. bcReactor *bc.BlockchainReactor // for fast-syncing
  91. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  92. consensusState *consensus.ConsensusState // latest consensus state
  93. consensusReactor *consensus.ConsensusReactor // for participating in the consensus
  94. evidencePool *evidence.EvidencePool // tracking evidence
  95. proxyApp proxy.AppConns // connection to the application
  96. rpcListeners []net.Listener // rpc servers
  97. txIndexer txindex.TxIndexer
  98. indexerService *txindex.IndexerService
  99. }
  100. // NewNode returns a new, ready to go, Tendermint Node.
  101. func NewNode(config *cfg.Config,
  102. privValidator types.PrivValidator,
  103. clientCreator proxy.ClientCreator,
  104. genesisDocProvider GenesisDocProvider,
  105. dbProvider DBProvider,
  106. logger log.Logger) (*Node, error) {
  107. // Get BlockStore
  108. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  109. if err != nil {
  110. return nil, err
  111. }
  112. blockStore := bc.NewBlockStore(blockStoreDB)
  113. // Get State
  114. stateDB, err := dbProvider(&DBContext{"state", config})
  115. if err != nil {
  116. return nil, err
  117. }
  118. // Get genesis doc
  119. // TODO: move to state package?
  120. genDoc, err := loadGenesisDoc(stateDB)
  121. if err != nil {
  122. genDoc, err = genesisDocProvider()
  123. if err != nil {
  124. return nil, err
  125. }
  126. // save genesis doc to prevent a certain class of user errors (e.g. when it
  127. // was changed, accidentally or not). Also good for audit trail.
  128. saveGenesisDoc(stateDB, genDoc)
  129. }
  130. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  131. if err != nil {
  132. return nil, err
  133. }
  134. // Create the proxyApp, which manages connections (consensus, mempool, query)
  135. // and sync tendermint and the app by performing a handshake
  136. // and replaying any necessary blocks
  137. consensusLogger := logger.With("module", "consensus")
  138. handshaker := consensus.NewHandshaker(stateDB, state, blockStore)
  139. handshaker.SetLogger(consensusLogger)
  140. proxyApp := proxy.NewAppConns(clientCreator, handshaker)
  141. proxyApp.SetLogger(logger.With("module", "proxy"))
  142. if err := proxyApp.Start(); err != nil {
  143. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  144. }
  145. // reload the state (it may have been updated by the handshake)
  146. state = sm.LoadState(stateDB)
  147. // Decide whether to fast-sync or not
  148. // We don't fast-sync when the only validator is us.
  149. fastSync := config.FastSync
  150. if state.Validators.Size() == 1 {
  151. addr, _ := state.Validators.GetByIndex(0)
  152. if bytes.Equal(privValidator.GetAddress(), addr) {
  153. fastSync = false
  154. }
  155. }
  156. // Log whether this node is a validator or an observer
  157. if state.Validators.HasAddress(privValidator.GetAddress()) {
  158. consensusLogger.Info("This node is a validator")
  159. } else {
  160. consensusLogger.Info("This node is not a validator")
  161. }
  162. // Make MempoolReactor
  163. mempoolLogger := logger.With("module", "mempool")
  164. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight)
  165. mempool.SetLogger(mempoolLogger)
  166. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  167. mempoolReactor.SetLogger(mempoolLogger)
  168. if config.Consensus.WaitForTxs() {
  169. mempool.EnableTxsAvailable()
  170. }
  171. // Make Evidence Reactor
  172. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  173. if err != nil {
  174. return nil, err
  175. }
  176. evidenceLogger := logger.With("module", "evidence")
  177. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  178. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  179. evidencePool.SetLogger(evidenceLogger)
  180. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  181. evidenceReactor.SetLogger(evidenceLogger)
  182. blockExecLogger := logger.With("module", "state")
  183. // make block executor for consensus and blockchain reactors to execute blocks
  184. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  185. // Make BlockchainReactor
  186. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  187. bcReactor.SetLogger(logger.With("module", "blockchain"))
  188. // Make ConsensusReactor
  189. consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(),
  190. blockExec, blockStore, mempool, evidencePool)
  191. consensusState.SetLogger(consensusLogger)
  192. if privValidator != nil {
  193. consensusState.SetPrivValidator(privValidator)
  194. }
  195. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  196. consensusReactor.SetLogger(consensusLogger)
  197. p2pLogger := logger.With("module", "p2p")
  198. sw := p2p.NewSwitch(config.P2P)
  199. sw.SetLogger(p2pLogger)
  200. sw.AddReactor("MEMPOOL", mempoolReactor)
  201. sw.AddReactor("BLOCKCHAIN", bcReactor)
  202. sw.AddReactor("CONSENSUS", consensusReactor)
  203. sw.AddReactor("EVIDENCE", evidenceReactor)
  204. // Optionally, start the pex reactor
  205. var addrBook *p2p.AddrBook
  206. var trustMetricStore *trust.TrustMetricStore
  207. if config.P2P.PexReactor {
  208. addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  209. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  210. // Get the trust metric history data
  211. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  212. if err != nil {
  213. return nil, err
  214. }
  215. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  216. trustMetricStore.SetLogger(p2pLogger)
  217. pexReactor := p2p.NewPEXReactor(addrBook)
  218. pexReactor.SetLogger(p2pLogger)
  219. sw.AddReactor("PEX", pexReactor)
  220. }
  221. // Filter peers by addr or pubkey with an ABCI query.
  222. // If the query return code is OK, add peer.
  223. // XXX: Query format subject to change
  224. if config.FilterPeers {
  225. // NOTE: addr is ip:port
  226. sw.SetAddrFilter(func(addr net.Addr) error {
  227. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  228. if err != nil {
  229. return err
  230. }
  231. if resQuery.IsErr() {
  232. return resQuery
  233. }
  234. return nil
  235. })
  236. sw.SetPubKeyFilter(func(pubkey crypto.PubKey) error {
  237. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  238. if err != nil {
  239. return err
  240. }
  241. if resQuery.IsErr() {
  242. return resQuery
  243. }
  244. return nil
  245. })
  246. }
  247. eventBus := types.NewEventBus()
  248. eventBus.SetLogger(logger.With("module", "events"))
  249. // services which will be publishing and/or subscribing for messages (events)
  250. // consensusReactor will set it on consensusState and blockExecutor
  251. consensusReactor.SetEventBus(eventBus)
  252. // Transaction indexing
  253. var txIndexer txindex.TxIndexer
  254. switch config.TxIndex.Indexer {
  255. case "kv":
  256. store, err := dbProvider(&DBContext{"tx_index", config})
  257. if err != nil {
  258. return nil, err
  259. }
  260. if config.TxIndex.IndexTags != "" {
  261. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  262. } else if config.TxIndex.IndexAllTags {
  263. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  264. } else {
  265. txIndexer = kv.NewTxIndex(store)
  266. }
  267. default:
  268. txIndexer = &null.TxIndex{}
  269. }
  270. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  271. // run the profile server
  272. profileHost := config.ProfListenAddress
  273. if profileHost != "" {
  274. go func() {
  275. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  276. }()
  277. }
  278. node := &Node{
  279. config: config,
  280. genesisDoc: genDoc,
  281. privValidator: privValidator,
  282. sw: sw,
  283. addrBook: addrBook,
  284. trustMetricStore: trustMetricStore,
  285. stateDB: stateDB,
  286. blockStore: blockStore,
  287. bcReactor: bcReactor,
  288. mempoolReactor: mempoolReactor,
  289. consensusState: consensusState,
  290. consensusReactor: consensusReactor,
  291. evidencePool: evidencePool,
  292. proxyApp: proxyApp,
  293. txIndexer: txIndexer,
  294. indexerService: indexerService,
  295. eventBus: eventBus,
  296. }
  297. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  298. return node, nil
  299. }
  300. // OnStart starts the Node. It implements cmn.Service.
  301. func (n *Node) OnStart() error {
  302. err := n.eventBus.Start()
  303. if err != nil {
  304. return err
  305. }
  306. // Run the RPC server first
  307. // so we can eg. receive txs for the first block
  308. if n.config.RPC.ListenAddress != "" {
  309. listeners, err := n.startRPC()
  310. if err != nil {
  311. return err
  312. }
  313. n.rpcListeners = listeners
  314. }
  315. // Create & add listener
  316. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  317. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  318. n.sw.AddListener(l)
  319. // Generate node PrivKey
  320. // TODO: Load
  321. privKey := crypto.GenPrivKeyEd25519().Wrap()
  322. // Start the switch
  323. n.sw.SetNodeInfo(n.makeNodeInfo(privKey.PubKey()))
  324. n.sw.SetNodePrivKey(privKey)
  325. err = n.sw.Start()
  326. if err != nil {
  327. return err
  328. }
  329. // If seeds exist, add them to the address book and dial out
  330. if n.config.P2P.Seeds != "" {
  331. // dial out
  332. seeds := strings.Split(n.config.P2P.Seeds, ",")
  333. if err := n.DialSeeds(seeds); err != nil {
  334. return err
  335. }
  336. }
  337. // start tx indexer
  338. return n.indexerService.Start()
  339. }
  340. // OnStop stops the Node. It implements cmn.Service.
  341. func (n *Node) OnStop() {
  342. n.BaseService.OnStop()
  343. n.Logger.Info("Stopping Node")
  344. // TODO: gracefully disconnect from peers.
  345. n.sw.Stop()
  346. for _, l := range n.rpcListeners {
  347. n.Logger.Info("Closing rpc listener", "listener", l)
  348. if err := l.Close(); err != nil {
  349. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  350. }
  351. }
  352. n.eventBus.Stop()
  353. n.indexerService.Stop()
  354. }
  355. // RunForever waits for an interrupt signal and stops the node.
  356. func (n *Node) RunForever() {
  357. // Sleep forever and then...
  358. cmn.TrapSignal(func() {
  359. n.Stop()
  360. })
  361. }
  362. // AddListener adds a listener to accept inbound peer connections.
  363. // It should be called before starting the Node.
  364. // The first listener is the primary listener (in NodeInfo)
  365. func (n *Node) AddListener(l p2p.Listener) {
  366. n.sw.AddListener(l)
  367. }
  368. // ConfigureRPC sets all variables in rpccore so they will serve
  369. // rpc calls from this node
  370. func (n *Node) ConfigureRPC() {
  371. rpccore.SetStateDB(n.stateDB)
  372. rpccore.SetBlockStore(n.blockStore)
  373. rpccore.SetConsensusState(n.consensusState)
  374. rpccore.SetMempool(n.mempoolReactor.Mempool)
  375. rpccore.SetEvidencePool(n.evidencePool)
  376. rpccore.SetSwitch(n.sw)
  377. rpccore.SetPubKey(n.privValidator.GetPubKey())
  378. rpccore.SetGenesisDoc(n.genesisDoc)
  379. rpccore.SetAddrBook(n.addrBook)
  380. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  381. rpccore.SetTxIndexer(n.txIndexer)
  382. rpccore.SetConsensusReactor(n.consensusReactor)
  383. rpccore.SetEventBus(n.eventBus)
  384. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  385. }
  386. func (n *Node) startRPC() ([]net.Listener, error) {
  387. n.ConfigureRPC()
  388. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  389. if n.config.RPC.Unsafe {
  390. rpccore.AddUnsafeRoutes()
  391. }
  392. // we may expose the rpc over both a unix and tcp socket
  393. listeners := make([]net.Listener, len(listenAddrs))
  394. for i, listenAddr := range listenAddrs {
  395. mux := http.NewServeMux()
  396. rpcLogger := n.Logger.With("module", "rpc-server")
  397. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  398. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  399. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  400. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  401. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  402. if err != nil {
  403. return nil, err
  404. }
  405. listeners[i] = listener
  406. }
  407. // we expose a simplified api over grpc for convenience to app devs
  408. grpcListenAddr := n.config.RPC.GRPCListenAddress
  409. if grpcListenAddr != "" {
  410. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  411. if err != nil {
  412. return nil, err
  413. }
  414. listeners = append(listeners, listener)
  415. }
  416. return listeners, nil
  417. }
  418. // Switch returns the Node's Switch.
  419. func (n *Node) Switch() *p2p.Switch {
  420. return n.sw
  421. }
  422. // BlockStore returns the Node's BlockStore.
  423. func (n *Node) BlockStore() *bc.BlockStore {
  424. return n.blockStore
  425. }
  426. // ConsensusState returns the Node's ConsensusState.
  427. func (n *Node) ConsensusState() *consensus.ConsensusState {
  428. return n.consensusState
  429. }
  430. // ConsensusReactor returns the Node's ConsensusReactor.
  431. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  432. return n.consensusReactor
  433. }
  434. // MempoolReactor returns the Node's MempoolReactor.
  435. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  436. return n.mempoolReactor
  437. }
  438. // EvidencePool returns the Node's EvidencePool.
  439. func (n *Node) EvidencePool() *evidence.EvidencePool {
  440. return n.evidencePool
  441. }
  442. // EventBus returns the Node's EventBus.
  443. func (n *Node) EventBus() *types.EventBus {
  444. return n.eventBus
  445. }
  446. // PrivValidator returns the Node's PrivValidator.
  447. // XXX: for convenience only!
  448. func (n *Node) PrivValidator() types.PrivValidator {
  449. return n.privValidator
  450. }
  451. // GenesisDoc returns the Node's GenesisDoc.
  452. func (n *Node) GenesisDoc() *types.GenesisDoc {
  453. return n.genesisDoc
  454. }
  455. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  456. func (n *Node) ProxyApp() proxy.AppConns {
  457. return n.proxyApp
  458. }
  459. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) *p2p.NodeInfo {
  460. txIndexerStatus := "on"
  461. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  462. txIndexerStatus = "off"
  463. }
  464. nodeInfo := &p2p.NodeInfo{
  465. PubKey: pubKey,
  466. Moniker: n.config.Moniker,
  467. Network: n.genesisDoc.ChainID,
  468. Version: version.Version,
  469. Other: []string{
  470. cmn.Fmt("wire_version=%v", wire.Version),
  471. cmn.Fmt("p2p_version=%v", p2p.Version),
  472. cmn.Fmt("consensus_version=%v", consensus.Version),
  473. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  474. cmn.Fmt("tx_index=%v", txIndexerStatus),
  475. },
  476. }
  477. rpcListenAddr := n.config.RPC.ListenAddress
  478. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  479. if !n.sw.IsListening() {
  480. return nodeInfo
  481. }
  482. p2pListener := n.sw.Listeners()[0]
  483. p2pHost := p2pListener.ExternalAddress().IP.String()
  484. p2pPort := p2pListener.ExternalAddress().Port
  485. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  486. return nodeInfo
  487. }
  488. //------------------------------------------------------------------------------
  489. // NodeInfo returns the Node's Info from the Switch.
  490. func (n *Node) NodeInfo() *p2p.NodeInfo {
  491. return n.sw.NodeInfo()
  492. }
  493. // DialSeeds dials the given seeds on the Switch.
  494. func (n *Node) DialSeeds(seeds []string) error {
  495. return n.sw.DialSeeds(n.addrBook, seeds)
  496. }
  497. //------------------------------------------------------------------------------
  498. var (
  499. genesisDocKey = []byte("genesisDoc")
  500. )
  501. // panics if failed to unmarshal bytes
  502. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  503. bytes := db.Get(genesisDocKey)
  504. if len(bytes) == 0 {
  505. return nil, errors.New("Genesis doc not found")
  506. } else {
  507. var genDoc *types.GenesisDoc
  508. err := json.Unmarshal(bytes, &genDoc)
  509. if err != nil {
  510. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  511. }
  512. return genDoc, nil
  513. }
  514. }
  515. // panics if failed to marshal the given genesis document
  516. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  517. bytes, err := json.Marshal(genDoc)
  518. if err != nil {
  519. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  520. }
  521. db.SetSync(genesisDocKey, bytes)
  522. }