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.

299 lines
8.6 KiB

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