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.

307 lines
9.0 KiB

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
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
7 years ago
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
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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package consensus
  2. import (
  3. "context"
  4. "sync"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/require"
  8. crypto "github.com/tendermint/go-crypto"
  9. data "github.com/tendermint/go-wire/data"
  10. "github.com/tendermint/tendermint/p2p"
  11. "github.com/tendermint/tendermint/types"
  12. cmn "github.com/tendermint/tmlibs/common"
  13. )
  14. func init() {
  15. config = ResetConfig("consensus_byzantine_test")
  16. }
  17. //----------------------------------------------
  18. // byzantine failures
  19. // 4 validators. 1 is byzantine. The other three are partitioned into A (1 val) and B (2 vals).
  20. // byzantine validator sends conflicting proposals into A and B,
  21. // and prevotes/precommits on both of them.
  22. // B sees a commit, A doesn't.
  23. // Byzantine validator refuses to prevote.
  24. // Heal partition and ensure A sees the commit
  25. func TestByzantine(t *testing.T) {
  26. N := 4
  27. logger := consensusLogger()
  28. css := randConsensusNet(N, "consensus_byzantine_test", newMockTickerFunc(false), newCounter)
  29. // give the byzantine validator a normal ticker
  30. css[0].SetTimeoutTicker(NewTimeoutTicker())
  31. switches := make([]*p2p.Switch, N)
  32. p2pLogger := logger.With("module", "p2p")
  33. for i := 0; i < N; i++ {
  34. switches[i] = p2p.NewSwitch(config.P2P)
  35. switches[i].SetLogger(p2pLogger.With("validator", i))
  36. }
  37. eventChans := make([]chan interface{}, N)
  38. reactors := make([]p2p.Reactor, N)
  39. for i := 0; i < N; i++ {
  40. if i == 0 {
  41. css[i].privValidator = NewByzantinePrivValidator(css[i].privValidator)
  42. // make byzantine
  43. css[i].decideProposal = func(j int) func(int, int) {
  44. return func(height, round int) {
  45. byzantineDecideProposalFunc(t, height, round, css[j], switches[j])
  46. }
  47. }(i)
  48. css[i].doPrevote = func(height, round int) {}
  49. }
  50. eventBus := types.NewEventBus()
  51. eventBus.SetLogger(logger.With("module", "events", "validator", i))
  52. _, err := eventBus.Start()
  53. require.NoError(t, err)
  54. defer eventBus.Stop()
  55. eventChans[i] = make(chan interface{}, 1)
  56. err = eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock, eventChans[i])
  57. require.NoError(t, err)
  58. conR := NewConsensusReactor(css[i], true) // so we dont start the consensus states
  59. conR.SetLogger(logger.With("validator", i))
  60. conR.SetEventBus(eventBus)
  61. var conRI p2p.Reactor
  62. conRI = conR
  63. if i == 0 {
  64. conRI = NewByzantineReactor(conR)
  65. }
  66. reactors[i] = conRI
  67. }
  68. defer func() {
  69. for _, r := range reactors {
  70. if rr, ok := r.(*ByzantineReactor); ok {
  71. rr.reactor.Switch.Stop()
  72. } else {
  73. r.(*ConsensusReactor).Switch.Stop()
  74. }
  75. }
  76. }()
  77. p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch {
  78. // ignore new switch s, we already made ours
  79. switches[i].AddReactor("CONSENSUS", reactors[i])
  80. return switches[i]
  81. }, func(sws []*p2p.Switch, i, j int) {
  82. // the network starts partitioned with globally active adversary
  83. if i != 0 {
  84. return
  85. }
  86. p2p.Connect2Switches(sws, i, j)
  87. })
  88. // start the state machines
  89. byzR := reactors[0].(*ByzantineReactor)
  90. s := byzR.reactor.conS.GetState()
  91. byzR.reactor.SwitchToConsensus(s, 0)
  92. for i := 1; i < N; i++ {
  93. cr := reactors[i].(*ConsensusReactor)
  94. cr.SwitchToConsensus(cr.conS.GetState(), 0)
  95. }
  96. // byz proposer sends one block to peers[0]
  97. // and the other block to peers[1] and peers[2].
  98. // note peers and switches order don't match.
  99. peers := switches[0].Peers().List()
  100. ind0 := getSwitchIndex(switches, peers[0])
  101. ind1 := getSwitchIndex(switches, peers[1])
  102. ind2 := getSwitchIndex(switches, peers[2])
  103. // connect the 2 peers in the larger partition
  104. p2p.Connect2Switches(switches, ind1, ind2)
  105. // wait for someone in the big partition to make a block
  106. <-eventChans[ind2]
  107. t.Log("A block has been committed. Healing partition")
  108. // connect the partitions
  109. p2p.Connect2Switches(switches, ind0, ind1)
  110. p2p.Connect2Switches(switches, ind0, ind2)
  111. // wait till everyone makes the first new block
  112. // (one of them already has)
  113. wg := new(sync.WaitGroup)
  114. wg.Add(2)
  115. for i := 1; i < N-1; i++ {
  116. go func(j int) {
  117. <-eventChans[j]
  118. wg.Done()
  119. }(i)
  120. }
  121. done := make(chan struct{})
  122. go func() {
  123. wg.Wait()
  124. close(done)
  125. }()
  126. tick := time.NewTicker(time.Second * 10)
  127. select {
  128. case <-done:
  129. case <-tick.C:
  130. for i, reactor := range reactors {
  131. t.Log(cmn.Fmt("Consensus Reactor %v", i))
  132. t.Log(cmn.Fmt("%v", reactor))
  133. }
  134. t.Fatalf("Timed out waiting for all validators to commit first block")
  135. }
  136. }
  137. //-------------------------------
  138. // byzantine consensus functions
  139. func byzantineDecideProposalFunc(t *testing.T, height, round int, cs *ConsensusState, sw *p2p.Switch) {
  140. // byzantine user should create two proposals and try to split the vote.
  141. // Avoid sending on internalMsgQueue and running consensus state.
  142. // Create a new proposal block from state/txs from the mempool.
  143. block1, blockParts1 := cs.createProposalBlock()
  144. polRound, polBlockID := cs.Votes.POLInfo()
  145. proposal1 := types.NewProposal(height, round, blockParts1.Header(), polRound, polBlockID)
  146. if err := cs.privValidator.SignProposal(cs.state.ChainID, proposal1); err != nil {
  147. t.Error(err)
  148. }
  149. // Create a new proposal block from state/txs from the mempool.
  150. block2, blockParts2 := cs.createProposalBlock()
  151. polRound, polBlockID = cs.Votes.POLInfo()
  152. proposal2 := types.NewProposal(height, round, blockParts2.Header(), polRound, polBlockID)
  153. if err := cs.privValidator.SignProposal(cs.state.ChainID, proposal2); err != nil {
  154. t.Error(err)
  155. }
  156. block1Hash := block1.Hash()
  157. block2Hash := block2.Hash()
  158. // broadcast conflicting proposals/block parts to peers
  159. peers := sw.Peers().List()
  160. t.Logf("Byzantine: broadcasting conflicting proposals to %d peers", len(peers))
  161. for i, peer := range peers {
  162. if i < len(peers)/2 {
  163. go sendProposalAndParts(height, round, cs, peer, proposal1, block1Hash, blockParts1)
  164. } else {
  165. go sendProposalAndParts(height, round, cs, peer, proposal2, block2Hash, blockParts2)
  166. }
  167. }
  168. }
  169. func sendProposalAndParts(height, round int, cs *ConsensusState, peer p2p.Peer, proposal *types.Proposal, blockHash []byte, parts *types.PartSet) {
  170. // proposal
  171. msg := &ProposalMessage{Proposal: proposal}
  172. peer.Send(DataChannel, struct{ ConsensusMessage }{msg})
  173. // parts
  174. for i := 0; i < parts.Total(); i++ {
  175. part := parts.GetPart(i)
  176. msg := &BlockPartMessage{
  177. Height: height, // This tells peer that this part applies to us.
  178. Round: round, // This tells peer that this part applies to us.
  179. Part: part,
  180. }
  181. peer.Send(DataChannel, struct{ ConsensusMessage }{msg})
  182. }
  183. // votes
  184. cs.mtx.Lock()
  185. prevote, _ := cs.signVote(types.VoteTypePrevote, blockHash, parts.Header())
  186. precommit, _ := cs.signVote(types.VoteTypePrecommit, blockHash, parts.Header())
  187. cs.mtx.Unlock()
  188. peer.Send(VoteChannel, struct{ ConsensusMessage }{&VoteMessage{prevote}})
  189. peer.Send(VoteChannel, struct{ ConsensusMessage }{&VoteMessage{precommit}})
  190. }
  191. //----------------------------------------
  192. // byzantine consensus reactor
  193. type ByzantineReactor struct {
  194. cmn.Service
  195. reactor *ConsensusReactor
  196. }
  197. func NewByzantineReactor(conR *ConsensusReactor) *ByzantineReactor {
  198. return &ByzantineReactor{
  199. Service: conR,
  200. reactor: conR,
  201. }
  202. }
  203. func (br *ByzantineReactor) SetSwitch(s *p2p.Switch) { br.reactor.SetSwitch(s) }
  204. func (br *ByzantineReactor) GetChannels() []*p2p.ChannelDescriptor { return br.reactor.GetChannels() }
  205. func (br *ByzantineReactor) AddPeer(peer p2p.Peer) {
  206. if !br.reactor.IsRunning() {
  207. return
  208. }
  209. // Create peerState for peer
  210. peerState := NewPeerState(peer).SetLogger(br.reactor.Logger)
  211. peer.Set(types.PeerStateKey, peerState)
  212. // Send our state to peer.
  213. // If we're fast_syncing, broadcast a RoundStepMessage later upon SwitchToConsensus().
  214. if !br.reactor.fastSync {
  215. br.reactor.sendNewRoundStepMessages(peer)
  216. }
  217. }
  218. func (br *ByzantineReactor) RemovePeer(peer p2p.Peer, reason interface{}) {
  219. br.reactor.RemovePeer(peer, reason)
  220. }
  221. func (br *ByzantineReactor) Receive(chID byte, peer p2p.Peer, msgBytes []byte) {
  222. br.reactor.Receive(chID, peer, msgBytes)
  223. }
  224. //----------------------------------------
  225. // byzantine privValidator
  226. type ByzantinePrivValidator struct {
  227. types.Signer
  228. pv types.PrivValidator
  229. }
  230. // Return a priv validator that will sign anything
  231. func NewByzantinePrivValidator(pv types.PrivValidator) *ByzantinePrivValidator {
  232. return &ByzantinePrivValidator{
  233. Signer: pv.(*types.PrivValidatorFS).Signer,
  234. pv: pv,
  235. }
  236. }
  237. func (privVal *ByzantinePrivValidator) GetAddress() data.Bytes {
  238. return privVal.pv.GetAddress()
  239. }
  240. func (privVal *ByzantinePrivValidator) GetPubKey() crypto.PubKey {
  241. return privVal.pv.GetPubKey()
  242. }
  243. func (privVal *ByzantinePrivValidator) SignVote(chainID string, vote *types.Vote) (err error) {
  244. vote.Signature, err = privVal.Sign(types.SignBytes(chainID, vote))
  245. return err
  246. }
  247. func (privVal *ByzantinePrivValidator) SignProposal(chainID string, proposal *types.Proposal) (err error) {
  248. proposal.Signature, err = privVal.Sign(types.SignBytes(chainID, proposal))
  249. return nil
  250. }
  251. func (privVal *ByzantinePrivValidator) SignHeartbeat(chainID string, heartbeat *types.Heartbeat) (err error) {
  252. heartbeat.Signature, err = privVal.Sign(types.SignBytes(chainID, heartbeat))
  253. return nil
  254. }
  255. func (privVal *ByzantinePrivValidator) String() string {
  256. return cmn.Fmt("PrivValidator{%X}", privVal.GetAddress())
  257. }