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.

654 lines
20 KiB

10 years ago
7 years ago
10 years ago
7 years ago
10 years ago
7 years ago
10 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
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
10 years ago
8 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
8 years ago
10 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
10 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
8 years ago
10 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
9 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "strings"
  10. abci "github.com/tendermint/abci/types"
  11. crypto "github.com/tendermint/go-crypto"
  12. wire "github.com/tendermint/go-wire"
  13. cmn "github.com/tendermint/tmlibs/common"
  14. dbm "github.com/tendermint/tmlibs/db"
  15. "github.com/tendermint/tmlibs/log"
  16. bc "github.com/tendermint/tendermint/blockchain"
  17. cfg "github.com/tendermint/tendermint/config"
  18. 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. /* TODO
  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. //------------------------------------------------------------------------------
  88. // Node is the highest level interface to a full Tendermint node.
  89. // It includes all configuration information and running services.
  90. type Node struct {
  91. cmn.BaseService
  92. // config
  93. config *cfg.Config
  94. genesisDoc *types.GenesisDoc // initial validator set
  95. privValidator types.PrivValidator // local node's validator key
  96. // network
  97. sw *p2p.Switch // p2p connections
  98. addrBook pex.AddrBook // known peers
  99. trustMetricStore *trust.TrustMetricStore // trust metrics for all peers
  100. // services
  101. eventBus *types.EventBus // pub/sub for services
  102. stateDB dbm.DB
  103. blockStore *bc.BlockStore // store the blockchain to disk
  104. bcReactor *bc.BlockchainReactor // for fast-syncing
  105. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  106. consensusState *cs.ConsensusState // latest consensus state
  107. consensusReactor *cs.ConsensusReactor // for participating in the consensus
  108. evidencePool *evidence.EvidencePool // tracking evidence
  109. proxyApp proxy.AppConns // connection to the application
  110. rpcListeners []net.Listener // rpc servers
  111. txIndexer txindex.TxIndexer
  112. indexerService *txindex.IndexerService
  113. }
  114. // NewNode returns a new, ready to go, Tendermint Node.
  115. func NewNode(config *cfg.Config,
  116. privValidator types.PrivValidator,
  117. clientCreator proxy.ClientCreator,
  118. genesisDocProvider GenesisDocProvider,
  119. dbProvider DBProvider,
  120. logger log.Logger) (*Node, error) {
  121. // Get BlockStore
  122. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  123. if err != nil {
  124. return nil, err
  125. }
  126. blockStore := bc.NewBlockStore(blockStoreDB)
  127. // Get State
  128. stateDB, err := dbProvider(&DBContext{"state", config})
  129. if err != nil {
  130. return nil, err
  131. }
  132. // Get genesis doc
  133. // TODO: move to state package?
  134. genDoc, err := loadGenesisDoc(stateDB)
  135. if err != nil {
  136. genDoc, err = genesisDocProvider()
  137. if err != nil {
  138. return nil, err
  139. }
  140. // save genesis doc to prevent a certain class of user errors (e.g. when it
  141. // was changed, accidentally or not). Also good for audit trail.
  142. saveGenesisDoc(stateDB, genDoc)
  143. }
  144. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  145. if err != nil {
  146. return nil, err
  147. }
  148. // Create the proxyApp, which manages connections (consensus, mempool, query)
  149. // and sync tendermint and the app by performing a handshake
  150. // and replaying any necessary blocks
  151. consensusLogger := logger.With("module", "consensus")
  152. handshaker := cs.NewHandshaker(stateDB, state, blockStore)
  153. handshaker.SetLogger(consensusLogger)
  154. proxyApp := proxy.NewAppConns(clientCreator, handshaker)
  155. proxyApp.SetLogger(logger.With("module", "proxy"))
  156. if err := proxyApp.Start(); err != nil {
  157. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  158. }
  159. // reload the state (it may have been updated by the handshake)
  160. state = sm.LoadState(stateDB)
  161. /* TODO
  162. // Generate node PrivKey
  163. privKey := crypto.GenPrivKeyEd25519()
  164. if config.PrivValidatorAddr != "" {
  165. pvsc := priv_val.NewPrivValidatorSocketClient(
  166. logger.With("module", "priv_val"),
  167. config.PrivValidatorAddr,
  168. &privKey,
  169. )
  170. pvsc.Start()
  171. privValidator = pvsc
  172. }
  173. */
  174. // Decide whether to fast-sync or not
  175. // We don't fast-sync when the only validator is us.
  176. fastSync := config.FastSync
  177. if state.Validators.Size() == 1 {
  178. addr, _ := state.Validators.GetByIndex(0)
  179. if bytes.Equal(privValidator.GetAddress(), addr) {
  180. fastSync = false
  181. }
  182. }
  183. // Log whether this node is a validator or an observer
  184. if state.Validators.HasAddress(privValidator.GetAddress()) {
  185. consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  186. } else {
  187. consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  188. }
  189. // Make MempoolReactor
  190. mempoolLogger := logger.With("module", "mempool")
  191. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight)
  192. mempool.InitWAL() // no need to have the mempool wal during tests
  193. mempool.SetLogger(mempoolLogger)
  194. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  195. mempoolReactor.SetLogger(mempoolLogger)
  196. if config.Consensus.WaitForTxs() {
  197. mempool.EnableTxsAvailable()
  198. }
  199. // Make Evidence Reactor
  200. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  201. if err != nil {
  202. return nil, err
  203. }
  204. evidenceLogger := logger.With("module", "evidence")
  205. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  206. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  207. evidencePool.SetLogger(evidenceLogger)
  208. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  209. evidenceReactor.SetLogger(evidenceLogger)
  210. blockExecLogger := logger.With("module", "state")
  211. // make block executor for consensus and blockchain reactors to execute blocks
  212. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  213. // Make BlockchainReactor
  214. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  215. bcReactor.SetLogger(logger.With("module", "blockchain"))
  216. // Make ConsensusReactor
  217. consensusState := cs.NewConsensusState(config.Consensus, state.Copy(),
  218. blockExec, blockStore, mempool, evidencePool)
  219. consensusState.SetLogger(consensusLogger)
  220. if privValidator != nil {
  221. consensusState.SetPrivValidator(privValidator)
  222. }
  223. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync)
  224. consensusReactor.SetLogger(consensusLogger)
  225. p2pLogger := logger.With("module", "p2p")
  226. sw := p2p.NewSwitch(config.P2P)
  227. sw.SetLogger(p2pLogger)
  228. sw.AddReactor("MEMPOOL", mempoolReactor)
  229. sw.AddReactor("BLOCKCHAIN", bcReactor)
  230. sw.AddReactor("CONSENSUS", consensusReactor)
  231. sw.AddReactor("EVIDENCE", evidenceReactor)
  232. // Optionally, start the pex reactor
  233. var addrBook pex.AddrBook
  234. var trustMetricStore *trust.TrustMetricStore
  235. if config.P2P.PexReactor {
  236. addrBook = pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  237. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  238. // Get the trust metric history data
  239. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  240. if err != nil {
  241. return nil, err
  242. }
  243. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  244. trustMetricStore.SetLogger(p2pLogger)
  245. var seeds []string
  246. if config.P2P.Seeds != "" {
  247. seeds = strings.Split(config.P2P.Seeds, ",")
  248. }
  249. pexReactor := pex.NewPEXReactor(addrBook,
  250. &pex.PEXReactorConfig{Seeds: seeds, SeedMode: config.P2P.SeedMode})
  251. pexReactor.SetLogger(p2pLogger)
  252. sw.AddReactor("PEX", pexReactor)
  253. }
  254. // Filter peers by addr or pubkey with an ABCI query.
  255. // If the query return code is OK, add peer.
  256. // XXX: Query format subject to change
  257. if config.FilterPeers {
  258. // NOTE: addr is ip:port
  259. sw.SetAddrFilter(func(addr net.Addr) error {
  260. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  261. if err != nil {
  262. return err
  263. }
  264. if resQuery.IsErr() {
  265. return fmt.Errorf("Error querying abci app: %v", resQuery)
  266. }
  267. return nil
  268. })
  269. sw.SetPubKeyFilter(func(pubkey crypto.PubKey) error {
  270. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  271. if err != nil {
  272. return err
  273. }
  274. if resQuery.IsErr() {
  275. return fmt.Errorf("Error querying abci app: %v", resQuery)
  276. }
  277. return nil
  278. })
  279. }
  280. eventBus := types.NewEventBus()
  281. eventBus.SetLogger(logger.With("module", "events"))
  282. // services which will be publishing and/or subscribing for messages (events)
  283. // consensusReactor will set it on consensusState and blockExecutor
  284. consensusReactor.SetEventBus(eventBus)
  285. // Transaction indexing
  286. var txIndexer txindex.TxIndexer
  287. switch config.TxIndex.Indexer {
  288. case "kv":
  289. store, err := dbProvider(&DBContext{"tx_index", config})
  290. if err != nil {
  291. return nil, err
  292. }
  293. if config.TxIndex.IndexTags != "" {
  294. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  295. } else if config.TxIndex.IndexAllTags {
  296. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  297. } else {
  298. txIndexer = kv.NewTxIndex(store)
  299. }
  300. default:
  301. txIndexer = &null.TxIndex{}
  302. }
  303. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  304. // run the profile server
  305. profileHost := config.ProfListenAddress
  306. if profileHost != "" {
  307. go func() {
  308. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  309. }()
  310. }
  311. node := &Node{
  312. config: config,
  313. genesisDoc: genDoc,
  314. privValidator: privValidator,
  315. sw: sw,
  316. addrBook: addrBook,
  317. trustMetricStore: trustMetricStore,
  318. stateDB: stateDB,
  319. blockStore: blockStore,
  320. bcReactor: bcReactor,
  321. mempoolReactor: mempoolReactor,
  322. consensusState: consensusState,
  323. consensusReactor: consensusReactor,
  324. evidencePool: evidencePool,
  325. proxyApp: proxyApp,
  326. txIndexer: txIndexer,
  327. indexerService: indexerService,
  328. eventBus: eventBus,
  329. }
  330. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  331. return node, nil
  332. }
  333. // OnStart starts the Node. It implements cmn.Service.
  334. func (n *Node) OnStart() error {
  335. err := n.eventBus.Start()
  336. if err != nil {
  337. return err
  338. }
  339. // Run the RPC server first
  340. // so we can eg. receive txs for the first block
  341. if n.config.RPC.ListenAddress != "" {
  342. listeners, err := n.startRPC()
  343. if err != nil {
  344. return err
  345. }
  346. n.rpcListeners = listeners
  347. }
  348. // Create & add listener
  349. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  350. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  351. n.sw.AddListener(l)
  352. // Generate node PrivKey
  353. // TODO: pass in like priv_val
  354. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  355. if err != nil {
  356. return err
  357. }
  358. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  359. // Start the switch
  360. n.sw.SetNodeInfo(n.makeNodeInfo(nodeKey.PubKey()))
  361. n.sw.SetNodeKey(nodeKey)
  362. err = n.sw.Start()
  363. if err != nil {
  364. return err
  365. }
  366. // Always connect to persistent peers
  367. if n.config.P2P.PersistentPeers != "" {
  368. err = n.sw.DialPeersAsync(n.addrBook, strings.Split(n.config.P2P.PersistentPeers, ","), true)
  369. if err != nil {
  370. return err
  371. }
  372. }
  373. // start tx indexer
  374. return n.indexerService.Start()
  375. }
  376. // OnStop stops the Node. It implements cmn.Service.
  377. func (n *Node) OnStop() {
  378. n.BaseService.OnStop()
  379. n.Logger.Info("Stopping Node")
  380. // TODO: gracefully disconnect from peers.
  381. n.sw.Stop()
  382. for _, l := range n.rpcListeners {
  383. n.Logger.Info("Closing rpc listener", "listener", l)
  384. if err := l.Close(); err != nil {
  385. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  386. }
  387. }
  388. n.eventBus.Stop()
  389. n.indexerService.Stop()
  390. }
  391. // RunForever waits for an interrupt signal and stops the node.
  392. func (n *Node) RunForever() {
  393. // Sleep forever and then...
  394. cmn.TrapSignal(func() {
  395. n.Stop()
  396. })
  397. }
  398. // AddListener adds a listener to accept inbound peer connections.
  399. // It should be called before starting the Node.
  400. // The first listener is the primary listener (in NodeInfo)
  401. func (n *Node) AddListener(l p2p.Listener) {
  402. n.sw.AddListener(l)
  403. }
  404. // ConfigureRPC sets all variables in rpccore so they will serve
  405. // rpc calls from this node
  406. func (n *Node) ConfigureRPC() {
  407. rpccore.SetStateDB(n.stateDB)
  408. rpccore.SetBlockStore(n.blockStore)
  409. rpccore.SetConsensusState(n.consensusState)
  410. rpccore.SetMempool(n.mempoolReactor.Mempool)
  411. rpccore.SetEvidencePool(n.evidencePool)
  412. rpccore.SetSwitch(n.sw)
  413. rpccore.SetPubKey(n.privValidator.GetPubKey())
  414. rpccore.SetGenesisDoc(n.genesisDoc)
  415. rpccore.SetAddrBook(n.addrBook)
  416. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  417. rpccore.SetTxIndexer(n.txIndexer)
  418. rpccore.SetConsensusReactor(n.consensusReactor)
  419. rpccore.SetEventBus(n.eventBus)
  420. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  421. }
  422. func (n *Node) startRPC() ([]net.Listener, error) {
  423. n.ConfigureRPC()
  424. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  425. if n.config.RPC.Unsafe {
  426. rpccore.AddUnsafeRoutes()
  427. }
  428. // we may expose the rpc over both a unix and tcp socket
  429. listeners := make([]net.Listener, len(listenAddrs))
  430. for i, listenAddr := range listenAddrs {
  431. mux := http.NewServeMux()
  432. rpcLogger := n.Logger.With("module", "rpc-server")
  433. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  434. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  435. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  436. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  437. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  438. if err != nil {
  439. return nil, err
  440. }
  441. listeners[i] = listener
  442. }
  443. // we expose a simplified api over grpc for convenience to app devs
  444. grpcListenAddr := n.config.RPC.GRPCListenAddress
  445. if grpcListenAddr != "" {
  446. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  447. if err != nil {
  448. return nil, err
  449. }
  450. listeners = append(listeners, listener)
  451. }
  452. return listeners, nil
  453. }
  454. // Switch returns the Node's Switch.
  455. func (n *Node) Switch() *p2p.Switch {
  456. return n.sw
  457. }
  458. // BlockStore returns the Node's BlockStore.
  459. func (n *Node) BlockStore() *bc.BlockStore {
  460. return n.blockStore
  461. }
  462. // ConsensusState returns the Node's ConsensusState.
  463. func (n *Node) ConsensusState() *cs.ConsensusState {
  464. return n.consensusState
  465. }
  466. // ConsensusReactor returns the Node's ConsensusReactor.
  467. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  468. return n.consensusReactor
  469. }
  470. // MempoolReactor returns the Node's MempoolReactor.
  471. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  472. return n.mempoolReactor
  473. }
  474. // EvidencePool returns the Node's EvidencePool.
  475. func (n *Node) EvidencePool() *evidence.EvidencePool {
  476. return n.evidencePool
  477. }
  478. // EventBus returns the Node's EventBus.
  479. func (n *Node) EventBus() *types.EventBus {
  480. return n.eventBus
  481. }
  482. // PrivValidator returns the Node's PrivValidator.
  483. // XXX: for convenience only!
  484. func (n *Node) PrivValidator() types.PrivValidator {
  485. return n.privValidator
  486. }
  487. // GenesisDoc returns the Node's GenesisDoc.
  488. func (n *Node) GenesisDoc() *types.GenesisDoc {
  489. return n.genesisDoc
  490. }
  491. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  492. func (n *Node) ProxyApp() proxy.AppConns {
  493. return n.proxyApp
  494. }
  495. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) p2p.NodeInfo {
  496. txIndexerStatus := "on"
  497. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  498. txIndexerStatus = "off"
  499. }
  500. nodeInfo := p2p.NodeInfo{
  501. PubKey: pubKey,
  502. Network: n.genesisDoc.ChainID,
  503. Version: version.Version,
  504. Channels: []byte{
  505. bc.BlockchainChannel,
  506. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  507. mempl.MempoolChannel,
  508. evidence.EvidenceChannel,
  509. },
  510. Moniker: n.config.Moniker,
  511. Other: []string{
  512. cmn.Fmt("wire_version=%v", wire.Version),
  513. cmn.Fmt("p2p_version=%v", p2p.Version),
  514. cmn.Fmt("consensus_version=%v", cs.Version),
  515. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  516. cmn.Fmt("tx_index=%v", txIndexerStatus),
  517. },
  518. }
  519. if n.config.P2P.PexReactor {
  520. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  521. }
  522. rpcListenAddr := n.config.RPC.ListenAddress
  523. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  524. if !n.sw.IsListening() {
  525. return nodeInfo
  526. }
  527. p2pListener := n.sw.Listeners()[0]
  528. p2pHost := p2pListener.ExternalAddress().IP.String()
  529. p2pPort := p2pListener.ExternalAddress().Port
  530. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  531. return nodeInfo
  532. }
  533. //------------------------------------------------------------------------------
  534. // NodeInfo returns the Node's Info from the Switch.
  535. func (n *Node) NodeInfo() p2p.NodeInfo {
  536. return n.sw.NodeInfo()
  537. }
  538. //------------------------------------------------------------------------------
  539. var (
  540. genesisDocKey = []byte("genesisDoc")
  541. )
  542. // panics if failed to unmarshal bytes
  543. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  544. bytes := db.Get(genesisDocKey)
  545. if len(bytes) == 0 {
  546. return nil, errors.New("Genesis doc not found")
  547. } else {
  548. var genDoc *types.GenesisDoc
  549. err := json.Unmarshal(bytes, &genDoc)
  550. if err != nil {
  551. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  552. }
  553. return genDoc, nil
  554. }
  555. }
  556. // panics if failed to marshal the given genesis document
  557. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  558. bytes, err := json.Marshal(genDoc)
  559. if err != nil {
  560. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  561. }
  562. db.SetSync(genesisDocKey, bytes)
  563. }