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.

347 lines
9.7 KiB

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