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.

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