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.

611 lines
19 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. privKey crypto.PrivKeyEd25519 // local node's p2p key
  84. sw *p2p.Switch // p2p connections
  85. addrBook *p2p.AddrBook // known peers
  86. trustMetricStore *trust.TrustMetricStore // trust metrics for all peers
  87. // services
  88. eventBus *types.EventBus // pub/sub for services
  89. stateDB dbm.DB
  90. blockStore *bc.BlockStore // store the blockchain to disk
  91. bcReactor *bc.BlockchainReactor // for fast-syncing
  92. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  93. consensusState *consensus.ConsensusState // latest consensus state
  94. consensusReactor *consensus.ConsensusReactor // for participating in the consensus
  95. evidencePool *evidence.EvidencePool // tracking evidence
  96. proxyApp proxy.AppConns // connection to the application
  97. rpcListeners []net.Listener // rpc servers
  98. txIndexer txindex.TxIndexer
  99. indexerService *txindex.IndexerService
  100. }
  101. // NewNode returns a new, ready to go, Tendermint Node.
  102. func NewNode(config *cfg.Config,
  103. privValidator types.PrivValidator,
  104. clientCreator proxy.ClientCreator,
  105. genesisDocProvider GenesisDocProvider,
  106. dbProvider DBProvider,
  107. logger log.Logger) (*Node, error) {
  108. // Get BlockStore
  109. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  110. if err != nil {
  111. return nil, err
  112. }
  113. blockStore := bc.NewBlockStore(blockStoreDB)
  114. // Get State
  115. stateDB, err := dbProvider(&DBContext{"state", config})
  116. if err != nil {
  117. return nil, err
  118. }
  119. // Get genesis doc
  120. // TODO: move to state package?
  121. genDoc, err := loadGenesisDoc(stateDB)
  122. if err != nil {
  123. genDoc, err = genesisDocProvider()
  124. if err != nil {
  125. return nil, err
  126. }
  127. // save genesis doc to prevent a certain class of user errors (e.g. when it
  128. // was changed, accidentally or not). Also good for audit trail.
  129. saveGenesisDoc(stateDB, genDoc)
  130. }
  131. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  132. if err != nil {
  133. return nil, err
  134. }
  135. // Create the proxyApp, which manages connections (consensus, mempool, query)
  136. // and sync tendermint and the app by performing a handshake
  137. // and replaying any necessary blocks
  138. consensusLogger := logger.With("module", "consensus")
  139. handshaker := consensus.NewHandshaker(stateDB, state, blockStore)
  140. handshaker.SetLogger(consensusLogger)
  141. proxyApp := proxy.NewAppConns(clientCreator, handshaker)
  142. proxyApp.SetLogger(logger.With("module", "proxy"))
  143. if err := proxyApp.Start(); err != nil {
  144. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  145. }
  146. // reload the state (it may have been updated by the handshake)
  147. state = sm.LoadState(stateDB)
  148. // Generate node PrivKey
  149. privKey := crypto.GenPrivKeyEd25519()
  150. // Decide whether to fast-sync or not
  151. // We don't fast-sync when the only validator is us.
  152. fastSync := config.FastSync
  153. if state.Validators.Size() == 1 {
  154. addr, _ := state.Validators.GetByIndex(0)
  155. if bytes.Equal(privValidator.GetAddress(), addr) {
  156. fastSync = false
  157. }
  158. }
  159. // Log whether this node is a validator or an observer
  160. if state.Validators.HasAddress(privValidator.GetAddress()) {
  161. consensusLogger.Info("This node is a validator")
  162. } else {
  163. consensusLogger.Info("This node is not a validator")
  164. }
  165. // Make MempoolReactor
  166. mempoolLogger := logger.With("module", "mempool")
  167. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight)
  168. mempool.SetLogger(mempoolLogger)
  169. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  170. mempoolReactor.SetLogger(mempoolLogger)
  171. if config.Consensus.WaitForTxs() {
  172. mempool.EnableTxsAvailable()
  173. }
  174. // Make Evidence Reactor
  175. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  176. if err != nil {
  177. return nil, err
  178. }
  179. evidenceLogger := logger.With("module", "evidence")
  180. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  181. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  182. evidencePool.SetLogger(evidenceLogger)
  183. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  184. evidenceReactor.SetLogger(evidenceLogger)
  185. blockExecLogger := logger.With("module", "state")
  186. // make block executor for consensus and blockchain reactors to execute blocks
  187. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  188. // Make BlockchainReactor
  189. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  190. bcReactor.SetLogger(logger.With("module", "blockchain"))
  191. // Make ConsensusReactor
  192. consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(),
  193. blockExec, blockStore, mempool, evidencePool)
  194. consensusState.SetLogger(consensusLogger)
  195. if privValidator != nil {
  196. consensusState.SetPrivValidator(privValidator)
  197. }
  198. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  199. consensusReactor.SetLogger(consensusLogger)
  200. p2pLogger := logger.With("module", "p2p")
  201. sw := p2p.NewSwitch(config.P2P)
  202. sw.SetLogger(p2pLogger)
  203. sw.AddReactor("MEMPOOL", mempoolReactor)
  204. sw.AddReactor("BLOCKCHAIN", bcReactor)
  205. sw.AddReactor("CONSENSUS", consensusReactor)
  206. sw.AddReactor("EVIDENCE", evidenceReactor)
  207. // Optionally, start the pex reactor
  208. var addrBook *p2p.AddrBook
  209. var trustMetricStore *trust.TrustMetricStore
  210. if config.P2P.PexReactor {
  211. addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  212. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  213. // Get the trust metric history data
  214. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  215. if err != nil {
  216. return nil, err
  217. }
  218. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  219. trustMetricStore.SetLogger(p2pLogger)
  220. pexReactor := p2p.NewPEXReactor(addrBook)
  221. pexReactor.SetLogger(p2pLogger)
  222. sw.AddReactor("PEX", pexReactor)
  223. }
  224. // Filter peers by addr or pubkey with an ABCI query.
  225. // If the query return code is OK, add peer.
  226. // XXX: Query format subject to change
  227. if config.FilterPeers {
  228. // NOTE: addr is ip:port
  229. sw.SetAddrFilter(func(addr net.Addr) error {
  230. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  231. if err != nil {
  232. return err
  233. }
  234. if resQuery.IsErr() {
  235. return resQuery
  236. }
  237. return nil
  238. })
  239. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  240. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  241. if err != nil {
  242. return err
  243. }
  244. if resQuery.IsErr() {
  245. return resQuery
  246. }
  247. return nil
  248. })
  249. }
  250. eventBus := types.NewEventBus()
  251. eventBus.SetLogger(logger.With("module", "events"))
  252. // services which will be publishing and/or subscribing for messages (events)
  253. // consensusReactor will set it on consensusState and blockExecutor
  254. consensusReactor.SetEventBus(eventBus)
  255. // Transaction indexing
  256. var txIndexer txindex.TxIndexer
  257. switch config.TxIndex.Indexer {
  258. case "kv":
  259. store, err := dbProvider(&DBContext{"tx_index", config})
  260. if err != nil {
  261. return nil, err
  262. }
  263. if config.TxIndex.IndexTags != "" {
  264. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  265. } else if config.TxIndex.IndexAllTags {
  266. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  267. } else {
  268. txIndexer = kv.NewTxIndex(store)
  269. }
  270. default:
  271. txIndexer = &null.TxIndex{}
  272. }
  273. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  274. // run the profile server
  275. profileHost := config.ProfListenAddress
  276. if profileHost != "" {
  277. go func() {
  278. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  279. }()
  280. }
  281. node := &Node{
  282. config: config,
  283. genesisDoc: genDoc,
  284. privValidator: privValidator,
  285. privKey: privKey,
  286. sw: sw,
  287. addrBook: addrBook,
  288. trustMetricStore: trustMetricStore,
  289. stateDB: stateDB,
  290. blockStore: blockStore,
  291. bcReactor: bcReactor,
  292. mempoolReactor: mempoolReactor,
  293. consensusState: consensusState,
  294. consensusReactor: consensusReactor,
  295. evidencePool: evidencePool,
  296. proxyApp: proxyApp,
  297. txIndexer: txIndexer,
  298. indexerService: indexerService,
  299. eventBus: eventBus,
  300. }
  301. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  302. return node, nil
  303. }
  304. // OnStart starts the Node. It implements cmn.Service.
  305. func (n *Node) OnStart() error {
  306. err := n.eventBus.Start()
  307. if err != nil {
  308. return err
  309. }
  310. // Run the RPC server first
  311. // so we can eg. receive txs for the first block
  312. if n.config.RPC.ListenAddress != "" {
  313. listeners, err := n.startRPC()
  314. if err != nil {
  315. return err
  316. }
  317. n.rpcListeners = listeners
  318. }
  319. // Create & add listener
  320. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  321. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  322. n.sw.AddListener(l)
  323. // Start the switch
  324. n.sw.SetNodeInfo(n.makeNodeInfo())
  325. n.sw.SetNodePrivKey(n.privKey)
  326. err = n.sw.Start()
  327. if err != nil {
  328. return err
  329. }
  330. // If seeds exist, add them to the address book and dial out
  331. if n.config.P2P.Seeds != "" {
  332. // dial out
  333. seeds := strings.Split(n.config.P2P.Seeds, ",")
  334. if err := n.DialSeeds(seeds); err != nil {
  335. return err
  336. }
  337. }
  338. // start tx indexer
  339. return n.indexerService.Start()
  340. }
  341. // OnStop stops the Node. It implements cmn.Service.
  342. func (n *Node) OnStop() {
  343. n.BaseService.OnStop()
  344. n.Logger.Info("Stopping Node")
  345. // TODO: gracefully disconnect from peers.
  346. n.sw.Stop()
  347. for _, l := range n.rpcListeners {
  348. n.Logger.Info("Closing rpc listener", "listener", l)
  349. if err := l.Close(); err != nil {
  350. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  351. }
  352. }
  353. n.eventBus.Stop()
  354. n.indexerService.Stop()
  355. }
  356. // RunForever waits for an interrupt signal and stops the node.
  357. func (n *Node) RunForever() {
  358. // Sleep forever and then...
  359. cmn.TrapSignal(func() {
  360. n.Stop()
  361. })
  362. }
  363. // AddListener adds a listener to accept inbound peer connections.
  364. // It should be called before starting the Node.
  365. // The first listener is the primary listener (in NodeInfo)
  366. func (n *Node) AddListener(l p2p.Listener) {
  367. n.sw.AddListener(l)
  368. }
  369. // ConfigureRPC sets all variables in rpccore so they will serve
  370. // rpc calls from this node
  371. func (n *Node) ConfigureRPC() {
  372. rpccore.SetStateDB(n.stateDB)
  373. rpccore.SetBlockStore(n.blockStore)
  374. rpccore.SetConsensusState(n.consensusState)
  375. rpccore.SetMempool(n.mempoolReactor.Mempool)
  376. rpccore.SetEvidencePool(n.evidencePool)
  377. rpccore.SetSwitch(n.sw)
  378. rpccore.SetPubKey(n.privValidator.GetPubKey())
  379. rpccore.SetGenesisDoc(n.genesisDoc)
  380. rpccore.SetAddrBook(n.addrBook)
  381. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  382. rpccore.SetTxIndexer(n.txIndexer)
  383. rpccore.SetConsensusReactor(n.consensusReactor)
  384. rpccore.SetEventBus(n.eventBus)
  385. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  386. }
  387. func (n *Node) startRPC() ([]net.Listener, error) {
  388. n.ConfigureRPC()
  389. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  390. if n.config.RPC.Unsafe {
  391. rpccore.AddUnsafeRoutes()
  392. }
  393. // we may expose the rpc over both a unix and tcp socket
  394. listeners := make([]net.Listener, len(listenAddrs))
  395. for i, listenAddr := range listenAddrs {
  396. mux := http.NewServeMux()
  397. rpcLogger := n.Logger.With("module", "rpc-server")
  398. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  399. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  400. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  401. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  402. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  403. if err != nil {
  404. return nil, err
  405. }
  406. listeners[i] = listener
  407. }
  408. // we expose a simplified api over grpc for convenience to app devs
  409. grpcListenAddr := n.config.RPC.GRPCListenAddress
  410. if grpcListenAddr != "" {
  411. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  412. if err != nil {
  413. return nil, err
  414. }
  415. listeners = append(listeners, listener)
  416. }
  417. return listeners, nil
  418. }
  419. // Switch returns the Node's Switch.
  420. func (n *Node) Switch() *p2p.Switch {
  421. return n.sw
  422. }
  423. // BlockStore returns the Node's BlockStore.
  424. func (n *Node) BlockStore() *bc.BlockStore {
  425. return n.blockStore
  426. }
  427. // ConsensusState returns the Node's ConsensusState.
  428. func (n *Node) ConsensusState() *consensus.ConsensusState {
  429. return n.consensusState
  430. }
  431. // ConsensusReactor returns the Node's ConsensusReactor.
  432. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  433. return n.consensusReactor
  434. }
  435. // MempoolReactor returns the Node's MempoolReactor.
  436. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  437. return n.mempoolReactor
  438. }
  439. // EvidencePool returns the Node's EvidencePool.
  440. func (n *Node) EvidencePool() *evidence.EvidencePool {
  441. return n.evidencePool
  442. }
  443. // EventBus returns the Node's EventBus.
  444. func (n *Node) EventBus() *types.EventBus {
  445. return n.eventBus
  446. }
  447. // PrivValidator returns the Node's PrivValidator.
  448. // XXX: for convenience only!
  449. func (n *Node) PrivValidator() types.PrivValidator {
  450. return n.privValidator
  451. }
  452. // GenesisDoc returns the Node's GenesisDoc.
  453. func (n *Node) GenesisDoc() *types.GenesisDoc {
  454. return n.genesisDoc
  455. }
  456. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  457. func (n *Node) ProxyApp() proxy.AppConns {
  458. return n.proxyApp
  459. }
  460. func (n *Node) makeNodeInfo() *p2p.NodeInfo {
  461. txIndexerStatus := "on"
  462. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  463. txIndexerStatus = "off"
  464. }
  465. nodeInfo := &p2p.NodeInfo{
  466. PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  467. Moniker: n.config.Moniker,
  468. Network: n.genesisDoc.ChainID,
  469. Version: version.Version,
  470. Other: []string{
  471. cmn.Fmt("wire_version=%v", wire.Version),
  472. cmn.Fmt("p2p_version=%v", p2p.Version),
  473. cmn.Fmt("consensus_version=%v", consensus.Version),
  474. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  475. cmn.Fmt("tx_index=%v", txIndexerStatus),
  476. },
  477. }
  478. rpcListenAddr := n.config.RPC.ListenAddress
  479. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  480. if !n.sw.IsListening() {
  481. return nodeInfo
  482. }
  483. p2pListener := n.sw.Listeners()[0]
  484. p2pHost := p2pListener.ExternalAddress().IP.String()
  485. p2pPort := p2pListener.ExternalAddress().Port
  486. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  487. return nodeInfo
  488. }
  489. //------------------------------------------------------------------------------
  490. // NodeInfo returns the Node's Info from the Switch.
  491. func (n *Node) NodeInfo() *p2p.NodeInfo {
  492. return n.sw.NodeInfo()
  493. }
  494. // DialSeeds dials the given seeds on the Switch.
  495. func (n *Node) DialSeeds(seeds []string) error {
  496. return n.sw.DialSeeds(n.addrBook, seeds)
  497. }
  498. //------------------------------------------------------------------------------
  499. var (
  500. genesisDocKey = []byte("genesisDoc")
  501. )
  502. // panics if failed to unmarshal bytes
  503. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  504. bytes := db.Get(genesisDocKey)
  505. if len(bytes) == 0 {
  506. return nil, errors.New("Genesis doc not found")
  507. } else {
  508. var genDoc *types.GenesisDoc
  509. err := json.Unmarshal(bytes, &genDoc)
  510. if err != nil {
  511. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  512. }
  513. return genDoc, nil
  514. }
  515. }
  516. // panics if failed to marshal the given genesis document
  517. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  518. bytes, err := json.Marshal(genDoc)
  519. if err != nil {
  520. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  521. }
  522. db.SetSync(genesisDocKey, bytes)
  523. }