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.

592 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
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. }
  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.Code.IsOK() {
  221. return nil
  222. }
  223. return errors.New(resQuery.Code.String())
  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.Code.IsOK() {
  231. return nil
  232. }
  233. return errors.New(resQuery.Code.String())
  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. txIndexer = kv.NewTxIndex(store)
  250. default:
  251. txIndexer = &null.TxIndex{}
  252. }
  253. // subscribe for all transactions and index them by tags
  254. ch := make(chan interface{})
  255. eventBus.Subscribe(context.Background(), "tx_index", types.EventQueryTx, ch)
  256. go func() {
  257. for event := range ch {
  258. // XXX: may be not perfomant to write one event at a time
  259. txResult := event.(types.TMEventData).Unwrap().(types.EventDataTx).TxResult
  260. txIndexer.Index(&txResult, strings.Split(config.TxIndex.IndexTags, ","))
  261. }
  262. }()
  263. // run the profile server
  264. profileHost := config.ProfListenAddress
  265. if profileHost != "" {
  266. go func() {
  267. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  268. }()
  269. }
  270. node := &Node{
  271. config: config,
  272. genesisDoc: genDoc,
  273. privValidator: privValidator,
  274. privKey: privKey,
  275. sw: sw,
  276. addrBook: addrBook,
  277. trustMetricStore: trustMetricStore,
  278. blockStore: blockStore,
  279. bcReactor: bcReactor,
  280. mempoolReactor: mempoolReactor,
  281. consensusState: consensusState,
  282. consensusReactor: consensusReactor,
  283. proxyApp: proxyApp,
  284. txIndexer: txIndexer,
  285. eventBus: eventBus,
  286. }
  287. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  288. return node, nil
  289. }
  290. // OnStart starts the Node. It implements cmn.Service.
  291. func (n *Node) OnStart() error {
  292. err := n.eventBus.Start()
  293. if err != nil {
  294. return err
  295. }
  296. // Run the RPC server first
  297. // so we can eg. receive txs for the first block
  298. if n.config.RPC.ListenAddress != "" {
  299. listeners, err := n.startRPC()
  300. if err != nil {
  301. return err
  302. }
  303. n.rpcListeners = listeners
  304. }
  305. // Create & add listener
  306. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  307. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  308. n.sw.AddListener(l)
  309. // Start the switch
  310. n.sw.SetNodeInfo(n.makeNodeInfo())
  311. n.sw.SetNodePrivKey(n.privKey)
  312. err = n.sw.Start()
  313. if err != nil {
  314. return err
  315. }
  316. // If seeds exist, add them to the address book and dial out
  317. if n.config.P2P.Seeds != "" {
  318. // dial out
  319. seeds := strings.Split(n.config.P2P.Seeds, ",")
  320. if err := n.DialSeeds(seeds); err != nil {
  321. return err
  322. }
  323. }
  324. return nil
  325. }
  326. // OnStop stops the Node. It implements cmn.Service.
  327. func (n *Node) OnStop() {
  328. n.BaseService.OnStop()
  329. n.Logger.Info("Stopping Node")
  330. // TODO: gracefully disconnect from peers.
  331. n.sw.Stop()
  332. for _, l := range n.rpcListeners {
  333. n.Logger.Info("Closing rpc listener", "listener", l)
  334. if err := l.Close(); err != nil {
  335. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  336. }
  337. }
  338. n.eventBus.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. onDisconnect := rpcserver.OnDisconnect(func(remoteAddr string) {
  381. err := n.eventBus.UnsubscribeAll(context.Background(), remoteAddr)
  382. if err != nil {
  383. rpcLogger.Error("Error unsubsribing from all on disconnect", "err", err)
  384. }
  385. })
  386. wm := rpcserver.NewWebsocketManager(rpccore.Routes, onDisconnect)
  387. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  388. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  389. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  390. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  391. if err != nil {
  392. return nil, err
  393. }
  394. listeners[i] = listener
  395. }
  396. // we expose a simplified api over grpc for convenience to app devs
  397. grpcListenAddr := n.config.RPC.GRPCListenAddress
  398. if grpcListenAddr != "" {
  399. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  400. if err != nil {
  401. return nil, err
  402. }
  403. listeners = append(listeners, listener)
  404. }
  405. return listeners, nil
  406. }
  407. // Switch returns the Node's Switch.
  408. func (n *Node) Switch() *p2p.Switch {
  409. return n.sw
  410. }
  411. // BlockStore returns the Node's BlockStore.
  412. func (n *Node) BlockStore() *bc.BlockStore {
  413. return n.blockStore
  414. }
  415. // ConsensusState returns the Node's ConsensusState.
  416. func (n *Node) ConsensusState() *consensus.ConsensusState {
  417. return n.consensusState
  418. }
  419. // ConsensusReactor returns the Node's ConsensusReactor.
  420. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  421. return n.consensusReactor
  422. }
  423. // MempoolReactor returns the Node's MempoolReactor.
  424. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  425. return n.mempoolReactor
  426. }
  427. // EventBus returns the Node's EventBus.
  428. func (n *Node) EventBus() *types.EventBus {
  429. return n.eventBus
  430. }
  431. // PrivValidator returns the Node's PrivValidator.
  432. // XXX: for convenience only!
  433. func (n *Node) PrivValidator() types.PrivValidator {
  434. return n.privValidator
  435. }
  436. // GenesisDoc returns the Node's GenesisDoc.
  437. func (n *Node) GenesisDoc() *types.GenesisDoc {
  438. return n.genesisDoc
  439. }
  440. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  441. func (n *Node) ProxyApp() proxy.AppConns {
  442. return n.proxyApp
  443. }
  444. func (n *Node) makeNodeInfo() *p2p.NodeInfo {
  445. txIndexerStatus := "on"
  446. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  447. txIndexerStatus = "off"
  448. }
  449. nodeInfo := &p2p.NodeInfo{
  450. PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  451. Moniker: n.config.Moniker,
  452. Network: n.genesisDoc.ChainID,
  453. Version: version.Version,
  454. Other: []string{
  455. cmn.Fmt("wire_version=%v", wire.Version),
  456. cmn.Fmt("p2p_version=%v", p2p.Version),
  457. cmn.Fmt("consensus_version=%v", consensus.Version),
  458. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  459. cmn.Fmt("tx_index=%v", txIndexerStatus),
  460. },
  461. }
  462. rpcListenAddr := n.config.RPC.ListenAddress
  463. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  464. if !n.sw.IsListening() {
  465. return nodeInfo
  466. }
  467. p2pListener := n.sw.Listeners()[0]
  468. p2pHost := p2pListener.ExternalAddress().IP.String()
  469. p2pPort := p2pListener.ExternalAddress().Port
  470. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  471. return nodeInfo
  472. }
  473. //------------------------------------------------------------------------------
  474. // NodeInfo returns the Node's Info from the Switch.
  475. func (n *Node) NodeInfo() *p2p.NodeInfo {
  476. return n.sw.NodeInfo()
  477. }
  478. // DialSeeds dials the given seeds on the Switch.
  479. func (n *Node) DialSeeds(seeds []string) error {
  480. return n.sw.DialSeeds(n.addrBook, seeds)
  481. }
  482. //------------------------------------------------------------------------------
  483. var (
  484. genesisDocKey = []byte("genesisDoc")
  485. )
  486. // panics if failed to unmarshal bytes
  487. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  488. bytes := db.Get(genesisDocKey)
  489. if len(bytes) == 0 {
  490. return nil, errors.New("Genesis doc not found")
  491. } else {
  492. var genDoc *types.GenesisDoc
  493. err := json.Unmarshal(bytes, &genDoc)
  494. if err != nil {
  495. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  496. }
  497. return genDoc, nil
  498. }
  499. }
  500. // panics if failed to marshal the given genesis document
  501. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  502. bytes, err := json.Marshal(genDoc)
  503. if err != nil {
  504. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  505. }
  506. db.SetSync(genesisDocKey, bytes)
  507. }