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.

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