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.

294 lines
8.4 KiB

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