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.

579 lines
17 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
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
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
11 years ago
11 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
10 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
9 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "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. // Transaction indexing
  151. var txIndexer txindex.TxIndexer
  152. switch config.TxIndex {
  153. case "kv":
  154. store, err := dbProvider(&DBContext{"tx_index", config})
  155. if err != nil {
  156. return nil, err
  157. }
  158. txIndexer = kv.NewTxIndex(store)
  159. default:
  160. txIndexer = &null.TxIndex{}
  161. }
  162. state.TxIndexer = txIndexer
  163. // Generate node PrivKey
  164. privKey := crypto.GenPrivKeyEd25519()
  165. // Decide whether to fast-sync or not
  166. // We don't fast-sync when the only validator is us.
  167. fastSync := config.FastSync
  168. if state.Validators.Size() == 1 {
  169. addr, _ := state.Validators.GetByIndex(0)
  170. if bytes.Equal(privValidator.GetAddress(), addr) {
  171. fastSync = false
  172. }
  173. }
  174. // Log whether this node is a validator or an observer
  175. if state.Validators.HasAddress(privValidator.GetAddress()) {
  176. consensusLogger.Info("This node is a validator")
  177. } else {
  178. consensusLogger.Info("This node is not a validator")
  179. }
  180. // Make BlockchainReactor
  181. bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  182. bcReactor.SetLogger(logger.With("module", "blockchain"))
  183. // Make MempoolReactor
  184. mempoolLogger := logger.With("module", "mempool")
  185. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight)
  186. mempool.SetLogger(mempoolLogger)
  187. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  188. mempoolReactor.SetLogger(mempoolLogger)
  189. if config.Consensus.WaitForTxs() {
  190. mempool.EnableTxsAvailable()
  191. }
  192. // Make ConsensusReactor
  193. consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  194. consensusState.SetLogger(consensusLogger)
  195. if privValidator != nil {
  196. consensusState.SetPrivValidator(privValidator)
  197. }
  198. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  199. consensusReactor.SetLogger(consensusLogger)
  200. p2pLogger := logger.With("module", "p2p")
  201. sw := p2p.NewSwitch(config.P2P)
  202. sw.SetLogger(p2pLogger)
  203. sw.AddReactor("MEMPOOL", mempoolReactor)
  204. sw.AddReactor("BLOCKCHAIN", bcReactor)
  205. sw.AddReactor("CONSENSUS", consensusReactor)
  206. // Optionally, start the pex reactor
  207. var addrBook *p2p.AddrBook
  208. var trustMetricStore *trust.TrustMetricStore
  209. if config.P2P.PexReactor {
  210. addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  211. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  212. // Get the trust metric history data
  213. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  214. if err != nil {
  215. return nil, err
  216. }
  217. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  218. trustMetricStore.SetLogger(p2pLogger)
  219. pexReactor := p2p.NewPEXReactor(addrBook)
  220. pexReactor.SetLogger(p2pLogger)
  221. sw.AddReactor("PEX", pexReactor)
  222. }
  223. // Filter peers by addr or pubkey with an ABCI query.
  224. // If the query return code is OK, add peer.
  225. // XXX: Query format subject to change
  226. if config.FilterPeers {
  227. // NOTE: addr is ip:port
  228. sw.SetAddrFilter(func(addr net.Addr) error {
  229. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  230. if err != nil {
  231. return err
  232. }
  233. if resQuery.Code.IsOK() {
  234. return nil
  235. }
  236. return errors.New(resQuery.Code.String())
  237. })
  238. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  239. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  240. if err != nil {
  241. return err
  242. }
  243. if resQuery.Code.IsOK() {
  244. return nil
  245. }
  246. return errors.New(resQuery.Code.String())
  247. })
  248. }
  249. eventBus := types.NewEventBus()
  250. eventBus.SetLogger(logger.With("module", "events"))
  251. // services which will be publishing and/or subscribing for messages (events)
  252. bcReactor.SetEventBus(eventBus)
  253. consensusReactor.SetEventBus(eventBus)
  254. // run the profile server
  255. profileHost := config.ProfListenAddress
  256. if profileHost != "" {
  257. go func() {
  258. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  259. }()
  260. }
  261. node := &Node{
  262. config: config,
  263. genesisDoc: genDoc,
  264. privValidator: privValidator,
  265. privKey: privKey,
  266. sw: sw,
  267. addrBook: addrBook,
  268. trustMetricStore: trustMetricStore,
  269. blockStore: blockStore,
  270. bcReactor: bcReactor,
  271. mempoolReactor: mempoolReactor,
  272. consensusState: consensusState,
  273. consensusReactor: consensusReactor,
  274. proxyApp: proxyApp,
  275. txIndexer: txIndexer,
  276. eventBus: eventBus,
  277. }
  278. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  279. return node, nil
  280. }
  281. // OnStart starts the Node. It implements cmn.Service.
  282. func (n *Node) OnStart() error {
  283. _, err := n.eventBus.Start()
  284. if err != nil {
  285. return err
  286. }
  287. // Run the RPC server first
  288. // so we can eg. receive txs for the first block
  289. if n.config.RPC.ListenAddress != "" {
  290. listeners, err := n.startRPC()
  291. if err != nil {
  292. return err
  293. }
  294. n.rpcListeners = listeners
  295. }
  296. // Create & add listener
  297. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  298. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  299. n.sw.AddListener(l)
  300. // Start the switch
  301. n.sw.SetNodeInfo(n.makeNodeInfo())
  302. n.sw.SetNodePrivKey(n.privKey)
  303. _, err = n.sw.Start()
  304. if err != nil {
  305. return err
  306. }
  307. // If seeds exist, add them to the address book and dial out
  308. if n.config.P2P.Seeds != "" {
  309. // dial out
  310. seeds := strings.Split(n.config.P2P.Seeds, ",")
  311. if err := n.DialSeeds(seeds); err != nil {
  312. return err
  313. }
  314. }
  315. return nil
  316. }
  317. // OnStop stops the Node. It implements cmn.Service.
  318. func (n *Node) OnStop() {
  319. n.BaseService.OnStop()
  320. n.Logger.Info("Stopping Node")
  321. // TODO: gracefully disconnect from peers.
  322. n.sw.Stop()
  323. for _, l := range n.rpcListeners {
  324. n.Logger.Info("Closing rpc listener", "listener", l)
  325. if err := l.Close(); err != nil {
  326. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  327. }
  328. }
  329. n.eventBus.Stop()
  330. }
  331. // RunForever waits for an interupt signal and stops the node.
  332. func (n *Node) RunForever() {
  333. // Sleep forever and then...
  334. cmn.TrapSignal(func() {
  335. n.Stop()
  336. })
  337. }
  338. // AddListener adds a listener to accept inbound peer connections.
  339. // It should be called before starting the Node.
  340. // The first listener is the primary listener (in NodeInfo)
  341. func (n *Node) AddListener(l p2p.Listener) {
  342. n.sw.AddListener(l)
  343. }
  344. // ConfigureRPC sets all variables in rpccore so they will serve
  345. // rpc calls from this node
  346. func (n *Node) ConfigureRPC() {
  347. rpccore.SetBlockStore(n.blockStore)
  348. rpccore.SetConsensusState(n.consensusState)
  349. rpccore.SetMempool(n.mempoolReactor.Mempool)
  350. rpccore.SetSwitch(n.sw)
  351. rpccore.SetPubKey(n.privValidator.GetPubKey())
  352. rpccore.SetGenesisDoc(n.genesisDoc)
  353. rpccore.SetAddrBook(n.addrBook)
  354. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  355. rpccore.SetTxIndexer(n.txIndexer)
  356. rpccore.SetConsensusReactor(n.consensusReactor)
  357. rpccore.SetEventBus(n.eventBus)
  358. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  359. }
  360. func (n *Node) startRPC() ([]net.Listener, error) {
  361. n.ConfigureRPC()
  362. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  363. if n.config.RPC.Unsafe {
  364. rpccore.AddUnsafeRoutes()
  365. }
  366. // we may expose the rpc over both a unix and tcp socket
  367. listeners := make([]net.Listener, len(listenAddrs))
  368. for i, listenAddr := range listenAddrs {
  369. mux := http.NewServeMux()
  370. rpcLogger := n.Logger.With("module", "rpc-server")
  371. onDisconnect := rpcserver.OnDisconnect(func(remoteAddr string) {
  372. n.eventBus.UnsubscribeAll(context.Background(), remoteAddr)
  373. })
  374. wm := rpcserver.NewWebsocketManager(rpccore.Routes, onDisconnect)
  375. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  376. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  377. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  378. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  379. if err != nil {
  380. return nil, err
  381. }
  382. listeners[i] = listener
  383. }
  384. // we expose a simplified api over grpc for convenience to app devs
  385. grpcListenAddr := n.config.RPC.GRPCListenAddress
  386. if grpcListenAddr != "" {
  387. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  388. if err != nil {
  389. return nil, err
  390. }
  391. listeners = append(listeners, listener)
  392. }
  393. return listeners, nil
  394. }
  395. // Switch returns the Node's Switch.
  396. func (n *Node) Switch() *p2p.Switch {
  397. return n.sw
  398. }
  399. // BlockStore returns the Node's BlockStore.
  400. func (n *Node) BlockStore() *bc.BlockStore {
  401. return n.blockStore
  402. }
  403. // ConsensusState returns the Node's ConsensusState.
  404. func (n *Node) ConsensusState() *consensus.ConsensusState {
  405. return n.consensusState
  406. }
  407. // ConsensusReactor returns the Node's ConsensusReactor.
  408. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  409. return n.consensusReactor
  410. }
  411. // MempoolReactor returns the Node's MempoolReactor.
  412. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  413. return n.mempoolReactor
  414. }
  415. // EventBus returns the Node's EventBus.
  416. func (n *Node) EventBus() *types.EventBus {
  417. return n.eventBus
  418. }
  419. // PrivValidator returns the Node's PrivValidator.
  420. // XXX: for convenience only!
  421. func (n *Node) PrivValidator() types.PrivValidator {
  422. return n.privValidator
  423. }
  424. // GenesisDoc returns the Node's GenesisDoc.
  425. func (n *Node) GenesisDoc() *types.GenesisDoc {
  426. return n.genesisDoc
  427. }
  428. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  429. func (n *Node) ProxyApp() proxy.AppConns {
  430. return n.proxyApp
  431. }
  432. func (n *Node) makeNodeInfo() *p2p.NodeInfo {
  433. txIndexerStatus := "on"
  434. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  435. txIndexerStatus = "off"
  436. }
  437. nodeInfo := &p2p.NodeInfo{
  438. PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519),
  439. Moniker: n.config.Moniker,
  440. Network: n.genesisDoc.ChainID,
  441. Version: version.Version,
  442. Other: []string{
  443. cmn.Fmt("wire_version=%v", wire.Version),
  444. cmn.Fmt("p2p_version=%v", p2p.Version),
  445. cmn.Fmt("consensus_version=%v", consensus.Version),
  446. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  447. cmn.Fmt("tx_index=%v", txIndexerStatus),
  448. },
  449. }
  450. rpcListenAddr := n.config.RPC.ListenAddress
  451. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  452. if !n.sw.IsListening() {
  453. return nodeInfo
  454. }
  455. p2pListener := n.sw.Listeners()[0]
  456. p2pHost := p2pListener.ExternalAddress().IP.String()
  457. p2pPort := p2pListener.ExternalAddress().Port
  458. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  459. return nodeInfo
  460. }
  461. //------------------------------------------------------------------------------
  462. // NodeInfo returns the Node's Info from the Switch.
  463. func (n *Node) NodeInfo() *p2p.NodeInfo {
  464. return n.sw.NodeInfo()
  465. }
  466. // DialSeeds dials the given seeds on the Switch.
  467. func (n *Node) DialSeeds(seeds []string) error {
  468. return n.sw.DialSeeds(n.addrBook, seeds)
  469. }
  470. //------------------------------------------------------------------------------
  471. var (
  472. genesisDocKey = []byte("genesisDoc")
  473. )
  474. // panics if failed to unmarshal bytes
  475. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  476. bytes := db.Get(genesisDocKey)
  477. if len(bytes) == 0 {
  478. return nil, errors.New("Genesis doc not found")
  479. } else {
  480. var genDoc *types.GenesisDoc
  481. err := json.Unmarshal(bytes, &genDoc)
  482. if err != nil {
  483. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  484. }
  485. return genDoc, nil
  486. }
  487. }
  488. // panics if failed to marshal the given genesis document
  489. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  490. bytes, err := json.Marshal(genDoc)
  491. if err != nil {
  492. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  493. }
  494. db.SetSync(genesisDocKey, bytes)
  495. }