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.

100 lines
2.5 KiB

  1. package consensus
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. "github.com/tendermint/tendermint/libs/log"
  6. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  7. "github.com/tendermint/tendermint/types"
  8. )
  9. func peerStateSetup(h, r, v int) *PeerState {
  10. ps := NewPeerState(log.TestingLogger(), "testPeerState")
  11. ps.PRS.Height = int64(h)
  12. ps.PRS.Round = int32(r)
  13. ps.ensureVoteBitArrays(int64(h), v)
  14. return ps
  15. }
  16. func TestSetHasVote(t *testing.T) {
  17. ps := peerStateSetup(1, 1, 1)
  18. pva := ps.PRS.Prevotes.Copy()
  19. // nil vote should return ErrPeerStateNilVote
  20. err := ps.SetHasVote(nil)
  21. require.Equal(t, ErrPeerStateSetNilVote, err)
  22. // the peer giving an invalid index should returns ErrPeerStateInvalidVoteIndex
  23. v0 := &types.Vote{
  24. Height: 1,
  25. ValidatorIndex: -1,
  26. Round: 1,
  27. Type: tmproto.PrevoteType,
  28. }
  29. err = ps.SetHasVote(v0)
  30. require.Equal(t, ErrPeerStateInvalidVoteIndex, err)
  31. // the peer giving an invalid index should returns ErrPeerStateInvalidVoteIndex
  32. v1 := &types.Vote{
  33. Height: 1,
  34. ValidatorIndex: 1,
  35. Round: 1,
  36. Type: tmproto.PrevoteType,
  37. }
  38. err = ps.SetHasVote(v1)
  39. require.Equal(t, ErrPeerStateInvalidVoteIndex, err)
  40. // the peer giving a correct index should return nil (vote has been set)
  41. v2 := &types.Vote{
  42. Height: 1,
  43. ValidatorIndex: 0,
  44. Round: 1,
  45. Type: tmproto.PrevoteType,
  46. }
  47. require.Nil(t, ps.SetHasVote(v2))
  48. // verify vote
  49. pva.SetIndex(0, true)
  50. require.Equal(t, pva, ps.getVoteBitArray(1, 1, tmproto.PrevoteType))
  51. // the vote is not in the correct height/round/voteType should return nil (ignore the vote)
  52. v3 := &types.Vote{
  53. Height: 2,
  54. ValidatorIndex: 0,
  55. Round: 1,
  56. Type: tmproto.PrevoteType,
  57. }
  58. require.Nil(t, ps.SetHasVote(v3))
  59. // prevote bitarray has no update
  60. require.Equal(t, pva, ps.getVoteBitArray(1, 1, tmproto.PrevoteType))
  61. }
  62. func TestApplyHasVoteMessage(t *testing.T) {
  63. ps := peerStateSetup(1, 1, 1)
  64. pva := ps.PRS.Prevotes.Copy()
  65. // ignore the message with an invalid height
  66. msg := &HasVoteMessage{
  67. Height: 2,
  68. }
  69. require.Nil(t, ps.ApplyHasVoteMessage(msg))
  70. // apply a message like v2 in TestSetHasVote
  71. msg2 := &HasVoteMessage{
  72. Height: 1,
  73. Index: 0,
  74. Round: 1,
  75. Type: tmproto.PrevoteType,
  76. }
  77. require.Nil(t, ps.ApplyHasVoteMessage(msg2))
  78. // verify vote
  79. pva.SetIndex(0, true)
  80. require.Equal(t, pva, ps.getVoteBitArray(1, 1, tmproto.PrevoteType))
  81. // skip test cases like v & v3 in TestSetHasVote due to the same path
  82. }