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.

662 lines
20 KiB

10 years ago
7 years ago
10 years ago
7 years ago
11 years ago
7 years ago
11 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 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
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
11 years ago
8 years ago
11 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
11 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
11 years ago
11 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
10 years ago
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. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "strings"
  10. abci "github.com/tendermint/abci/types"
  11. crypto "github.com/tendermint/go-crypto"
  12. wire "github.com/tendermint/go-wire"
  13. cmn "github.com/tendermint/tmlibs/common"
  14. dbm "github.com/tendermint/tmlibs/db"
  15. "github.com/tendermint/tmlibs/log"
  16. bc "github.com/tendermint/tendermint/blockchain"
  17. cfg "github.com/tendermint/tendermint/config"
  18. cs "github.com/tendermint/tendermint/consensus"
  19. "github.com/tendermint/tendermint/evidence"
  20. mempl "github.com/tendermint/tendermint/mempool"
  21. "github.com/tendermint/tendermint/p2p"
  22. "github.com/tendermint/tendermint/p2p/pex"
  23. "github.com/tendermint/tendermint/p2p/trust"
  24. "github.com/tendermint/tendermint/proxy"
  25. rpccore "github.com/tendermint/tendermint/rpc/core"
  26. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  27. rpc "github.com/tendermint/tendermint/rpc/lib"
  28. rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
  29. sm "github.com/tendermint/tendermint/state"
  30. "github.com/tendermint/tendermint/state/txindex"
  31. "github.com/tendermint/tendermint/state/txindex/kv"
  32. "github.com/tendermint/tendermint/state/txindex/null"
  33. "github.com/tendermint/tendermint/types"
  34. priv_val "github.com/tendermint/tendermint/types/priv_validator"
  35. "github.com/tendermint/tendermint/version"
  36. _ "net/http/pprof"
  37. )
  38. //------------------------------------------------------------------------------
  39. // DBContext specifies config information for loading a new DB.
  40. type DBContext struct {
  41. ID string
  42. Config *cfg.Config
  43. }
  44. // DBProvider takes a DBContext and returns an instantiated DB.
  45. type DBProvider func(*DBContext) (dbm.DB, error)
  46. // DefaultDBProvider returns a database using the DBBackend and DBDir
  47. // specified in the ctx.Config.
  48. func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) {
  49. dbType := dbm.DBBackendType(ctx.Config.DBBackend)
  50. return dbm.NewDB(ctx.ID, dbType, ctx.Config.DBDir()), nil
  51. }
  52. // GenesisDocProvider returns a GenesisDoc.
  53. // It allows the GenesisDoc to be pulled from sources other than the
  54. // filesystem, for instance from a distributed key-value store cluster.
  55. type GenesisDocProvider func() (*types.GenesisDoc, error)
  56. // DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  57. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  58. func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider {
  59. return func() (*types.GenesisDoc, error) {
  60. return types.GenesisDocFromFile(config.GenesisFile())
  61. }
  62. }
  63. // NodeProvider takes a config and a logger and returns a ready to go Node.
  64. type NodeProvider func(*cfg.Config, log.Logger) (*Node, error)
  65. // DefaultNewNode returns a Tendermint node with default settings for the
  66. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  67. // It implements NodeProvider.
  68. func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) {
  69. return NewNode(config,
  70. types.LoadOrGenPrivValidatorFS(config.PrivValidatorFile()),
  71. proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()),
  72. DefaultGenesisDocProviderFunc(config),
  73. DefaultDBProvider,
  74. logger,
  75. )
  76. }
  77. //------------------------------------------------------------------------------
  78. // Node is the highest level interface to a full Tendermint node.
  79. // It includes all configuration information and running services.
  80. type Node struct {
  81. cmn.BaseService
  82. // config
  83. config *cfg.Config
  84. genesisDoc *types.GenesisDoc // initial validator set
  85. privValidator types.PrivValidator // local node's validator key
  86. // network
  87. sw *p2p.Switch // p2p connections
  88. addrBook pex.AddrBook // known peers
  89. trustMetricStore *trust.TrustMetricStore // trust metrics for all peers
  90. // services
  91. eventBus *types.EventBus // pub/sub for services
  92. stateDB dbm.DB
  93. blockStore *bc.BlockStore // store the blockchain to disk
  94. bcReactor *bc.BlockchainReactor // for fast-syncing
  95. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  96. consensusState *cs.ConsensusState // latest consensus state
  97. consensusReactor *cs.ConsensusReactor // for participating in the consensus
  98. evidencePool *evidence.EvidencePool // tracking evidence
  99. proxyApp proxy.AppConns // connection to the application
  100. rpcListeners []net.Listener // rpc servers
  101. txIndexer txindex.TxIndexer
  102. indexerService *txindex.IndexerService
  103. }
  104. // NewNode returns a new, ready to go, Tendermint Node.
  105. func NewNode(config *cfg.Config,
  106. privValidator types.PrivValidator,
  107. clientCreator proxy.ClientCreator,
  108. genesisDocProvider GenesisDocProvider,
  109. dbProvider DBProvider,
  110. logger log.Logger) (*Node, error) {
  111. // Get BlockStore
  112. blockStoreDB, err := dbProvider(&DBContext{"blockstore", config})
  113. if err != nil {
  114. return nil, err
  115. }
  116. blockStore := bc.NewBlockStore(blockStoreDB)
  117. // Get State
  118. stateDB, err := dbProvider(&DBContext{"state", config})
  119. if err != nil {
  120. return nil, err
  121. }
  122. // Get genesis doc
  123. // TODO: move to state package?
  124. genDoc, err := loadGenesisDoc(stateDB)
  125. if err != nil {
  126. genDoc, err = genesisDocProvider()
  127. if err != nil {
  128. return nil, err
  129. }
  130. // save genesis doc to prevent a certain class of user errors (e.g. when it
  131. // was changed, accidentally or not). Also good for audit trail.
  132. saveGenesisDoc(stateDB, genDoc)
  133. }
  134. state, err := sm.LoadStateFromDBOrGenesisDoc(stateDB, genDoc)
  135. if err != nil {
  136. return nil, err
  137. }
  138. // Create the proxyApp, which manages connections (consensus, mempool, query)
  139. // and sync tendermint and the app by performing a handshake
  140. // and replaying any necessary blocks
  141. consensusLogger := logger.With("module", "consensus")
  142. handshaker := cs.NewHandshaker(stateDB, state, blockStore, genDoc.AppState())
  143. handshaker.SetLogger(consensusLogger)
  144. proxyApp := proxy.NewAppConns(clientCreator, handshaker)
  145. proxyApp.SetLogger(logger.With("module", "proxy"))
  146. if err := proxyApp.Start(); err != nil {
  147. return nil, fmt.Errorf("Error starting proxy app connections: %v", err)
  148. }
  149. // reload the state (it may have been updated by the handshake)
  150. state = sm.LoadState(stateDB)
  151. // If an address is provided, listen on the socket for a
  152. // connection from an external signing process.
  153. if config.PrivValidatorListenAddr != "" {
  154. var (
  155. // TODO: persist this key so external signer
  156. // can actually authenticate us
  157. privKey = crypto.GenPrivKeyEd25519()
  158. pvsc = priv_val.NewSocketClient(
  159. logger.With("module", "priv_val"),
  160. config.PrivValidatorListenAddr,
  161. privKey,
  162. )
  163. )
  164. if err := pvsc.Start(); err != nil {
  165. return nil, fmt.Errorf("Error starting private validator client: %v", err)
  166. }
  167. privValidator = pvsc
  168. }
  169. // Decide whether to fast-sync or not
  170. // We don't fast-sync when the only validator is us.
  171. fastSync := config.FastSync
  172. if state.Validators.Size() == 1 {
  173. addr, _ := state.Validators.GetByIndex(0)
  174. if bytes.Equal(privValidator.GetAddress(), addr) {
  175. fastSync = false
  176. }
  177. }
  178. // Log whether this node is a validator or an observer
  179. if state.Validators.HasAddress(privValidator.GetAddress()) {
  180. consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  181. } else {
  182. consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  183. }
  184. // Make MempoolReactor
  185. mempoolLogger := logger.With("module", "mempool")
  186. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight)
  187. mempool.InitWAL() // no need to have the mempool wal during tests
  188. mempool.SetLogger(mempoolLogger)
  189. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  190. mempoolReactor.SetLogger(mempoolLogger)
  191. if config.Consensus.WaitForTxs() {
  192. mempool.EnableTxsAvailable()
  193. }
  194. // Make Evidence Reactor
  195. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  196. if err != nil {
  197. return nil, err
  198. }
  199. evidenceLogger := logger.With("module", "evidence")
  200. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  201. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  202. evidencePool.SetLogger(evidenceLogger)
  203. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  204. evidenceReactor.SetLogger(evidenceLogger)
  205. blockExecLogger := logger.With("module", "state")
  206. // make block executor for consensus and blockchain reactors to execute blocks
  207. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  208. // Make BlockchainReactor
  209. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  210. bcReactor.SetLogger(logger.With("module", "blockchain"))
  211. // Make ConsensusReactor
  212. consensusState := cs.NewConsensusState(config.Consensus, state.Copy(),
  213. blockExec, blockStore, mempool, evidencePool)
  214. consensusState.SetLogger(consensusLogger)
  215. if privValidator != nil {
  216. consensusState.SetPrivValidator(privValidator)
  217. }
  218. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync)
  219. consensusReactor.SetLogger(consensusLogger)
  220. p2pLogger := logger.With("module", "p2p")
  221. sw := p2p.NewSwitch(config.P2P)
  222. sw.SetLogger(p2pLogger)
  223. sw.AddReactor("MEMPOOL", mempoolReactor)
  224. sw.AddReactor("BLOCKCHAIN", bcReactor)
  225. sw.AddReactor("CONSENSUS", consensusReactor)
  226. sw.AddReactor("EVIDENCE", evidenceReactor)
  227. // Optionally, start the pex reactor
  228. var addrBook pex.AddrBook
  229. var trustMetricStore *trust.TrustMetricStore
  230. if config.P2P.PexReactor {
  231. addrBook = pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  232. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  233. // Get the trust metric history data
  234. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  235. if err != nil {
  236. return nil, err
  237. }
  238. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  239. trustMetricStore.SetLogger(p2pLogger)
  240. var seeds []string
  241. if config.P2P.Seeds != "" {
  242. seeds = strings.Split(config.P2P.Seeds, ",")
  243. }
  244. var privatePeerIDs []string
  245. if config.P2P.PrivatePeerIDs != "" {
  246. privatePeerIDs = strings.Split(config.P2P.PrivatePeerIDs, ",")
  247. }
  248. pexReactor := pex.NewPEXReactor(addrBook,
  249. &pex.PEXReactorConfig{
  250. Seeds: seeds,
  251. SeedMode: config.P2P.SeedMode,
  252. PrivatePeerIDs: privatePeerIDs})
  253. pexReactor.SetLogger(p2pLogger)
  254. sw.AddReactor("PEX", pexReactor)
  255. }
  256. sw.SetAddrBook(addrBook)
  257. // Filter peers by addr or pubkey with an ABCI query.
  258. // If the query return code is OK, add peer.
  259. // XXX: Query format subject to change
  260. if config.FilterPeers {
  261. // NOTE: addr is ip:port
  262. sw.SetAddrFilter(func(addr net.Addr) error {
  263. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  264. if err != nil {
  265. return err
  266. }
  267. if resQuery.IsErr() {
  268. return fmt.Errorf("Error querying abci app: %v", resQuery)
  269. }
  270. return nil
  271. })
  272. sw.SetIDFilter(func(id p2p.ID) error {
  273. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%s", id)})
  274. if err != nil {
  275. return err
  276. }
  277. if resQuery.IsErr() {
  278. return fmt.Errorf("Error querying abci app: %v", resQuery)
  279. }
  280. return nil
  281. })
  282. }
  283. eventBus := types.NewEventBus()
  284. eventBus.SetLogger(logger.With("module", "events"))
  285. // services which will be publishing and/or subscribing for messages (events)
  286. // consensusReactor will set it on consensusState and blockExecutor
  287. consensusReactor.SetEventBus(eventBus)
  288. // Transaction indexing
  289. var txIndexer txindex.TxIndexer
  290. switch config.TxIndex.Indexer {
  291. case "kv":
  292. store, err := dbProvider(&DBContext{"tx_index", config})
  293. if err != nil {
  294. return nil, err
  295. }
  296. if config.TxIndex.IndexTags != "" {
  297. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  298. } else if config.TxIndex.IndexAllTags {
  299. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  300. } else {
  301. txIndexer = kv.NewTxIndex(store)
  302. }
  303. default:
  304. txIndexer = &null.TxIndex{}
  305. }
  306. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  307. // run the profile server
  308. profileHost := config.ProfListenAddress
  309. if profileHost != "" {
  310. go func() {
  311. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  312. }()
  313. }
  314. node := &Node{
  315. config: config,
  316. genesisDoc: genDoc,
  317. privValidator: privValidator,
  318. sw: sw,
  319. addrBook: addrBook,
  320. trustMetricStore: trustMetricStore,
  321. stateDB: stateDB,
  322. blockStore: blockStore,
  323. bcReactor: bcReactor,
  324. mempoolReactor: mempoolReactor,
  325. consensusState: consensusState,
  326. consensusReactor: consensusReactor,
  327. evidencePool: evidencePool,
  328. proxyApp: proxyApp,
  329. txIndexer: txIndexer,
  330. indexerService: indexerService,
  331. eventBus: eventBus,
  332. }
  333. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  334. return node, nil
  335. }
  336. // OnStart starts the Node. It implements cmn.Service.
  337. func (n *Node) OnStart() error {
  338. err := n.eventBus.Start()
  339. if err != nil {
  340. return err
  341. }
  342. // Run the RPC server first
  343. // so we can eg. receive txs for the first block
  344. if n.config.RPC.ListenAddress != "" {
  345. listeners, err := n.startRPC()
  346. if err != nil {
  347. return err
  348. }
  349. n.rpcListeners = listeners
  350. }
  351. // Create & add listener
  352. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  353. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  354. n.sw.AddListener(l)
  355. // Generate node PrivKey
  356. // TODO: pass in like privValidator
  357. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  358. if err != nil {
  359. return err
  360. }
  361. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  362. // Start the switch
  363. n.sw.SetNodeInfo(n.makeNodeInfo(nodeKey.PubKey()))
  364. n.sw.SetNodeKey(nodeKey)
  365. err = n.sw.Start()
  366. if err != nil {
  367. return err
  368. }
  369. // Always connect to persistent peers
  370. if n.config.P2P.PersistentPeers != "" {
  371. err = n.sw.DialPeersAsync(n.addrBook, strings.Split(n.config.P2P.PersistentPeers, ","), true)
  372. if err != nil {
  373. return err
  374. }
  375. }
  376. // start tx indexer
  377. return n.indexerService.Start()
  378. }
  379. // OnStop stops the Node. It implements cmn.Service.
  380. func (n *Node) OnStop() {
  381. n.BaseService.OnStop()
  382. n.Logger.Info("Stopping Node")
  383. // TODO: gracefully disconnect from peers.
  384. n.sw.Stop()
  385. for _, l := range n.rpcListeners {
  386. n.Logger.Info("Closing rpc listener", "listener", l)
  387. if err := l.Close(); err != nil {
  388. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  389. }
  390. }
  391. n.eventBus.Stop()
  392. n.indexerService.Stop()
  393. if pvsc, ok := n.privValidator.(*priv_val.SocketClient); ok {
  394. if err := pvsc.Stop(); err != nil {
  395. n.Logger.Error("Error stopping priv validator socket client", "err", err)
  396. }
  397. }
  398. }
  399. // RunForever waits for an interrupt signal and stops the node.
  400. func (n *Node) RunForever() {
  401. // Sleep forever and then...
  402. cmn.TrapSignal(func() {
  403. n.Stop()
  404. })
  405. }
  406. // AddListener adds a listener to accept inbound peer connections.
  407. // It should be called before starting the Node.
  408. // The first listener is the primary listener (in NodeInfo)
  409. func (n *Node) AddListener(l p2p.Listener) {
  410. n.sw.AddListener(l)
  411. }
  412. // ConfigureRPC sets all variables in rpccore so they will serve
  413. // rpc calls from this node
  414. func (n *Node) ConfigureRPC() {
  415. rpccore.SetStateDB(n.stateDB)
  416. rpccore.SetBlockStore(n.blockStore)
  417. rpccore.SetConsensusState(n.consensusState)
  418. rpccore.SetMempool(n.mempoolReactor.Mempool)
  419. rpccore.SetEvidencePool(n.evidencePool)
  420. rpccore.SetSwitch(n.sw)
  421. rpccore.SetPubKey(n.privValidator.GetPubKey())
  422. rpccore.SetGenesisDoc(n.genesisDoc)
  423. rpccore.SetAddrBook(n.addrBook)
  424. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  425. rpccore.SetTxIndexer(n.txIndexer)
  426. rpccore.SetConsensusReactor(n.consensusReactor)
  427. rpccore.SetEventBus(n.eventBus)
  428. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  429. }
  430. func (n *Node) startRPC() ([]net.Listener, error) {
  431. n.ConfigureRPC()
  432. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  433. if n.config.RPC.Unsafe {
  434. rpccore.AddUnsafeRoutes()
  435. }
  436. // we may expose the rpc over both a unix and tcp socket
  437. listeners := make([]net.Listener, len(listenAddrs))
  438. for i, listenAddr := range listenAddrs {
  439. mux := http.NewServeMux()
  440. rpcLogger := n.Logger.With("module", "rpc-server")
  441. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  442. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  443. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  444. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  445. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  446. if err != nil {
  447. return nil, err
  448. }
  449. listeners[i] = listener
  450. }
  451. // we expose a simplified api over grpc for convenience to app devs
  452. grpcListenAddr := n.config.RPC.GRPCListenAddress
  453. if grpcListenAddr != "" {
  454. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  455. if err != nil {
  456. return nil, err
  457. }
  458. listeners = append(listeners, listener)
  459. }
  460. return listeners, nil
  461. }
  462. // Switch returns the Node's Switch.
  463. func (n *Node) Switch() *p2p.Switch {
  464. return n.sw
  465. }
  466. // BlockStore returns the Node's BlockStore.
  467. func (n *Node) BlockStore() *bc.BlockStore {
  468. return n.blockStore
  469. }
  470. // ConsensusState returns the Node's ConsensusState.
  471. func (n *Node) ConsensusState() *cs.ConsensusState {
  472. return n.consensusState
  473. }
  474. // ConsensusReactor returns the Node's ConsensusReactor.
  475. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  476. return n.consensusReactor
  477. }
  478. // MempoolReactor returns the Node's MempoolReactor.
  479. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  480. return n.mempoolReactor
  481. }
  482. // EvidencePool returns the Node's EvidencePool.
  483. func (n *Node) EvidencePool() *evidence.EvidencePool {
  484. return n.evidencePool
  485. }
  486. // EventBus returns the Node's EventBus.
  487. func (n *Node) EventBus() *types.EventBus {
  488. return n.eventBus
  489. }
  490. // PrivValidator returns the Node's PrivValidator.
  491. // XXX: for convenience only!
  492. func (n *Node) PrivValidator() types.PrivValidator {
  493. return n.privValidator
  494. }
  495. // GenesisDoc returns the Node's GenesisDoc.
  496. func (n *Node) GenesisDoc() *types.GenesisDoc {
  497. return n.genesisDoc
  498. }
  499. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  500. func (n *Node) ProxyApp() proxy.AppConns {
  501. return n.proxyApp
  502. }
  503. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) p2p.NodeInfo {
  504. txIndexerStatus := "on"
  505. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  506. txIndexerStatus = "off"
  507. }
  508. nodeInfo := p2p.NodeInfo{
  509. PubKey: pubKey,
  510. Network: n.genesisDoc.ChainID,
  511. Version: version.Version,
  512. Channels: []byte{
  513. bc.BlockchainChannel,
  514. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  515. mempl.MempoolChannel,
  516. evidence.EvidenceChannel,
  517. },
  518. Moniker: n.config.Moniker,
  519. Other: []string{
  520. cmn.Fmt("wire_version=%v", wire.Version),
  521. cmn.Fmt("p2p_version=%v", p2p.Version),
  522. cmn.Fmt("consensus_version=%v", cs.Version),
  523. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  524. cmn.Fmt("tx_index=%v", txIndexerStatus),
  525. },
  526. }
  527. if n.config.P2P.PexReactor {
  528. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  529. }
  530. rpcListenAddr := n.config.RPC.ListenAddress
  531. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  532. if !n.sw.IsListening() {
  533. return nodeInfo
  534. }
  535. p2pListener := n.sw.Listeners()[0]
  536. p2pHost := p2pListener.ExternalAddress().IP.String()
  537. p2pPort := p2pListener.ExternalAddress().Port
  538. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  539. return nodeInfo
  540. }
  541. //------------------------------------------------------------------------------
  542. // NodeInfo returns the Node's Info from the Switch.
  543. func (n *Node) NodeInfo() p2p.NodeInfo {
  544. return n.sw.NodeInfo()
  545. }
  546. //------------------------------------------------------------------------------
  547. var (
  548. genesisDocKey = []byte("genesisDoc")
  549. )
  550. // panics if failed to unmarshal bytes
  551. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  552. bytes := db.Get(genesisDocKey)
  553. if len(bytes) == 0 {
  554. return nil, errors.New("Genesis doc not found")
  555. }
  556. var genDoc *types.GenesisDoc
  557. err := json.Unmarshal(bytes, &genDoc)
  558. if err != nil {
  559. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  560. }
  561. return genDoc, nil
  562. }
  563. // panics if failed to marshal the given genesis document
  564. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  565. bytes, err := json.Marshal(genDoc)
  566. if err != nil {
  567. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  568. }
  569. db.SetSync(genesisDocKey, bytes)
  570. }