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.

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