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.

286 lines
8.3 KiB

8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "fmt"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. abci "github.com/tendermint/abci/types"
  8. crypto "github.com/tendermint/go-crypto"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. dbm "github.com/tendermint/tmlibs/db"
  11. "github.com/tendermint/tmlibs/log"
  12. cfg "github.com/tendermint/tendermint/config"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. // setupTestCase does setup common to all test cases
  16. func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, *State) {
  17. config := cfg.ResetTestRoot("state_")
  18. stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir())
  19. state, err := GetState(stateDB, config.GenesisFile())
  20. assert.NoError(t, err, "expected no error on GetState")
  21. state.SetLogger(log.TestingLogger())
  22. tearDown := func(t *testing.T) {}
  23. return tearDown, stateDB, state
  24. }
  25. // TestStateCopy tests the correct copying behaviour of State.
  26. func TestStateCopy(t *testing.T) {
  27. tearDown, _, state := setupTestCase(t)
  28. defer tearDown(t)
  29. // nolint: vetshadow
  30. assert := assert.New(t)
  31. stateCopy := state.Copy()
  32. assert.True(state.Equals(stateCopy),
  33. cmn.Fmt(`expected state and its copy to be identical. got %v\n expected %v\n`,
  34. stateCopy, state))
  35. stateCopy.LastBlockHeight++
  36. assert.False(state.Equals(stateCopy), cmn.Fmt(`expected states to be different. got same
  37. %v`, state))
  38. }
  39. // TestStateSaveLoad tests saving and loading State from a db.
  40. func TestStateSaveLoad(t *testing.T) {
  41. tearDown, stateDB, state := setupTestCase(t)
  42. defer tearDown(t)
  43. // nolint: vetshadow
  44. assert := assert.New(t)
  45. state.LastBlockHeight++
  46. state.Save()
  47. loadedState := LoadState(stateDB)
  48. assert.True(state.Equals(loadedState),
  49. cmn.Fmt(`expected state and its copy to be identical. got %v\n expected %v\n`,
  50. loadedState, state))
  51. }
  52. // TestABCIResponsesSaveLoad tests saving and loading ABCIResponses.
  53. func TestABCIResponsesSaveLoad(t *testing.T) {
  54. tearDown, _, state := setupTestCase(t)
  55. defer tearDown(t)
  56. // nolint: vetshadow
  57. assert := assert.New(t)
  58. state.LastBlockHeight++
  59. // build mock responses
  60. block := makeBlock(2, state)
  61. abciResponses := NewABCIResponses(block)
  62. abciResponses.DeliverTx[0] = &abci.ResponseDeliverTx{Data: []byte("foo"), Tags: []*abci.KVPair{}}
  63. abciResponses.DeliverTx[1] = &abci.ResponseDeliverTx{Data: []byte("bar"), Log: "ok", Tags: []*abci.KVPair{}}
  64. abciResponses.EndBlock = &abci.ResponseEndBlock{ValidatorUpdates: []*abci.Validator{
  65. {
  66. PubKey: crypto.GenPrivKeyEd25519().PubKey().Bytes(),
  67. Power: 10,
  68. },
  69. }}
  70. abciResponses.txs = nil
  71. state.SaveABCIResponses(abciResponses)
  72. loadedAbciResponses := state.LoadABCIResponses()
  73. assert.Equal(abciResponses, loadedAbciResponses,
  74. cmn.Fmt(`ABCIResponses don't match: Got %v, Expected %v`, loadedAbciResponses,
  75. abciResponses))
  76. }
  77. // TestValidatorSimpleSaveLoad tests saving and loading validators.
  78. func TestValidatorSimpleSaveLoad(t *testing.T) {
  79. tearDown, _, state := setupTestCase(t)
  80. defer tearDown(t)
  81. // nolint: vetshadow
  82. assert := assert.New(t)
  83. // can't load anything for height 0
  84. v, err := state.LoadValidators(0)
  85. assert.IsType(ErrNoValSetForHeight{}, err, "expected err at height 0")
  86. // should be able to load for height 1
  87. v, err = state.LoadValidators(1)
  88. assert.Nil(err, "expected no err at height 1")
  89. assert.Equal(v.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  90. // increment height, save; should be able to load for next height
  91. state.LastBlockHeight++
  92. state.saveValidatorsInfo()
  93. v, err = state.LoadValidators(state.LastBlockHeight + 1)
  94. assert.Nil(err, "expected no err")
  95. assert.Equal(v.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  96. // increment height, save; should be able to load for next height
  97. state.LastBlockHeight += 10
  98. state.saveValidatorsInfo()
  99. v, err = state.LoadValidators(state.LastBlockHeight + 1)
  100. assert.Nil(err, "expected no err")
  101. assert.Equal(v.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  102. // should be able to load for next next height
  103. _, err = state.LoadValidators(state.LastBlockHeight + 2)
  104. assert.IsType(ErrNoValSetForHeight{}, err, "expected err at unknown height")
  105. }
  106. // TestValidatorChangesSaveLoad tests saving and loading a validator set with changes.
  107. func TestValidatorChangesSaveLoad(t *testing.T) {
  108. tearDown, _, state := setupTestCase(t)
  109. defer tearDown(t)
  110. // nolint: vetshadow
  111. assert := assert.New(t)
  112. // change vals at these heights
  113. changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20}
  114. N := len(changeHeights)
  115. // each valset is just one validator.
  116. // create list of them
  117. pubkeys := make([]crypto.PubKey, N+1)
  118. _, val := state.Validators.GetByIndex(0)
  119. pubkeys[0] = val.PubKey
  120. for i := 1; i < N+1; i++ {
  121. pubkeys[i] = crypto.GenPrivKeyEd25519().PubKey()
  122. }
  123. // build the validator history by running SetBlockAndValidators
  124. // with the right validator set for each height
  125. highestHeight := changeHeights[N-1] + 5
  126. changeIndex := 0
  127. pubkey := pubkeys[changeIndex]
  128. for i := int64(1); i < highestHeight; i++ {
  129. // when we get to a change height,
  130. // use the next pubkey
  131. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
  132. changeIndex++
  133. pubkey = pubkeys[changeIndex]
  134. }
  135. header, parts, responses := makeHeaderPartsResponses(state, i, pubkey)
  136. state.SetBlockAndValidators(header, parts, responses)
  137. state.saveValidatorsInfo()
  138. }
  139. // make all the test cases by using the same validator until after the change
  140. testCases := make([]valChangeTestCase, highestHeight)
  141. changeIndex = 0
  142. pubkey = pubkeys[changeIndex]
  143. for i := int64(1); i < highestHeight+1; i++ {
  144. // we we get to the height after a change height
  145. // use the next pubkey (note our counter starts at 0 this time)
  146. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
  147. changeIndex++
  148. pubkey = pubkeys[changeIndex]
  149. }
  150. testCases[i-1] = valChangeTestCase{i, pubkey}
  151. }
  152. for _, testCase := range testCases {
  153. v, err := state.LoadValidators(testCase.height)
  154. assert.Nil(err, fmt.Sprintf("expected no err at height %d", testCase.height))
  155. assert.Equal(v.Size(), 1, "validator set size is greater than 1: %d", v.Size())
  156. addr, _ := v.GetByIndex(0)
  157. assert.Equal(addr, testCase.vals.Address(), fmt.Sprintf(`unexpected pubkey at
  158. height %d`, testCase.height))
  159. }
  160. }
  161. func makeParams(blockBytes, blockTx, blockGas, txBytes,
  162. txGas, partSize int) types.ConsensusParams {
  163. return types.ConsensusParams{
  164. BlockSize: types.BlockSize{
  165. MaxBytes: blockBytes,
  166. MaxTxs: blockTx,
  167. MaxGas: blockGas,
  168. },
  169. TxSize: types.TxSize{
  170. MaxBytes: txBytes,
  171. MaxGas: txGas,
  172. },
  173. BlockGossip: types.BlockGossip{
  174. BlockPartSizeBytes: partSize,
  175. },
  176. }
  177. }
  178. func TestApplyUpdates(t *testing.T) {
  179. initParams := makeParams(1, 2, 3, 4, 5, 6)
  180. cases := [...]struct {
  181. init types.ConsensusParams
  182. updates *abci.ConsensusParams
  183. expected types.ConsensusParams
  184. }{
  185. 0: {initParams, nil, initParams},
  186. 1: {initParams, &abci.ConsensusParams{}, initParams},
  187. 2: {initParams,
  188. &abci.ConsensusParams{
  189. TxSize: &abci.TxSize{
  190. MaxBytes: 123,
  191. },
  192. },
  193. makeParams(1, 2, 3, 123, 5, 6)},
  194. 3: {initParams,
  195. &abci.ConsensusParams{
  196. BlockSize: &abci.BlockSize{
  197. MaxTxs: 44,
  198. MaxGas: 55,
  199. },
  200. },
  201. makeParams(1, 44, 55, 4, 5, 6)},
  202. 4: {initParams,
  203. &abci.ConsensusParams{
  204. BlockSize: &abci.BlockSize{
  205. MaxTxs: 789,
  206. },
  207. TxSize: &abci.TxSize{
  208. MaxGas: 888,
  209. },
  210. BlockGossip: &abci.BlockGossip{
  211. BlockPartSizeBytes: 2002,
  212. },
  213. },
  214. makeParams(1, 789, 3, 4, 888, 2002)},
  215. }
  216. for i, tc := range cases {
  217. res := applyUpdates(tc.init, tc.updates)
  218. assert.Equal(t, tc.expected, res, "case %d", i)
  219. }
  220. }
  221. func makeHeaderPartsResponses(state *State, height int64,
  222. pubkey crypto.PubKey) (*types.Header, types.PartSetHeader, *ABCIResponses) {
  223. block := makeBlock(height, state)
  224. _, val := state.Validators.GetByIndex(0)
  225. abciResponses := &ABCIResponses{
  226. Height: height,
  227. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: []*abci.Validator{}},
  228. }
  229. // if the pubkey is new, remove the old and add the new
  230. if !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) {
  231. abciResponses.EndBlock = &abci.ResponseEndBlock{
  232. ValidatorUpdates: []*abci.Validator{
  233. {val.PubKey.Bytes(), 0},
  234. {pubkey.Bytes(), 10},
  235. },
  236. }
  237. }
  238. return block.Header, types.PartSetHeader{}, abciResponses
  239. }
  240. type valChangeTestCase struct {
  241. height int64
  242. vals crypto.PubKey
  243. }