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.

614 lines
19 KiB

10 years ago
10 years ago
10 years ago
10 years ago
8 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
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
8 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
8 years ago
10 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
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
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
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", "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.InitWAL() // no need to have the mempool wal during tests
  166. mempool.SetLogger(mempoolLogger)
  167. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  168. mempoolReactor.SetLogger(mempoolLogger)
  169. if config.Consensus.WaitForTxs() {
  170. mempool.EnableTxsAvailable()
  171. }
  172. // Make Evidence Reactor
  173. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  174. if err != nil {
  175. return nil, err
  176. }
  177. evidenceLogger := logger.With("module", "evidence")
  178. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  179. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  180. evidencePool.SetLogger(evidenceLogger)
  181. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  182. evidenceReactor.SetLogger(evidenceLogger)
  183. blockExecLogger := logger.With("module", "state")
  184. // make block executor for consensus and blockchain reactors to execute blocks
  185. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  186. // Make BlockchainReactor
  187. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  188. bcReactor.SetLogger(logger.With("module", "blockchain"))
  189. // Make ConsensusReactor
  190. consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(),
  191. blockExec, blockStore, mempool, evidencePool)
  192. consensusState.SetLogger(consensusLogger)
  193. if privValidator != nil {
  194. consensusState.SetPrivValidator(privValidator)
  195. }
  196. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  197. consensusReactor.SetLogger(consensusLogger)
  198. p2pLogger := logger.With("module", "p2p")
  199. sw := p2p.NewSwitch(config.P2P)
  200. sw.SetLogger(p2pLogger)
  201. sw.AddReactor("MEMPOOL", mempoolReactor)
  202. sw.AddReactor("BLOCKCHAIN", bcReactor)
  203. sw.AddReactor("CONSENSUS", consensusReactor)
  204. sw.AddReactor("EVIDENCE", evidenceReactor)
  205. // Optionally, start the pex reactor
  206. var addrBook *p2p.AddrBook
  207. var trustMetricStore *trust.TrustMetricStore
  208. if config.P2P.PexReactor {
  209. addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  210. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  211. // Get the trust metric history data
  212. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  213. if err != nil {
  214. return nil, err
  215. }
  216. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  217. trustMetricStore.SetLogger(p2pLogger)
  218. var seeds []string
  219. if config.P2P.Seeds != "" {
  220. seeds = strings.Split(config.P2P.Seeds, ",")
  221. }
  222. pexReactor := p2p.NewPEXReactor(addrBook,
  223. &p2p.PEXReactorConfig{Seeds: seeds})
  224. pexReactor.SetLogger(p2pLogger)
  225. sw.AddReactor("PEX", pexReactor)
  226. }
  227. // Filter peers by addr or pubkey with an ABCI query.
  228. // If the query return code is OK, add peer.
  229. // XXX: Query format subject to change
  230. if config.FilterPeers {
  231. // NOTE: addr is ip:port
  232. sw.SetAddrFilter(func(addr net.Addr) error {
  233. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  234. if err != nil {
  235. return err
  236. }
  237. if resQuery.IsErr() {
  238. return resQuery
  239. }
  240. return nil
  241. })
  242. sw.SetPubKeyFilter(func(pubkey crypto.PubKey) error {
  243. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  244. if err != nil {
  245. return err
  246. }
  247. if resQuery.IsErr() {
  248. return resQuery
  249. }
  250. return nil
  251. })
  252. }
  253. eventBus := types.NewEventBus()
  254. eventBus.SetLogger(logger.With("module", "events"))
  255. // services which will be publishing and/or subscribing for messages (events)
  256. // consensusReactor will set it on consensusState and blockExecutor
  257. consensusReactor.SetEventBus(eventBus)
  258. // Transaction indexing
  259. var txIndexer txindex.TxIndexer
  260. switch config.TxIndex.Indexer {
  261. case "kv":
  262. store, err := dbProvider(&DBContext{"tx_index", config})
  263. if err != nil {
  264. return nil, err
  265. }
  266. if config.TxIndex.IndexTags != "" {
  267. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  268. } else if config.TxIndex.IndexAllTags {
  269. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  270. } else {
  271. txIndexer = kv.NewTxIndex(store)
  272. }
  273. default:
  274. txIndexer = &null.TxIndex{}
  275. }
  276. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  277. // run the profile server
  278. profileHost := config.ProfListenAddress
  279. if profileHost != "" {
  280. go func() {
  281. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  282. }()
  283. }
  284. node := &Node{
  285. config: config,
  286. genesisDoc: genDoc,
  287. privValidator: privValidator,
  288. sw: sw,
  289. addrBook: addrBook,
  290. trustMetricStore: trustMetricStore,
  291. stateDB: stateDB,
  292. blockStore: blockStore,
  293. bcReactor: bcReactor,
  294. mempoolReactor: mempoolReactor,
  295. consensusState: consensusState,
  296. consensusReactor: consensusReactor,
  297. evidencePool: evidencePool,
  298. proxyApp: proxyApp,
  299. txIndexer: txIndexer,
  300. indexerService: indexerService,
  301. eventBus: eventBus,
  302. }
  303. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  304. return node, nil
  305. }
  306. // OnStart starts the Node. It implements cmn.Service.
  307. func (n *Node) OnStart() error {
  308. err := n.eventBus.Start()
  309. if err != nil {
  310. return err
  311. }
  312. // Run the RPC server first
  313. // so we can eg. receive txs for the first block
  314. if n.config.RPC.ListenAddress != "" {
  315. listeners, err := n.startRPC()
  316. if err != nil {
  317. return err
  318. }
  319. n.rpcListeners = listeners
  320. }
  321. // Create & add listener
  322. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  323. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  324. n.sw.AddListener(l)
  325. // Generate node PrivKey
  326. // TODO: pass in like priv_val
  327. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  328. if err != nil {
  329. return err
  330. }
  331. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  332. // Start the switch
  333. n.sw.SetNodeInfo(n.makeNodeInfo(nodeKey.PubKey()))
  334. n.sw.SetNodeKey(nodeKey)
  335. err = n.sw.Start()
  336. if err != nil {
  337. return err
  338. }
  339. // Always connect to persistent peers
  340. if n.config.P2P.PersistentPeers != "" {
  341. err = n.sw.DialPeersAsync(n.addrBook, strings.Split(n.config.P2P.PersistentPeers, ","), true)
  342. if err != nil {
  343. return err
  344. }
  345. }
  346. // start tx indexer
  347. return n.indexerService.Start()
  348. }
  349. // OnStop stops the Node. It implements cmn.Service.
  350. func (n *Node) OnStop() {
  351. n.BaseService.OnStop()
  352. n.Logger.Info("Stopping Node")
  353. // TODO: gracefully disconnect from peers.
  354. n.sw.Stop()
  355. for _, l := range n.rpcListeners {
  356. n.Logger.Info("Closing rpc listener", "listener", l)
  357. if err := l.Close(); err != nil {
  358. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  359. }
  360. }
  361. n.eventBus.Stop()
  362. n.indexerService.Stop()
  363. }
  364. // RunForever waits for an interrupt signal and stops the node.
  365. func (n *Node) RunForever() {
  366. // Sleep forever and then...
  367. cmn.TrapSignal(func() {
  368. n.Stop()
  369. })
  370. }
  371. // AddListener adds a listener to accept inbound peer connections.
  372. // It should be called before starting the Node.
  373. // The first listener is the primary listener (in NodeInfo)
  374. func (n *Node) AddListener(l p2p.Listener) {
  375. n.sw.AddListener(l)
  376. }
  377. // ConfigureRPC sets all variables in rpccore so they will serve
  378. // rpc calls from this node
  379. func (n *Node) ConfigureRPC() {
  380. rpccore.SetStateDB(n.stateDB)
  381. rpccore.SetBlockStore(n.blockStore)
  382. rpccore.SetConsensusState(n.consensusState)
  383. rpccore.SetMempool(n.mempoolReactor.Mempool)
  384. rpccore.SetEvidencePool(n.evidencePool)
  385. rpccore.SetSwitch(n.sw)
  386. rpccore.SetPubKey(n.privValidator.GetPubKey())
  387. rpccore.SetGenesisDoc(n.genesisDoc)
  388. rpccore.SetAddrBook(n.addrBook)
  389. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  390. rpccore.SetTxIndexer(n.txIndexer)
  391. rpccore.SetConsensusReactor(n.consensusReactor)
  392. rpccore.SetEventBus(n.eventBus)
  393. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  394. }
  395. func (n *Node) startRPC() ([]net.Listener, error) {
  396. n.ConfigureRPC()
  397. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  398. if n.config.RPC.Unsafe {
  399. rpccore.AddUnsafeRoutes()
  400. }
  401. // we may expose the rpc over both a unix and tcp socket
  402. listeners := make([]net.Listener, len(listenAddrs))
  403. for i, listenAddr := range listenAddrs {
  404. mux := http.NewServeMux()
  405. rpcLogger := n.Logger.With("module", "rpc-server")
  406. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  407. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  408. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  409. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  410. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  411. if err != nil {
  412. return nil, err
  413. }
  414. listeners[i] = listener
  415. }
  416. // we expose a simplified api over grpc for convenience to app devs
  417. grpcListenAddr := n.config.RPC.GRPCListenAddress
  418. if grpcListenAddr != "" {
  419. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  420. if err != nil {
  421. return nil, err
  422. }
  423. listeners = append(listeners, listener)
  424. }
  425. return listeners, nil
  426. }
  427. // Switch returns the Node's Switch.
  428. func (n *Node) Switch() *p2p.Switch {
  429. return n.sw
  430. }
  431. // BlockStore returns the Node's BlockStore.
  432. func (n *Node) BlockStore() *bc.BlockStore {
  433. return n.blockStore
  434. }
  435. // ConsensusState returns the Node's ConsensusState.
  436. func (n *Node) ConsensusState() *consensus.ConsensusState {
  437. return n.consensusState
  438. }
  439. // ConsensusReactor returns the Node's ConsensusReactor.
  440. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  441. return n.consensusReactor
  442. }
  443. // MempoolReactor returns the Node's MempoolReactor.
  444. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  445. return n.mempoolReactor
  446. }
  447. // EvidencePool returns the Node's EvidencePool.
  448. func (n *Node) EvidencePool() *evidence.EvidencePool {
  449. return n.evidencePool
  450. }
  451. // EventBus returns the Node's EventBus.
  452. func (n *Node) EventBus() *types.EventBus {
  453. return n.eventBus
  454. }
  455. // PrivValidator returns the Node's PrivValidator.
  456. // XXX: for convenience only!
  457. func (n *Node) PrivValidator() types.PrivValidator {
  458. return n.privValidator
  459. }
  460. // GenesisDoc returns the Node's GenesisDoc.
  461. func (n *Node) GenesisDoc() *types.GenesisDoc {
  462. return n.genesisDoc
  463. }
  464. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  465. func (n *Node) ProxyApp() proxy.AppConns {
  466. return n.proxyApp
  467. }
  468. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) p2p.NodeInfo {
  469. txIndexerStatus := "on"
  470. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  471. txIndexerStatus = "off"
  472. }
  473. nodeInfo := p2p.NodeInfo{
  474. PubKey: pubKey,
  475. Network: n.genesisDoc.ChainID,
  476. Version: version.Version,
  477. Moniker: n.config.Moniker,
  478. Other: []string{
  479. cmn.Fmt("wire_version=%v", wire.Version),
  480. cmn.Fmt("p2p_version=%v", p2p.Version),
  481. cmn.Fmt("consensus_version=%v", consensus.Version),
  482. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  483. cmn.Fmt("tx_index=%v", txIndexerStatus),
  484. },
  485. }
  486. rpcListenAddr := n.config.RPC.ListenAddress
  487. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  488. if !n.sw.IsListening() {
  489. return nodeInfo
  490. }
  491. p2pListener := n.sw.Listeners()[0]
  492. p2pHost := p2pListener.ExternalAddress().IP.String()
  493. p2pPort := p2pListener.ExternalAddress().Port
  494. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  495. return nodeInfo
  496. }
  497. //------------------------------------------------------------------------------
  498. // NodeInfo returns the Node's Info from the Switch.
  499. func (n *Node) NodeInfo() p2p.NodeInfo {
  500. return n.sw.NodeInfo()
  501. }
  502. //------------------------------------------------------------------------------
  503. var (
  504. genesisDocKey = []byte("genesisDoc")
  505. )
  506. // panics if failed to unmarshal bytes
  507. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  508. bytes := db.Get(genesisDocKey)
  509. if len(bytes) == 0 {
  510. return nil, errors.New("Genesis doc not found")
  511. } else {
  512. var genDoc *types.GenesisDoc
  513. err := json.Unmarshal(bytes, &genDoc)
  514. if err != nil {
  515. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  516. }
  517. return genDoc, nil
  518. }
  519. }
  520. // panics if failed to marshal the given genesis document
  521. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  522. bytes, err := json.Marshal(genDoc)
  523. if err != nil {
  524. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  525. }
  526. db.SetSync(genesisDocKey, bytes)
  527. }