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.

587 lines
18 KiB

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