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.

288 lines
8.3 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", 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], true) // so we dont start the consensus states
  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. // start the state machines
  73. byzR := reactors[0].(*ByzantineReactor)
  74. s := byzR.reactor.conS.GetState()
  75. byzR.reactor.SwitchToConsensus(s)
  76. for i := 1; i < N; i++ {
  77. cr := reactors[i].(*ConsensusReactor)
  78. cr.SwitchToConsensus(cr.conS.GetState())
  79. }
  80. // byz proposer sends one block to peers[0]
  81. // and the other block to peers[1] and peers[2].
  82. // note peers and switches order don't match.
  83. peers := switches[0].Peers().List()
  84. ind0 := getSwitchIndex(switches, peers[0])
  85. ind1 := getSwitchIndex(switches, peers[1])
  86. ind2 := getSwitchIndex(switches, peers[2])
  87. // connect the 2 peers in the larger partition
  88. p2p.Connect2Switches(switches, ind1, ind2)
  89. // wait for someone in the big partition to make a block
  90. select {
  91. case <-eventChans[ind2]:
  92. }
  93. log.Notice("A block has been committed. Healing partition")
  94. // connect the partitions
  95. p2p.Connect2Switches(switches, ind0, ind1)
  96. p2p.Connect2Switches(switches, ind0, ind2)
  97. // wait till everyone makes the first new block
  98. // (one of them already has)
  99. wg := new(sync.WaitGroup)
  100. wg.Add(2)
  101. for i := 1; i < N-1; i++ {
  102. go func(j int) {
  103. <-eventChans[j]
  104. wg.Done()
  105. }(i)
  106. }
  107. done := make(chan struct{})
  108. go func() {
  109. wg.Wait()
  110. close(done)
  111. }()
  112. tick := time.NewTicker(time.Second * 10)
  113. select {
  114. case <-done:
  115. case <-tick.C:
  116. for i, reactor := range reactors {
  117. t.Log(Fmt("Consensus Reactor %v", i))
  118. t.Log(Fmt("%v", reactor))
  119. }
  120. t.Fatalf("Timed out waiting for all validators to commit first block")
  121. }
  122. }
  123. //-------------------------------
  124. // byzantine consensus functions
  125. func byzantineDecideProposalFunc(height, round int, cs *ConsensusState, sw *p2p.Switch) {
  126. // byzantine user should create two proposals and try to split the vote.
  127. // Avoid sending on internalMsgQueue and running consensus state.
  128. // Create a new proposal block from state/txs from the mempool.
  129. block1, blockParts1 := cs.createProposalBlock()
  130. polRound, polBlockID := cs.Votes.POLInfo()
  131. proposal1 := types.NewProposal(height, round, blockParts1.Header(), polRound, polBlockID)
  132. cs.privValidator.SignProposal(cs.state.ChainID, proposal1) // byzantine doesnt err
  133. // Create a new proposal block from state/txs from the mempool.
  134. block2, blockParts2 := cs.createProposalBlock()
  135. polRound, polBlockID = cs.Votes.POLInfo()
  136. proposal2 := types.NewProposal(height, round, blockParts2.Header(), polRound, polBlockID)
  137. cs.privValidator.SignProposal(cs.state.ChainID, proposal2) // byzantine doesnt err
  138. block1Hash := block1.Hash()
  139. block2Hash := block2.Hash()
  140. // broadcast conflicting proposals/block parts to peers
  141. peers := sw.Peers().List()
  142. log.Notice("Byzantine: broadcasting conflicting proposals", "peers", len(peers))
  143. for i, peer := range peers {
  144. if i < len(peers)/2 {
  145. go sendProposalAndParts(height, round, cs, peer, proposal1, block1Hash, blockParts1)
  146. } else {
  147. go sendProposalAndParts(height, round, cs, peer, proposal2, block2Hash, blockParts2)
  148. }
  149. }
  150. }
  151. func sendProposalAndParts(height, round int, cs *ConsensusState, peer *p2p.Peer, proposal *types.Proposal, blockHash []byte, parts *types.PartSet) {
  152. // proposal
  153. msg := &ProposalMessage{Proposal: proposal}
  154. peer.Send(DataChannel, struct{ ConsensusMessage }{msg})
  155. // parts
  156. for i := 0; i < parts.Total(); i++ {
  157. part := parts.GetPart(i)
  158. msg := &BlockPartMessage{
  159. Height: height, // This tells peer that this part applies to us.
  160. Round: round, // This tells peer that this part applies to us.
  161. Part: part,
  162. }
  163. peer.Send(DataChannel, struct{ ConsensusMessage }{msg})
  164. }
  165. // votes
  166. cs.mtx.Lock()
  167. prevote, _ := cs.signVote(types.VoteTypePrevote, blockHash, parts.Header())
  168. precommit, _ := cs.signVote(types.VoteTypePrecommit, blockHash, parts.Header())
  169. cs.mtx.Unlock()
  170. peer.Send(VoteChannel, struct{ ConsensusMessage }{&VoteMessage{prevote}})
  171. peer.Send(VoteChannel, struct{ ConsensusMessage }{&VoteMessage{precommit}})
  172. }
  173. //----------------------------------------
  174. // byzantine consensus reactor
  175. type ByzantineReactor struct {
  176. Service
  177. reactor *ConsensusReactor
  178. }
  179. func NewByzantineReactor(conR *ConsensusReactor) *ByzantineReactor {
  180. return &ByzantineReactor{
  181. Service: conR,
  182. reactor: conR,
  183. }
  184. }
  185. func (br *ByzantineReactor) SetSwitch(s *p2p.Switch) { br.reactor.SetSwitch(s) }
  186. func (br *ByzantineReactor) GetChannels() []*p2p.ChannelDescriptor { return br.reactor.GetChannels() }
  187. func (br *ByzantineReactor) AddPeer(peer *p2p.Peer) {
  188. if !br.reactor.IsRunning() {
  189. return
  190. }
  191. // Create peerState for peer
  192. peerState := NewPeerState(peer)
  193. peer.Data.Set(types.PeerStateKey, peerState)
  194. // Send our state to peer.
  195. // If we're fast_syncing, broadcast a RoundStepMessage later upon SwitchToConsensus().
  196. if !br.reactor.fastSync {
  197. br.reactor.sendNewRoundStepMessage(peer)
  198. }
  199. }
  200. func (br *ByzantineReactor) RemovePeer(peer *p2p.Peer, reason interface{}) {
  201. br.reactor.RemovePeer(peer, reason)
  202. }
  203. func (br *ByzantineReactor) Receive(chID byte, peer *p2p.Peer, msgBytes []byte) {
  204. br.reactor.Receive(chID, peer, msgBytes)
  205. }
  206. //----------------------------------------
  207. // byzantine privValidator
  208. type ByzantinePrivValidator struct {
  209. Address []byte `json:"address"`
  210. types.Signer `json:"-"`
  211. mtx sync.Mutex
  212. }
  213. // Return a priv validator that will sign anything
  214. func NewByzantinePrivValidator(pv *types.PrivValidator) *ByzantinePrivValidator {
  215. return &ByzantinePrivValidator{
  216. Address: pv.Address,
  217. Signer: pv.Signer,
  218. }
  219. }
  220. func (privVal *ByzantinePrivValidator) GetAddress() []byte {
  221. return privVal.Address
  222. }
  223. func (privVal *ByzantinePrivValidator) SignVote(chainID string, vote *types.Vote) error {
  224. privVal.mtx.Lock()
  225. defer privVal.mtx.Unlock()
  226. // Sign
  227. vote.Signature = privVal.Sign(types.SignBytes(chainID, vote))
  228. return nil
  229. }
  230. func (privVal *ByzantinePrivValidator) SignProposal(chainID string, proposal *types.Proposal) error {
  231. privVal.mtx.Lock()
  232. defer privVal.mtx.Unlock()
  233. // Sign
  234. proposal.Signature = privVal.Sign(types.SignBytes(chainID, proposal))
  235. return nil
  236. }
  237. func (privVal *ByzantinePrivValidator) String() string {
  238. return Fmt("PrivValidator{%X}", privVal.Address)
  239. }