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.

599 lines
18 KiB

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