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.

372 lines
11 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "math"
  5. "strings"
  6. "testing"
  7. "testing/quick"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. crypto "github.com/tendermint/tendermint/crypto"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. )
  13. func TestCopy(t *testing.T) {
  14. vset := randValidatorSet(10)
  15. vsetHash := vset.Hash()
  16. if len(vsetHash) == 0 {
  17. t.Fatalf("ValidatorSet had unexpected zero hash")
  18. }
  19. vsetCopy := vset.Copy()
  20. vsetCopyHash := vsetCopy.Hash()
  21. if !bytes.Equal(vsetHash, vsetCopyHash) {
  22. t.Fatalf("ValidatorSet copy had wrong hash. Orig: %X, Copy: %X", vsetHash, vsetCopyHash)
  23. }
  24. }
  25. func BenchmarkValidatorSetCopy(b *testing.B) {
  26. b.StopTimer()
  27. vset := NewValidatorSet([]*Validator{})
  28. for i := 0; i < 1000; i++ {
  29. privKey := crypto.GenPrivKeyEd25519()
  30. pubKey := privKey.PubKey()
  31. val := NewValidator(pubKey, 0)
  32. if !vset.Add(val) {
  33. panic("Failed to add validator")
  34. }
  35. }
  36. b.StartTimer()
  37. for i := 0; i < b.N; i++ {
  38. vset.Copy()
  39. }
  40. }
  41. //-------------------------------------------------------------------
  42. func TestProposerSelection1(t *testing.T) {
  43. vset := NewValidatorSet([]*Validator{
  44. newValidator([]byte("foo"), 1000),
  45. newValidator([]byte("bar"), 300),
  46. newValidator([]byte("baz"), 330),
  47. })
  48. proposers := []string{}
  49. for i := 0; i < 99; i++ {
  50. val := vset.GetProposer()
  51. proposers = append(proposers, string(val.Address))
  52. vset.IncrementAccum(1)
  53. }
  54. expected := `foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar foo baz foo foo bar foo baz foo foo bar foo baz foo foo foo baz bar foo foo foo baz foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar foo baz foo foo bar foo baz foo foo`
  55. if expected != strings.Join(proposers, " ") {
  56. t.Errorf("Expected sequence of proposers was\n%v\nbut got \n%v", expected, strings.Join(proposers, " "))
  57. }
  58. }
  59. func TestProposerSelection2(t *testing.T) {
  60. addr0 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
  61. addr1 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
  62. addr2 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
  63. // when all voting power is same, we go in order of addresses
  64. val0, val1, val2 := newValidator(addr0, 100), newValidator(addr1, 100), newValidator(addr2, 100)
  65. valList := []*Validator{val0, val1, val2}
  66. vals := NewValidatorSet(valList)
  67. for i := 0; i < len(valList)*5; i++ {
  68. ii := (i) % len(valList)
  69. prop := vals.GetProposer()
  70. if !bytes.Equal(prop.Address, valList[ii].Address) {
  71. t.Fatalf("(%d): Expected %X. Got %X", i, valList[ii].Address, prop.Address)
  72. }
  73. vals.IncrementAccum(1)
  74. }
  75. // One validator has more than the others, but not enough to propose twice in a row
  76. *val2 = *newValidator(addr2, 400)
  77. vals = NewValidatorSet(valList)
  78. // vals.IncrementAccum(1)
  79. prop := vals.GetProposer()
  80. if !bytes.Equal(prop.Address, addr2) {
  81. t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address)
  82. }
  83. vals.IncrementAccum(1)
  84. prop = vals.GetProposer()
  85. if !bytes.Equal(prop.Address, addr0) {
  86. t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address)
  87. }
  88. // One validator has more than the others, and enough to be proposer twice in a row
  89. *val2 = *newValidator(addr2, 401)
  90. vals = NewValidatorSet(valList)
  91. prop = vals.GetProposer()
  92. if !bytes.Equal(prop.Address, addr2) {
  93. t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address)
  94. }
  95. vals.IncrementAccum(1)
  96. prop = vals.GetProposer()
  97. if !bytes.Equal(prop.Address, addr2) {
  98. t.Fatalf("Expected address with highest voting power to be second proposer. Got %X", prop.Address)
  99. }
  100. vals.IncrementAccum(1)
  101. prop = vals.GetProposer()
  102. if !bytes.Equal(prop.Address, addr0) {
  103. t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address)
  104. }
  105. // each validator should be the proposer a proportional number of times
  106. val0, val1, val2 = newValidator(addr0, 4), newValidator(addr1, 5), newValidator(addr2, 3)
  107. valList = []*Validator{val0, val1, val2}
  108. propCount := make([]int, 3)
  109. vals = NewValidatorSet(valList)
  110. N := 1
  111. for i := 0; i < 120*N; i++ {
  112. prop := vals.GetProposer()
  113. ii := prop.Address[19]
  114. propCount[ii]++
  115. vals.IncrementAccum(1)
  116. }
  117. if propCount[0] != 40*N {
  118. t.Fatalf("Expected prop count for validator with 4/12 of voting power to be %d/%d. Got %d/%d", 40*N, 120*N, propCount[0], 120*N)
  119. }
  120. if propCount[1] != 50*N {
  121. t.Fatalf("Expected prop count for validator with 5/12 of voting power to be %d/%d. Got %d/%d", 50*N, 120*N, propCount[1], 120*N)
  122. }
  123. if propCount[2] != 30*N {
  124. t.Fatalf("Expected prop count for validator with 3/12 of voting power to be %d/%d. Got %d/%d", 30*N, 120*N, propCount[2], 120*N)
  125. }
  126. }
  127. func TestProposerSelection3(t *testing.T) {
  128. vset := NewValidatorSet([]*Validator{
  129. newValidator([]byte("a"), 1),
  130. newValidator([]byte("b"), 1),
  131. newValidator([]byte("c"), 1),
  132. newValidator([]byte("d"), 1),
  133. })
  134. proposerOrder := make([]*Validator, 4)
  135. for i := 0; i < 4; i++ {
  136. proposerOrder[i] = vset.GetProposer()
  137. vset.IncrementAccum(1)
  138. }
  139. // i for the loop
  140. // j for the times
  141. // we should go in order for ever, despite some IncrementAccums with times > 1
  142. var i, j int
  143. for ; i < 10000; i++ {
  144. got := vset.GetProposer().Address
  145. expected := proposerOrder[j%4].Address
  146. if !bytes.Equal(got, expected) {
  147. t.Fatalf(cmn.Fmt("vset.Proposer (%X) does not match expected proposer (%X) for (%d, %d)", got, expected, i, j))
  148. }
  149. // serialize, deserialize, check proposer
  150. b := vset.toBytes()
  151. vset.fromBytes(b)
  152. computed := vset.GetProposer() // findGetProposer()
  153. if i != 0 {
  154. if !bytes.Equal(got, computed.Address) {
  155. t.Fatalf(cmn.Fmt("vset.Proposer (%X) does not match computed proposer (%X) for (%d, %d)", got, computed.Address, i, j))
  156. }
  157. }
  158. // times is usually 1
  159. times := 1
  160. mod := (cmn.RandInt() % 5) + 1
  161. if cmn.RandInt()%mod > 0 {
  162. // sometimes its up to 5
  163. times = cmn.RandInt() % 5
  164. }
  165. vset.IncrementAccum(times)
  166. j += times
  167. }
  168. }
  169. func newValidator(address []byte, power int64) *Validator {
  170. return &Validator{Address: address, VotingPower: power}
  171. }
  172. func randPubKey() crypto.PubKey {
  173. var pubKey [32]byte
  174. copy(pubKey[:], cmn.RandBytes(32))
  175. return crypto.PubKeyEd25519(pubKey)
  176. }
  177. func randValidator_() *Validator {
  178. val := NewValidator(randPubKey(), cmn.RandInt64())
  179. val.Accum = cmn.RandInt64()
  180. return val
  181. }
  182. func randValidatorSet(numValidators int) *ValidatorSet {
  183. validators := make([]*Validator, numValidators)
  184. for i := 0; i < numValidators; i++ {
  185. validators[i] = randValidator_()
  186. }
  187. return NewValidatorSet(validators)
  188. }
  189. func (valSet *ValidatorSet) toBytes() []byte {
  190. bz, err := cdc.MarshalBinary(valSet)
  191. if err != nil {
  192. panic(err)
  193. }
  194. return bz
  195. }
  196. func (valSet *ValidatorSet) fromBytes(b []byte) {
  197. err := cdc.UnmarshalBinary(b, &valSet)
  198. if err != nil {
  199. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  200. panic(err)
  201. }
  202. }
  203. //-------------------------------------------------------------------
  204. func TestValidatorSetTotalVotingPowerOverflows(t *testing.T) {
  205. vset := NewValidatorSet([]*Validator{
  206. {Address: []byte("a"), VotingPower: math.MaxInt64, Accum: 0},
  207. {Address: []byte("b"), VotingPower: math.MaxInt64, Accum: 0},
  208. {Address: []byte("c"), VotingPower: math.MaxInt64, Accum: 0},
  209. })
  210. assert.EqualValues(t, math.MaxInt64, vset.TotalVotingPower())
  211. }
  212. func TestValidatorSetIncrementAccumOverflows(t *testing.T) {
  213. // NewValidatorSet calls IncrementAccum(1)
  214. vset := NewValidatorSet([]*Validator{
  215. // too much voting power
  216. 0: {Address: []byte("a"), VotingPower: math.MaxInt64, Accum: 0},
  217. // too big accum
  218. 1: {Address: []byte("b"), VotingPower: 10, Accum: math.MaxInt64},
  219. // almost too big accum
  220. 2: {Address: []byte("c"), VotingPower: 10, Accum: math.MaxInt64 - 5},
  221. })
  222. assert.Equal(t, int64(0), vset.Validators[0].Accum, "0") // because we decrement val with most voting power
  223. assert.EqualValues(t, math.MaxInt64, vset.Validators[1].Accum, "1")
  224. assert.EqualValues(t, math.MaxInt64, vset.Validators[2].Accum, "2")
  225. }
  226. func TestValidatorSetIncrementAccumUnderflows(t *testing.T) {
  227. // NewValidatorSet calls IncrementAccum(1)
  228. vset := NewValidatorSet([]*Validator{
  229. 0: {Address: []byte("a"), VotingPower: math.MaxInt64, Accum: math.MinInt64},
  230. 1: {Address: []byte("b"), VotingPower: 1, Accum: math.MinInt64},
  231. })
  232. vset.IncrementAccum(5)
  233. assert.EqualValues(t, math.MinInt64, vset.Validators[0].Accum, "0")
  234. assert.EqualValues(t, math.MinInt64, vset.Validators[1].Accum, "1")
  235. }
  236. func TestSafeMul(t *testing.T) {
  237. f := func(a, b int64) bool {
  238. c, overflow := safeMul(a, b)
  239. return overflow || (!overflow && c == a*b)
  240. }
  241. if err := quick.Check(f, nil); err != nil {
  242. t.Error(err)
  243. }
  244. }
  245. func TestSafeAdd(t *testing.T) {
  246. f := func(a, b int64) bool {
  247. c, overflow := safeAdd(a, b)
  248. return overflow || (!overflow && c == a+b)
  249. }
  250. if err := quick.Check(f, nil); err != nil {
  251. t.Error(err)
  252. }
  253. }
  254. func TestSafeMulClip(t *testing.T) {
  255. assert.EqualValues(t, math.MaxInt64, safeMulClip(math.MinInt64, math.MinInt64))
  256. assert.EqualValues(t, math.MinInt64, safeMulClip(math.MaxInt64, math.MinInt64))
  257. assert.EqualValues(t, math.MinInt64, safeMulClip(math.MinInt64, math.MaxInt64))
  258. assert.EqualValues(t, math.MaxInt64, safeMulClip(math.MaxInt64, 2))
  259. }
  260. func TestSafeAddClip(t *testing.T) {
  261. assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, 10))
  262. assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, math.MaxInt64))
  263. assert.EqualValues(t, math.MinInt64, safeAddClip(math.MinInt64, -10))
  264. }
  265. func TestSafeSubClip(t *testing.T) {
  266. assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, 10))
  267. assert.EqualValues(t, 0, safeSubClip(math.MinInt64, math.MinInt64))
  268. assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, math.MaxInt64))
  269. assert.EqualValues(t, math.MaxInt64, safeSubClip(math.MaxInt64, -10))
  270. }
  271. //-------------------------------------------------------------------
  272. func TestValidatorSetVerifyCommit(t *testing.T) {
  273. privKey := crypto.GenPrivKeyEd25519()
  274. pubKey := privKey.PubKey()
  275. v1 := NewValidator(pubKey, 1000)
  276. vset := NewValidatorSet([]*Validator{v1})
  277. chainID := "mychainID"
  278. blockID := BlockID{Hash: []byte("hello")}
  279. height := int64(5)
  280. vote := &Vote{
  281. ValidatorAddress: v1.Address,
  282. ValidatorIndex: 0,
  283. Height: height,
  284. Round: 0,
  285. Timestamp: time.Now().UTC(),
  286. Type: VoteTypePrecommit,
  287. BlockID: blockID,
  288. }
  289. sig, err := privKey.Sign(vote.SignBytes(chainID))
  290. assert.NoError(t, err)
  291. vote.Signature = sig
  292. commit := &Commit{
  293. BlockID: blockID,
  294. Precommits: []*Vote{vote},
  295. }
  296. badChainID := "notmychainID"
  297. badBlockID := BlockID{Hash: []byte("goodbye")}
  298. badHeight := height + 1
  299. badCommit := &Commit{
  300. BlockID: blockID,
  301. Precommits: []*Vote{nil},
  302. }
  303. // test some error cases
  304. // TODO: test more cases!
  305. cases := []struct {
  306. chainID string
  307. blockID BlockID
  308. height int64
  309. commit *Commit
  310. }{
  311. {badChainID, blockID, height, commit},
  312. {chainID, badBlockID, height, commit},
  313. {chainID, blockID, badHeight, commit},
  314. {chainID, blockID, height, badCommit},
  315. }
  316. for i, c := range cases {
  317. err := vset.VerifyCommit(c.chainID, c.blockID, c.height, c.commit)
  318. assert.NotNil(t, err, i)
  319. }
  320. // test a good one
  321. err = vset.VerifyCommit(chainID, blockID, height, commit)
  322. assert.Nil(t, err)
  323. }