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.

371 lines
11 KiB

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