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.

638 lines
20 KiB

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