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.

646 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. // Connect to external signing process, if an address is provided.
  152. if config.PrivValidatorAddr != "" {
  153. var (
  154. privKey = crypto.GenPrivKeyEd25519()
  155. pvsc = priv_val.NewSocketClient(
  156. logger.With("module", "priv_val"),
  157. config.PrivValidatorAddr,
  158. &privKey,
  159. )
  160. )
  161. if err := pvsc.Start(); err != nil {
  162. return nil, fmt.Errorf("Error starting private validator client: %v", err)
  163. }
  164. privValidator = pvsc
  165. }
  166. // Decide whether to fast-sync or not
  167. // We don't fast-sync when the only validator is us.
  168. fastSync := config.FastSync
  169. if state.Validators.Size() == 1 {
  170. addr, _ := state.Validators.GetByIndex(0)
  171. if bytes.Equal(privValidator.GetAddress(), addr) {
  172. fastSync = false
  173. }
  174. }
  175. // Log whether this node is a validator or an observer
  176. if state.Validators.HasAddress(privValidator.GetAddress()) {
  177. consensusLogger.Info("This node is a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  178. } else {
  179. consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey())
  180. }
  181. // Make MempoolReactor
  182. mempoolLogger := logger.With("module", "mempool")
  183. mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight)
  184. mempool.InitWAL() // no need to have the mempool wal during tests
  185. mempool.SetLogger(mempoolLogger)
  186. mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool)
  187. mempoolReactor.SetLogger(mempoolLogger)
  188. if config.Consensus.WaitForTxs() {
  189. mempool.EnableTxsAvailable()
  190. }
  191. // Make Evidence Reactor
  192. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  193. if err != nil {
  194. return nil, err
  195. }
  196. evidenceLogger := logger.With("module", "evidence")
  197. evidenceStore := evidence.NewEvidenceStore(evidenceDB)
  198. evidencePool := evidence.NewEvidencePool(stateDB, evidenceStore)
  199. evidencePool.SetLogger(evidenceLogger)
  200. evidenceReactor := evidence.NewEvidenceReactor(evidencePool)
  201. evidenceReactor.SetLogger(evidenceLogger)
  202. blockExecLogger := logger.With("module", "state")
  203. // make block executor for consensus and blockchain reactors to execute blocks
  204. blockExec := sm.NewBlockExecutor(stateDB, blockExecLogger, proxyApp.Consensus(), mempool, evidencePool)
  205. // Make BlockchainReactor
  206. bcReactor := bc.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  207. bcReactor.SetLogger(logger.With("module", "blockchain"))
  208. // Make ConsensusReactor
  209. consensusState := cs.NewConsensusState(config.Consensus, state.Copy(),
  210. blockExec, blockStore, mempool, evidencePool)
  211. consensusState.SetLogger(consensusLogger)
  212. if privValidator != nil {
  213. consensusState.SetPrivValidator(privValidator)
  214. }
  215. consensusReactor := cs.NewConsensusReactor(consensusState, fastSync)
  216. consensusReactor.SetLogger(consensusLogger)
  217. p2pLogger := logger.With("module", "p2p")
  218. sw := p2p.NewSwitch(config.P2P)
  219. sw.SetLogger(p2pLogger)
  220. sw.AddReactor("MEMPOOL", mempoolReactor)
  221. sw.AddReactor("BLOCKCHAIN", bcReactor)
  222. sw.AddReactor("CONSENSUS", consensusReactor)
  223. sw.AddReactor("EVIDENCE", evidenceReactor)
  224. // Optionally, start the pex reactor
  225. var addrBook pex.AddrBook
  226. var trustMetricStore *trust.TrustMetricStore
  227. if config.P2P.PexReactor {
  228. addrBook = pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  229. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  230. // Get the trust metric history data
  231. trustHistoryDB, err := dbProvider(&DBContext{"trusthistory", config})
  232. if err != nil {
  233. return nil, err
  234. }
  235. trustMetricStore = trust.NewTrustMetricStore(trustHistoryDB, trust.DefaultConfig())
  236. trustMetricStore.SetLogger(p2pLogger)
  237. var seeds []string
  238. if config.P2P.Seeds != "" {
  239. seeds = strings.Split(config.P2P.Seeds, ",")
  240. }
  241. pexReactor := pex.NewPEXReactor(addrBook,
  242. &pex.PEXReactorConfig{Seeds: seeds, SeedMode: config.P2P.SeedMode})
  243. pexReactor.SetLogger(p2pLogger)
  244. sw.AddReactor("PEX", pexReactor)
  245. }
  246. // Filter peers by addr or pubkey with an ABCI query.
  247. // If the query return code is OK, add peer.
  248. // XXX: Query format subject to change
  249. if config.FilterPeers {
  250. // NOTE: addr is ip:port
  251. sw.SetAddrFilter(func(addr net.Addr) error {
  252. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  253. if err != nil {
  254. return err
  255. }
  256. if resQuery.IsErr() {
  257. return fmt.Errorf("Error querying abci app: %v", resQuery)
  258. }
  259. return nil
  260. })
  261. sw.SetIDFilter(func(id p2p.ID) error {
  262. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%s", id)})
  263. if err != nil {
  264. return err
  265. }
  266. if resQuery.IsErr() {
  267. return fmt.Errorf("Error querying abci app: %v", resQuery)
  268. }
  269. return nil
  270. })
  271. }
  272. eventBus := types.NewEventBus()
  273. eventBus.SetLogger(logger.With("module", "events"))
  274. // services which will be publishing and/or subscribing for messages (events)
  275. // consensusReactor will set it on consensusState and blockExecutor
  276. consensusReactor.SetEventBus(eventBus)
  277. // Transaction indexing
  278. var txIndexer txindex.TxIndexer
  279. switch config.TxIndex.Indexer {
  280. case "kv":
  281. store, err := dbProvider(&DBContext{"tx_index", config})
  282. if err != nil {
  283. return nil, err
  284. }
  285. if config.TxIndex.IndexTags != "" {
  286. txIndexer = kv.NewTxIndex(store, kv.IndexTags(strings.Split(config.TxIndex.IndexTags, ",")))
  287. } else if config.TxIndex.IndexAllTags {
  288. txIndexer = kv.NewTxIndex(store, kv.IndexAllTags())
  289. } else {
  290. txIndexer = kv.NewTxIndex(store)
  291. }
  292. default:
  293. txIndexer = &null.TxIndex{}
  294. }
  295. indexerService := txindex.NewIndexerService(txIndexer, eventBus)
  296. // run the profile server
  297. profileHost := config.ProfListenAddress
  298. if profileHost != "" {
  299. go func() {
  300. logger.Error("Profile server", "err", http.ListenAndServe(profileHost, nil))
  301. }()
  302. }
  303. node := &Node{
  304. config: config,
  305. genesisDoc: genDoc,
  306. privValidator: privValidator,
  307. sw: sw,
  308. addrBook: addrBook,
  309. trustMetricStore: trustMetricStore,
  310. stateDB: stateDB,
  311. blockStore: blockStore,
  312. bcReactor: bcReactor,
  313. mempoolReactor: mempoolReactor,
  314. consensusState: consensusState,
  315. consensusReactor: consensusReactor,
  316. evidencePool: evidencePool,
  317. proxyApp: proxyApp,
  318. txIndexer: txIndexer,
  319. indexerService: indexerService,
  320. eventBus: eventBus,
  321. }
  322. node.BaseService = *cmn.NewBaseService(logger, "Node", node)
  323. return node, nil
  324. }
  325. // OnStart starts the Node. It implements cmn.Service.
  326. func (n *Node) OnStart() error {
  327. err := n.eventBus.Start()
  328. if err != nil {
  329. return err
  330. }
  331. // Run the RPC server first
  332. // so we can eg. receive txs for the first block
  333. if n.config.RPC.ListenAddress != "" {
  334. listeners, err := n.startRPC()
  335. if err != nil {
  336. return err
  337. }
  338. n.rpcListeners = listeners
  339. }
  340. // Create & add listener
  341. protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress)
  342. l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p"))
  343. n.sw.AddListener(l)
  344. // Generate node PrivKey
  345. // TODO: pass in like priv_val
  346. nodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile())
  347. if err != nil {
  348. return err
  349. }
  350. n.Logger.Info("P2P Node ID", "ID", nodeKey.ID(), "file", n.config.NodeKeyFile())
  351. // Start the switch
  352. n.sw.SetNodeInfo(n.makeNodeInfo(nodeKey.PubKey()))
  353. n.sw.SetNodeKey(nodeKey)
  354. err = n.sw.Start()
  355. if err != nil {
  356. return err
  357. }
  358. // Always connect to persistent peers
  359. if n.config.P2P.PersistentPeers != "" {
  360. err = n.sw.DialPeersAsync(n.addrBook, strings.Split(n.config.P2P.PersistentPeers, ","), true)
  361. if err != nil {
  362. return err
  363. }
  364. }
  365. // start tx indexer
  366. return n.indexerService.Start()
  367. }
  368. // OnStop stops the Node. It implements cmn.Service.
  369. func (n *Node) OnStop() {
  370. n.BaseService.OnStop()
  371. n.Logger.Info("Stopping Node")
  372. // TODO: gracefully disconnect from peers.
  373. n.sw.Stop()
  374. for _, l := range n.rpcListeners {
  375. n.Logger.Info("Closing rpc listener", "listener", l)
  376. if err := l.Close(); err != nil {
  377. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  378. }
  379. }
  380. n.eventBus.Stop()
  381. n.indexerService.Stop()
  382. }
  383. // RunForever waits for an interrupt signal and stops the node.
  384. func (n *Node) RunForever() {
  385. // Sleep forever and then...
  386. cmn.TrapSignal(func() {
  387. n.Stop()
  388. })
  389. }
  390. // AddListener adds a listener to accept inbound peer connections.
  391. // It should be called before starting the Node.
  392. // The first listener is the primary listener (in NodeInfo)
  393. func (n *Node) AddListener(l p2p.Listener) {
  394. n.sw.AddListener(l)
  395. }
  396. // ConfigureRPC sets all variables in rpccore so they will serve
  397. // rpc calls from this node
  398. func (n *Node) ConfigureRPC() {
  399. rpccore.SetStateDB(n.stateDB)
  400. rpccore.SetBlockStore(n.blockStore)
  401. rpccore.SetConsensusState(n.consensusState)
  402. rpccore.SetMempool(n.mempoolReactor.Mempool)
  403. rpccore.SetEvidencePool(n.evidencePool)
  404. rpccore.SetSwitch(n.sw)
  405. rpccore.SetPubKey(n.privValidator.GetPubKey())
  406. rpccore.SetGenesisDoc(n.genesisDoc)
  407. rpccore.SetAddrBook(n.addrBook)
  408. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  409. rpccore.SetTxIndexer(n.txIndexer)
  410. rpccore.SetConsensusReactor(n.consensusReactor)
  411. rpccore.SetEventBus(n.eventBus)
  412. rpccore.SetLogger(n.Logger.With("module", "rpc"))
  413. }
  414. func (n *Node) startRPC() ([]net.Listener, error) {
  415. n.ConfigureRPC()
  416. listenAddrs := strings.Split(n.config.RPC.ListenAddress, ",")
  417. if n.config.RPC.Unsafe {
  418. rpccore.AddUnsafeRoutes()
  419. }
  420. // we may expose the rpc over both a unix and tcp socket
  421. listeners := make([]net.Listener, len(listenAddrs))
  422. for i, listenAddr := range listenAddrs {
  423. mux := http.NewServeMux()
  424. rpcLogger := n.Logger.With("module", "rpc-server")
  425. wm := rpcserver.NewWebsocketManager(rpccore.Routes, rpcserver.EventSubscriber(n.eventBus))
  426. wm.SetLogger(rpcLogger.With("protocol", "websocket"))
  427. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  428. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  429. listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger)
  430. if err != nil {
  431. return nil, err
  432. }
  433. listeners[i] = listener
  434. }
  435. // we expose a simplified api over grpc for convenience to app devs
  436. grpcListenAddr := n.config.RPC.GRPCListenAddress
  437. if grpcListenAddr != "" {
  438. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  439. if err != nil {
  440. return nil, err
  441. }
  442. listeners = append(listeners, listener)
  443. }
  444. return listeners, nil
  445. }
  446. // Switch returns the Node's Switch.
  447. func (n *Node) Switch() *p2p.Switch {
  448. return n.sw
  449. }
  450. // BlockStore returns the Node's BlockStore.
  451. func (n *Node) BlockStore() *bc.BlockStore {
  452. return n.blockStore
  453. }
  454. // ConsensusState returns the Node's ConsensusState.
  455. func (n *Node) ConsensusState() *cs.ConsensusState {
  456. return n.consensusState
  457. }
  458. // ConsensusReactor returns the Node's ConsensusReactor.
  459. func (n *Node) ConsensusReactor() *cs.ConsensusReactor {
  460. return n.consensusReactor
  461. }
  462. // MempoolReactor returns the Node's MempoolReactor.
  463. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  464. return n.mempoolReactor
  465. }
  466. // EvidencePool returns the Node's EvidencePool.
  467. func (n *Node) EvidencePool() *evidence.EvidencePool {
  468. return n.evidencePool
  469. }
  470. // EventBus returns the Node's EventBus.
  471. func (n *Node) EventBus() *types.EventBus {
  472. return n.eventBus
  473. }
  474. // PrivValidator returns the Node's PrivValidator.
  475. // XXX: for convenience only!
  476. func (n *Node) PrivValidator() types.PrivValidator {
  477. return n.privValidator
  478. }
  479. // GenesisDoc returns the Node's GenesisDoc.
  480. func (n *Node) GenesisDoc() *types.GenesisDoc {
  481. return n.genesisDoc
  482. }
  483. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  484. func (n *Node) ProxyApp() proxy.AppConns {
  485. return n.proxyApp
  486. }
  487. func (n *Node) makeNodeInfo(pubKey crypto.PubKey) p2p.NodeInfo {
  488. txIndexerStatus := "on"
  489. if _, ok := n.txIndexer.(*null.TxIndex); ok {
  490. txIndexerStatus = "off"
  491. }
  492. nodeInfo := p2p.NodeInfo{
  493. PubKey: pubKey,
  494. Network: n.genesisDoc.ChainID,
  495. Version: version.Version,
  496. Channels: []byte{
  497. bc.BlockchainChannel,
  498. cs.StateChannel, cs.DataChannel, cs.VoteChannel, cs.VoteSetBitsChannel,
  499. mempl.MempoolChannel,
  500. evidence.EvidenceChannel,
  501. },
  502. Moniker: n.config.Moniker,
  503. Other: []string{
  504. cmn.Fmt("wire_version=%v", wire.Version),
  505. cmn.Fmt("p2p_version=%v", p2p.Version),
  506. cmn.Fmt("consensus_version=%v", cs.Version),
  507. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  508. cmn.Fmt("tx_index=%v", txIndexerStatus),
  509. },
  510. }
  511. if n.config.P2P.PexReactor {
  512. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  513. }
  514. rpcListenAddr := n.config.RPC.ListenAddress
  515. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  516. if !n.sw.IsListening() {
  517. return nodeInfo
  518. }
  519. p2pListener := n.sw.Listeners()[0]
  520. p2pHost := p2pListener.ExternalAddress().IP.String()
  521. p2pPort := p2pListener.ExternalAddress().Port
  522. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  523. return nodeInfo
  524. }
  525. //------------------------------------------------------------------------------
  526. // NodeInfo returns the Node's Info from the Switch.
  527. func (n *Node) NodeInfo() p2p.NodeInfo {
  528. return n.sw.NodeInfo()
  529. }
  530. //------------------------------------------------------------------------------
  531. var (
  532. genesisDocKey = []byte("genesisDoc")
  533. )
  534. // panics if failed to unmarshal bytes
  535. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  536. bytes := db.Get(genesisDocKey)
  537. if len(bytes) == 0 {
  538. return nil, errors.New("Genesis doc not found")
  539. } else {
  540. var genDoc *types.GenesisDoc
  541. err := json.Unmarshal(bytes, &genDoc)
  542. if err != nil {
  543. cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
  544. }
  545. return genDoc, nil
  546. }
  547. }
  548. // panics if failed to marshal the given genesis document
  549. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) {
  550. bytes, err := json.Marshal(genDoc)
  551. if err != nil {
  552. cmn.PanicCrisis(fmt.Sprintf("Failed to save genesis doc due to marshaling error: %v", err))
  553. }
  554. db.SetSync(genesisDocKey, bytes)
  555. }