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.

609 lines
19 KiB

10 years ago
10 years ago
11 years ago
11 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
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
8 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
8 years ago
11 years ago
8 years ago
11 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
8 years ago
8 years ago
11 years ago
8 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
8 years ago
11 years ago
11 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
8 years ago
8 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
8 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", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  159. } else {
  160. consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  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. &p2p.PEXReactorConfig{Seeds: strings.Split(config.P2P.Seeds, ",")})
  219. pexReactor.SetLogger(p2pLogger)
  220. sw.AddReactor("PEX", pexReactor)
  221. }
  222. // Filter peers by addr or pubkey with an ABCI query.
  223. // If the query return code is OK, add peer.
  224. // XXX: Query format subject to change
  225. if config.FilterPeers {
  226. // NOTE: addr is ip:port
  227. sw.SetAddrFilter(func(addr net.Addr) error {
  228. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  229. if err != nil {
  230. return err
  231. }
  232. if resQuery.IsErr() {
  233. return resQuery
  234. }
  235. return nil
  236. })
  237. sw.SetPubKeyFilter(func(pubkey crypto.PubKey) error {
  238. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  239. if err != nil {
  240. return err
  241. }
  242. if resQuery.IsErr() {
  243. return resQuery
  244. }
  245. return nil
  246. })
  247. }
  248. eventBus := types.NewEventBus()
  249. eventBus.SetLogger(logger.With("module", "events"))
  250. // services which will be publishing and/or subscribing for messages (events)
  251. // consensusReactor will set it on consensusState and blockExecutor
  252. consensusReactor.SetEventBus(eventBus)
  253. // Transaction indexing
  254. var txIndexer txindex.TxIndexer
  255. switch config.TxIndex.Indexer {
  256. case "kv":
  257. store, err := dbProvider(&DBContext{"tx_index", config})
  258. if err != nil {
  259. return nil, err
  260. }
  261. if config.TxIndex.IndexTags != "" {
  262. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  263. } else if config.TxIndex.IndexAllTags {
  264. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  265. } else {
  266. txIndexer = kv.NewTxIndex(store)
  267. }
  268. default:
  269. txIndexer = &null.TxIndex{}
  270. }
  271. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  272. // run the profile server
  273. profileHost := config.ProfListenAddress
  274. if profileHost != "" {
  275. go func() {
  276. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  277. }()
  278. }
  279. node := &Node{
  280. config: config,
  281. genesisDoc: genDoc,
  282. privValidator: privValidator,
  283. sw: sw,
  284. addrBook: addrBook,
  285. trustMetricStore: trustMetricStore,
  286. stateDB: stateDB,
  287. blockStore: blockStore,
  288. bcReactor: bcReactor,
  289. mempoolReactor: mempoolReactor,
  290. consensusState: consensusState,
  291. consensusReactor: consensusReactor,
  292. evidencePool: evidencePool,
  293. proxyApp: proxyApp,
  294. txIndexer: txIndexer,
  295. indexerService: indexerService,
  296. eventBus: eventBus,
  297. }
  298. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  299. return node, nil
  300. }
  301. // OnStart starts the Node. It implements cmn.Service.
  302. func (n *Node) OnStart() error {
  303. err := n.eventBus.Start()
  304. if err != nil {
  305. return err
  306. }
  307. // Run the RPC server first
  308. // so we can eg. receive txs for the first block
  309. if n.config.RPC.ListenAddress != "" {
  310. listeners, err := n.startRPC()
  311. if err != nil {
  312. return err
  313. }
  314. n.rpcListeners = listeners
  315. }
  316. // Create & add listener
  317. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  318. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  319. n.sw.AddListener(l)
  320. // Generate node PrivKey
  321. // TODO: pass in like priv_val
  322. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  323. if err != nil {
  324. return err
  325. }
  326. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  327. // Start the switch
  328. n.sw.SetNodeInfo(n.makeNodeInfo(nodeKey.PubKey()))
  329. n.sw.SetNodeKey(nodeKey)
  330. err = n.sw.Start()
  331. if err != nil {
  332. return err
  333. }
  334. // Always connect to persistent peers
  335. if n.config.P2P.PersistentPeers != "" {
  336. err = n.sw.DialPeersAsync(n.addrBook, strings.Split(n.config.P2P.PersistentPeers, ","), true)
  337. if err != nil {
  338. return err
  339. }
  340. }
  341. // start tx indexer
  342. return n.indexerService.Start()
  343. }
  344. // OnStop stops the Node. It implements cmn.Service.
  345. func (n *Node) OnStop() {
  346. n.BaseService.OnStop()
  347. n.Logger.Info("Stopping Node")
  348. // TODO: gracefully disconnect from peers.
  349. n.sw.Stop()
  350. for _, l := range n.rpcListeners {
  351. n.Logger.Info("Closing rpc listener", "listener", l)
  352. if err := l.Close(); err != nil {
  353. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  354. }
  355. }
  356. n.eventBus.Stop()
  357. n.indexerService.Stop()
  358. }
  359. // RunForever waits for an interrupt signal and stops the node.
  360. func (n *Node) RunForever() {
  361. // Sleep forever and then...
  362. cmn.TrapSignal(func() {
  363. n.Stop()
  364. })
  365. }
  366. // AddListener adds a listener to accept inbound peer connections.
  367. // It should be called before starting the Node.
  368. // The first listener is the primary listener (in NodeInfo)
  369. func (n *Node) AddListener(l p2p.Listener) {
  370. n.sw.AddListener(l)
  371. }
  372. // ConfigureRPC sets all variables in rpccore so they will serve
  373. // rpc calls from this node
  374. func (n *Node) ConfigureRPC() {
  375. rpccore.SetStateDB(n.stateDB)
  376. rpccore.SetBlockStore(n.blockStore)
  377. rpccore.SetConsensusState(n.consensusState)
  378. rpccore.SetMempool(n.mempoolReactor.Mempool)
  379. rpccore.SetEvidencePool(n.evidencePool)
  380. rpccore.SetSwitch(n.sw)
  381. rpccore.SetPubKey(n.privValidator.GetPubKey())
  382. rpccore.SetGenesisDoc(n.genesisDoc)
  383. rpccore.SetAddrBook(n.addrBook)
  384. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  385. rpccore.SetTxIndexer(n.txIndexer)
  386. rpccore.SetConsensusReactor(n.consensusReactor)
  387. rpccore.SetEventBus(n.eventBus)
  388. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  389. }
  390. func (n *Node) startRPC() ([]net.Listener, error) {
  391. n.ConfigureRPC()
  392. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  393. if n.config.RPC.Unsafe {
  394. rpccore.AddUnsafeRoutes()
  395. }
  396. // we may expose the rpc over both a unix and tcp socket
  397. listeners := make([]net.Listener, len(listenAddrs))
  398. for i, listenAddr := range listenAddrs {
  399. mux := http.NewServeMux()
  400. rpcLogger := n.Logger.With("module", "rpc-server")
  401. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  402. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  403. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  404. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  405. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  406. if err != nil {
  407. return nil, err
  408. }
  409. listeners[i] = listener
  410. }
  411. // we expose a simplified api over grpc for convenience to app devs
  412. grpcListenAddr := n.config.RPC.GRPCListenAddress
  413. if grpcListenAddr != "" {
  414. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  415. if err != nil {
  416. return nil, err
  417. }
  418. listeners = append(listeners, listener)
  419. }
  420. return listeners, nil
  421. }
  422. // Switch returns the Node's Switch.
  423. func (n *Node) Switch() *p2p.Switch {
  424. return n.sw
  425. }
  426. // BlockStore returns the Node's BlockStore.
  427. func (n *Node) BlockStore() *bc.BlockStore {
  428. return n.blockStore
  429. }
  430. // ConsensusState returns the Node's ConsensusState.
  431. func (n *Node) ConsensusState() *consensus.ConsensusState {
  432. return n.consensusState
  433. }
  434. // ConsensusReactor returns the Node's ConsensusReactor.
  435. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  436. return n.consensusReactor
  437. }
  438. // MempoolReactor returns the Node's MempoolReactor.
  439. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  440. return n.mempoolReactor
  441. }
  442. // EvidencePool returns the Node's EvidencePool.
  443. func (n *Node) EvidencePool() *evidence.EvidencePool {
  444. return n.evidencePool
  445. }
  446. // EventBus returns the Node's EventBus.
  447. func (n *Node) EventBus() *types.EventBus {
  448. return n.eventBus
  449. }
  450. // PrivValidator returns the Node's PrivValidator.
  451. // XXX: for convenience only!
  452. func (n *Node) PrivValidator() types.PrivValidator {
  453. return n.privValidator
  454. }
  455. // GenesisDoc returns the Node's GenesisDoc.
  456. func (n *Node) GenesisDoc() *types.GenesisDoc {
  457. return n.genesisDoc
  458. }
  459. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  460. func (n *Node) ProxyApp() proxy.AppConns {
  461. return n.proxyApp
  462. }
  463. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) p2p.NodeInfo {
  464. txIndexerStatus := "on"
  465. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  466. txIndexerStatus = "off"
  467. }
  468. nodeInfo := p2p.NodeInfo{
  469. PubKey: pubKey,
  470. Network: n.genesisDoc.ChainID,
  471. Version: version.Version,
  472. Moniker: n.config.Moniker,
  473. Other: []string{
  474. cmn.Fmt("wire_version=%v", wire.Version),
  475. cmn.Fmt("p2p_version=%v", p2p.Version),
  476. cmn.Fmt("consensus_version=%v", consensus.Version),
  477. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  478. cmn.Fmt("tx_index=%v", txIndexerStatus),
  479. },
  480. }
  481. rpcListenAddr := n.config.RPC.ListenAddress
  482. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  483. if !n.sw.IsListening() {
  484. return nodeInfo
  485. }
  486. p2pListener := n.sw.Listeners()[0]
  487. p2pHost := p2pListener.ExternalAddress().IP.String()
  488. p2pPort := p2pListener.ExternalAddress().Port
  489. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  490. return nodeInfo
  491. }
  492. //------------------------------------------------------------------------------
  493. // NodeInfo returns the Node's Info from the Switch.
  494. func (n *Node) NodeInfo() p2p.NodeInfo {
  495. return n.sw.NodeInfo()
  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. }