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.

625 lines
19 KiB

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