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.

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