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.

279 lines
8.0 KiB

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