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.

656 lines
20 KiB

10 years ago
7 years ago
10 years ago
7 years ago
10 years ago
7 years ago
10 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
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
7 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
10 years ago
8 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
8 years ago
10 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
10 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
8 years ago
10 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
9 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "strings"
  10. abci "github.com/tendermint/abci/types"
  11. crypto "github.com/tendermint/go-crypto"
  12. wire "github.com/tendermint/go-wire"
  13. cmn "github.com/tendermint/tmlibs/common"
  14. dbm "github.com/tendermint/tmlibs/db"
  15. "github.com/tendermint/tmlibs/log"
  16. bc "github.com/tendermint/tendermint/blockchain"
  17. cfg "github.com/tendermint/tendermint/config"
  18. 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. pexReactor := pex.NewPEXReactor(addrBook,
  245. &pex.PEXReactorConfig{Seeds: seeds, SeedMode: config.P2P.SeedMode})
  246. pexReactor.SetLogger(p2pLogger)
  247. sw.AddReactor("PEX", pexReactor)
  248. }
  249. sw.SetAddrBook(addrBook)
  250. // Filter peers by addr or pubkey with an ABCI query.
  251. // If the query return code is OK, add peer.
  252. // XXX: Query format subject to change
  253. if config.FilterPeers {
  254. // NOTE: addr is ip:port
  255. sw.SetAddrFilter(func(addr net.Addr) error {
  256. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  257. if err != nil {
  258. return err
  259. }
  260. if resQuery.IsErr() {
  261. return fmt.Errorf("Error querying abci app: %v", resQuery)
  262. }
  263. return nil
  264. })
  265. sw.SetIDFilter(func(id p2p.ID) error {
  266. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%s", id)})
  267. if err != nil {
  268. return err
  269. }
  270. if resQuery.IsErr() {
  271. return fmt.Errorf("Error querying abci app: %v", resQuery)
  272. }
  273. return nil
  274. })
  275. }
  276. eventBus := types.NewEventBus()
  277. eventBus.SetLogger(logger.With("module", "events"))
  278. // services which will be publishing and/or subscribing for messages (events)
  279. // consensusReactor will set it on consensusState and blockExecutor
  280. consensusReactor.SetEventBus(eventBus)
  281. // Transaction indexing
  282. var txIndexer txindex.TxIndexer
  283. switch config.TxIndex.Indexer {
  284. case "kv":
  285. store, err := dbProvider(&DBContext{"tx_index", config})
  286. if err != nil {
  287. return nil, err
  288. }
  289. if config.TxIndex.IndexTags != "" {
  290. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  291. } else if config.TxIndex.IndexAllTags {
  292. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  293. } else {
  294. txIndexer = kv.NewTxIndex(store)
  295. }
  296. default:
  297. txIndexer = &null.TxIndex{}
  298. }
  299. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  300. // run the profile server
  301. profileHost := config.ProfListenAddress
  302. if profileHost != "" {
  303. go func() {
  304. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  305. }()
  306. }
  307. node := &Node{
  308. config: config,
  309. genesisDoc: genDoc,
  310. privValidator: privValidator,
  311. sw: sw,
  312. addrBook: addrBook,
  313. trustMetricStore: trustMetricStore,
  314. stateDB: stateDB,
  315. blockStore: blockStore,
  316. bcReactor: bcReactor,
  317. mempoolReactor: mempoolReactor,
  318. consensusState: consensusState,
  319. consensusReactor: consensusReactor,
  320. evidencePool: evidencePool,
  321. proxyApp: proxyApp,
  322. txIndexer: txIndexer,
  323. indexerService: indexerService,
  324. eventBus: eventBus,
  325. }
  326. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  327. return node, nil
  328. }
  329. // OnStart starts the Node. It implements cmn.Service.
  330. func (n *Node) OnStart() error {
  331. err := n.eventBus.Start()
  332. if err != nil {
  333. return err
  334. }
  335. // Run the RPC server first
  336. // so we can eg. receive txs for the first block
  337. if n.config.RPC.ListenAddress != "" {
  338. listeners, err := n.startRPC()
  339. if err != nil {
  340. return err
  341. }
  342. n.rpcListeners = listeners
  343. }
  344. // Create & add listener
  345. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  346. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  347. n.sw.AddListener(l)
  348. // Generate node PrivKey
  349. // TODO: pass in like privValidator
  350. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  351. if err != nil {
  352. return err
  353. }
  354. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  355. // Start the switch
  356. n.sw.SetNodeInfo(n.makeNodeInfo(nodeKey.PubKey()))
  357. n.sw.SetNodeKey(nodeKey)
  358. err = n.sw.Start()
  359. if err != nil {
  360. return err
  361. }
  362. // Always connect to persistent peers
  363. if n.config.P2P.PersistentPeers != "" {
  364. err = n.sw.DialPeersAsync(n.addrBook, strings.Split(n.config.P2P.PersistentPeers, ","), true)
  365. if err != nil {
  366. return err
  367. }
  368. }
  369. // start tx indexer
  370. return n.indexerService.Start()
  371. }
  372. // OnStop stops the Node. It implements cmn.Service.
  373. func (n *Node) OnStop() {
  374. n.BaseService.OnStop()
  375. n.Logger.Info("Stopping Node")
  376. // TODO: gracefully disconnect from peers.
  377. n.sw.Stop()
  378. for _, l := range n.rpcListeners {
  379. n.Logger.Info("Closing rpc listener", "listener", l)
  380. if err := l.Close(); err != nil {
  381. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  382. }
  383. }
  384. n.eventBus.Stop()
  385. n.indexerService.Stop()
  386. if pvsc, ok := n.privValidator.(*priv_val.SocketClient); ok {
  387. if err := pvsc.Stop(); err != nil {
  388. n.Logger.Error("Error stopping priv validator socket client", "err", err)
  389. }
  390. }
  391. }
  392. // RunForever waits for an interrupt signal and stops the node.
  393. func (n *Node) RunForever() {
  394. // Sleep forever and then...
  395. cmn.TrapSignal(func() {
  396. n.Stop()
  397. })
  398. }
  399. // AddListener adds a listener to accept inbound peer connections.
  400. // It should be called before starting the Node.
  401. // The first listener is the primary listener (in NodeInfo)
  402. func (n *Node) AddListener(l p2p.Listener) {
  403. n.sw.AddListener(l)
  404. }
  405. // ConfigureRPC sets all variables in rpccore so they will serve
  406. // rpc calls from this node
  407. func (n *Node) ConfigureRPC() {
  408. rpccore.SetStateDB(n.stateDB)
  409. rpccore.SetBlockStore(n.blockStore)
  410. rpccore.SetConsensusState(n.consensusState)
  411. rpccore.SetMempool(n.mempoolReactor.Mempool)
  412. rpccore.SetEvidencePool(n.evidencePool)
  413. rpccore.SetSwitch(n.sw)
  414. rpccore.SetPubKey(n.privValidator.GetPubKey())
  415. rpccore.SetGenesisDoc(n.genesisDoc)
  416. rpccore.SetAddrBook(n.addrBook)
  417. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  418. rpccore.SetTxIndexer(n.txIndexer)
  419. rpccore.SetConsensusReactor(n.consensusReactor)
  420. rpccore.SetEventBus(n.eventBus)
  421. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  422. }
  423. func (n *Node) startRPC() ([]net.Listener, error) {
  424. n.ConfigureRPC()
  425. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  426. if n.config.RPC.Unsafe {
  427. rpccore.AddUnsafeRoutes()
  428. }
  429. // we may expose the rpc over both a unix and tcp socket
  430. listeners := make([]net.Listener, len(listenAddrs))
  431. for i, listenAddr := range listenAddrs {
  432. mux := http.NewServeMux()
  433. rpcLogger := n.Logger.With("module", "rpc-server")
  434. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  435. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  436. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  437. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  438. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  439. if err != nil {
  440. return nil, err
  441. }
  442. listeners[i] = listener
  443. }
  444. // we expose a simplified api over grpc for convenience to app devs
  445. grpcListenAddr := n.config.RPC.GRPCListenAddress
  446. if grpcListenAddr != "" {
  447. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  448. if err != nil {
  449. return nil, err
  450. }
  451. listeners = append(listeners, listener)
  452. }
  453. return listeners, nil
  454. }
  455. // Switch returns the Node's Switch.
  456. func (n *Node) Switch() *p2p.Switch {
  457. return n.sw
  458. }
  459. // BlockStore returns the Node's BlockStore.
  460. func (n *Node) BlockStore() *bc.BlockStore {
  461. return n.blockStore
  462. }
  463. // ConsensusState returns the Node's ConsensusState.
  464. func (n *Node) ConsensusState() *cs.ConsensusState {
  465. return n.consensusState
  466. }
  467. // ConsensusReactor returns the Node's ConsensusReactor.
  468. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  469. return n.consensusReactor
  470. }
  471. // MempoolReactor returns the Node's MempoolReactor.
  472. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  473. return n.mempoolReactor
  474. }
  475. // EvidencePool returns the Node's EvidencePool.
  476. func (n *Node) EvidencePool() *evidence.EvidencePool {
  477. return n.evidencePool
  478. }
  479. // EventBus returns the Node's EventBus.
  480. func (n *Node) EventBus() *types.EventBus {
  481. return n.eventBus
  482. }
  483. // PrivValidator returns the Node's PrivValidator.
  484. // XXX: for convenience only!
  485. func (n *Node) PrivValidator() types.PrivValidator {
  486. return n.privValidator
  487. }
  488. // GenesisDoc returns the Node's GenesisDoc.
  489. func (n *Node) GenesisDoc() *types.GenesisDoc {
  490. return n.genesisDoc
  491. }
  492. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  493. func (n *Node) ProxyApp() proxy.AppConns {
  494. return n.proxyApp
  495. }
  496. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) p2p.NodeInfo {
  497. txIndexerStatus := "on"
  498. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  499. txIndexerStatus = "off"
  500. }
  501. nodeInfo := p2p.NodeInfo{
  502. PubKey: pubKey,
  503. Network: n.genesisDoc.ChainID,
  504. Version: version.Version,
  505. Channels: []byte{
  506. bc.BlockchainChannel,
  507. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  508. mempl.MempoolChannel,
  509. evidence.EvidenceChannel,
  510. },
  511. Moniker: n.config.Moniker,
  512. Other: []string{
  513. cmn.Fmt("wire_version=%v", wire.Version),
  514. cmn.Fmt("p2p_version=%v", p2p.Version),
  515. cmn.Fmt("consensus_version=%v", cs.Version),
  516. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  517. cmn.Fmt("tx_index=%v", txIndexerStatus),
  518. },
  519. }
  520. if n.config.P2P.PexReactor {
  521. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  522. }
  523. rpcListenAddr := n.config.RPC.ListenAddress
  524. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  525. if !n.sw.IsListening() {
  526. return nodeInfo
  527. }
  528. p2pListener := n.sw.Listeners()[0]
  529. p2pHost := p2pListener.ExternalAddress().IP.String()
  530. p2pPort := p2pListener.ExternalAddress().Port
  531. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  532. return nodeInfo
  533. }
  534. //------------------------------------------------------------------------------
  535. // NodeInfo returns the Node's Info from the Switch.
  536. func (n *Node) NodeInfo() p2p.NodeInfo {
  537. return n.sw.NodeInfo()
  538. }
  539. //------------------------------------------------------------------------------
  540. var (
  541. genesisDocKey = []byte("genesisDoc")
  542. )
  543. // panics if failed to unmarshal bytes
  544. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  545. bytes := db.Get(genesisDocKey)
  546. if len(bytes) == 0 {
  547. return nil, errors.New("Genesis doc not found")
  548. } else {
  549. var genDoc *types.GenesisDoc
  550. err := json.Unmarshal(bytes, &genDoc)
  551. if err != nil {
  552. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  553. }
  554. return genDoc, nil
  555. }
  556. }
  557. // panics if failed to marshal the given genesis document
  558. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  559. bytes, err := json.Marshal(genDoc)
  560. if err != nil {
  561. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  562. }
  563. db.SetSync(genesisDocKey, bytes)
  564. }