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.

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