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.

496 lines
15 KiB

  1. package state
  2. import (
  3. "bytes"
  4. "fmt"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/require"
  8. abci "github.com/tendermint/tendermint/abci/types"
  9. crypto "github.com/tendermint/tendermint/crypto"
  10. "github.com/tendermint/tendermint/crypto/ed25519"
  11. cmn "github.com/tendermint/tendermint/libs/common"
  12. dbm "github.com/tendermint/tendermint/libs/db"
  13. cfg "github.com/tendermint/tendermint/config"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. // setupTestCase does setup common to all test cases.
  17. func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, State) {
  18. config := cfg.ResetTestRoot("state_")
  19. dbType := dbm.DBBackendType(config.DBBackend)
  20. stateDB := dbm.NewDB("state", dbType, config.DBDir())
  21. state, err := LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile())
  22. assert.NoError(t, err, "expected no error on LoadStateFromDBOrGenesisFile")
  23. tearDown := func(t *testing.T) {}
  24. return tearDown, stateDB, state
  25. }
  26. // TestStateCopy tests the correct copying behaviour of State.
  27. func TestStateCopy(t *testing.T) {
  28. tearDown, _, state := setupTestCase(t)
  29. defer tearDown(t)
  30. // nolint: vetshadow
  31. assert := assert.New(t)
  32. stateCopy := state.Copy()
  33. assert.True(state.Equals(stateCopy),
  34. fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n",
  35. stateCopy, state))
  36. stateCopy.LastBlockHeight++
  37. assert.False(state.Equals(stateCopy), fmt.Sprintf(`expected states to be different. got same
  38. %v`, state))
  39. }
  40. //TestMakeGenesisStateNilValidators tests state's consistency when genesis file's validators field is nil.
  41. func TestMakeGenesisStateNilValidators(t *testing.T) {
  42. doc := types.GenesisDoc{
  43. ChainID: "dummy",
  44. Validators: nil,
  45. }
  46. require.Nil(t, doc.ValidateAndComplete())
  47. state, err := MakeGenesisState(&doc)
  48. require.Nil(t, err)
  49. require.Equal(t, 0, len(state.Validators.Validators))
  50. require.Equal(t, 0, len(state.NextValidators.Validators))
  51. }
  52. // TestStateSaveLoad tests saving and loading State from a db.
  53. func TestStateSaveLoad(t *testing.T) {
  54. tearDown, stateDB, state := setupTestCase(t)
  55. defer tearDown(t)
  56. // nolint: vetshadow
  57. assert := assert.New(t)
  58. state.LastBlockHeight++
  59. SaveState(stateDB, state)
  60. loadedState := LoadState(stateDB)
  61. assert.True(state.Equals(loadedState),
  62. fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n",
  63. loadedState, state))
  64. }
  65. // TestABCIResponsesSaveLoad tests saving and loading ABCIResponses.
  66. func TestABCIResponsesSaveLoad1(t *testing.T) {
  67. tearDown, stateDB, state := setupTestCase(t)
  68. defer tearDown(t)
  69. // nolint: vetshadow
  70. assert := assert.New(t)
  71. state.LastBlockHeight++
  72. // Build mock responses.
  73. block := makeBlock(state, 2)
  74. abciResponses := NewABCIResponses(block)
  75. abciResponses.DeliverTx[0] = &abci.ResponseDeliverTx{Data: []byte("foo"), Tags: nil}
  76. abciResponses.DeliverTx[1] = &abci.ResponseDeliverTx{Data: []byte("bar"), Log: "ok", Tags: nil}
  77. abciResponses.EndBlock = &abci.ResponseEndBlock{ValidatorUpdates: []abci.ValidatorUpdate{
  78. types.TM2PB.NewValidatorUpdate(ed25519.GenPrivKey().PubKey(), 10),
  79. }}
  80. saveABCIResponses(stateDB, block.Height, abciResponses)
  81. loadedABCIResponses, err := LoadABCIResponses(stateDB, block.Height)
  82. assert.Nil(err)
  83. assert.Equal(abciResponses, loadedABCIResponses,
  84. fmt.Sprintf("ABCIResponses don't match:\ngot: %v\nexpected: %v\n",
  85. loadedABCIResponses, abciResponses))
  86. }
  87. // TestResultsSaveLoad tests saving and loading ABCI results.
  88. func TestABCIResponsesSaveLoad2(t *testing.T) {
  89. tearDown, stateDB, _ := setupTestCase(t)
  90. defer tearDown(t)
  91. // nolint: vetshadow
  92. assert := assert.New(t)
  93. cases := [...]struct {
  94. // Height is implied to equal index+2,
  95. // as block 1 is created from genesis.
  96. added []*abci.ResponseDeliverTx
  97. expected types.ABCIResults
  98. }{
  99. 0: {
  100. nil,
  101. nil,
  102. },
  103. 1: {
  104. []*abci.ResponseDeliverTx{
  105. {Code: 32, Data: []byte("Hello"), Log: "Huh?"},
  106. },
  107. types.ABCIResults{
  108. {32, []byte("Hello")},
  109. }},
  110. 2: {
  111. []*abci.ResponseDeliverTx{
  112. {Code: 383},
  113. {Data: []byte("Gotcha!"),
  114. Tags: []cmn.KVPair{
  115. cmn.KVPair{Key: []byte("a"), Value: []byte("1")},
  116. cmn.KVPair{Key: []byte("build"), Value: []byte("stuff")},
  117. }},
  118. },
  119. types.ABCIResults{
  120. {383, nil},
  121. {0, []byte("Gotcha!")},
  122. }},
  123. 3: {
  124. nil,
  125. nil,
  126. },
  127. }
  128. // Query all before, this should return error.
  129. for i := range cases {
  130. h := int64(i + 1)
  131. res, err := LoadABCIResponses(stateDB, h)
  132. assert.Error(err, "%d: %#v", i, res)
  133. }
  134. // Add all cases.
  135. for i, tc := range cases {
  136. h := int64(i + 1) // last block height, one below what we save
  137. responses := &ABCIResponses{
  138. DeliverTx: tc.added,
  139. EndBlock: &abci.ResponseEndBlock{},
  140. }
  141. saveABCIResponses(stateDB, h, responses)
  142. }
  143. // Query all before, should return expected value.
  144. for i, tc := range cases {
  145. h := int64(i + 1)
  146. res, err := LoadABCIResponses(stateDB, h)
  147. assert.NoError(err, "%d", i)
  148. assert.Equal(tc.expected.Hash(), res.ResultsHash(), "%d", i)
  149. }
  150. }
  151. // TestValidatorSimpleSaveLoad tests saving and loading validators.
  152. func TestValidatorSimpleSaveLoad(t *testing.T) {
  153. tearDown, stateDB, state := setupTestCase(t)
  154. defer tearDown(t)
  155. // nolint: vetshadow
  156. assert := assert.New(t)
  157. // Can't load anything for height 0.
  158. v, err := LoadValidators(stateDB, 0)
  159. assert.IsType(ErrNoValSetForHeight{}, err, "expected err at height 0")
  160. // Should be able to load for height 1.
  161. v, err = LoadValidators(stateDB, 1)
  162. assert.Nil(err, "expected no err at height 1")
  163. assert.Equal(v.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  164. // Should be able to load for height 2.
  165. v, err = LoadValidators(stateDB, 2)
  166. assert.Nil(err, "expected no err at height 2")
  167. assert.Equal(v.Hash(), state.NextValidators.Hash(), "expected validator hashes to match")
  168. // Increment height, save; should be able to load for next & next next height.
  169. state.LastBlockHeight++
  170. nextHeight := state.LastBlockHeight + 1
  171. saveValidatorsInfo(stateDB, nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators)
  172. vp0, err := LoadValidators(stateDB, nextHeight+0)
  173. assert.Nil(err, "expected no err")
  174. vp1, err := LoadValidators(stateDB, nextHeight+1)
  175. assert.Nil(err, "expected no err")
  176. assert.Equal(vp0.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  177. assert.Equal(vp1.Hash(), state.NextValidators.Hash(), "expected next validator hashes to match")
  178. }
  179. // TestValidatorChangesSaveLoad tests saving and loading a validator set with changes.
  180. func TestOneValidatorChangesSaveLoad(t *testing.T) {
  181. tearDown, stateDB, state := setupTestCase(t)
  182. defer tearDown(t)
  183. // Change vals at these heights.
  184. changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20}
  185. N := len(changeHeights)
  186. // Build the validator history by running updateState
  187. // with the right validator set for each height.
  188. highestHeight := changeHeights[N-1] + 5
  189. changeIndex := 0
  190. _, val := state.Validators.GetByIndex(0)
  191. power := val.VotingPower
  192. var err error
  193. for i := int64(1); i < highestHeight; i++ {
  194. // When we get to a change height, use the next pubkey.
  195. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
  196. changeIndex++
  197. power++
  198. }
  199. header, blockID, responses := makeHeaderPartsResponsesValPowerChange(state, i, power)
  200. state, err = updateState(state, blockID, &header, responses)
  201. assert.Nil(t, err)
  202. nextHeight := state.LastBlockHeight + 1
  203. saveValidatorsInfo(stateDB, nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators)
  204. }
  205. // On each height change, increment the power by one.
  206. testCases := make([]int64, highestHeight)
  207. changeIndex = 0
  208. power = val.VotingPower
  209. for i := int64(1); i < highestHeight+1; i++ {
  210. // We get to the height after a change height use the next pubkey (note
  211. // our counter starts at 0 this time).
  212. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
  213. changeIndex++
  214. power++
  215. }
  216. testCases[i-1] = power
  217. }
  218. for i, power := range testCases {
  219. v, err := LoadValidators(stateDB, int64(i+1+1)) // +1 because vset changes delayed by 1 block.
  220. assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", i))
  221. assert.Equal(t, v.Size(), 1, "validator set size is greater than 1: %d", v.Size())
  222. _, val := v.GetByIndex(0)
  223. assert.Equal(t, val.VotingPower, power, fmt.Sprintf(`unexpected powerat
  224. height %d`, i))
  225. }
  226. }
  227. // TestValidatorChangesSaveLoad tests saving and loading a validator set with
  228. // changes.
  229. func TestManyValidatorChangesSaveLoad(t *testing.T) {
  230. const valSetSize = 7
  231. tearDown, stateDB, state := setupTestCase(t)
  232. require.Equal(t, int64(0), state.LastBlockHeight)
  233. state.Validators = genValSet(valSetSize)
  234. state.NextValidators = state.Validators.CopyIncrementAccum(1)
  235. SaveState(stateDB, state)
  236. defer tearDown(t)
  237. _, valOld := state.Validators.GetByIndex(0)
  238. var pubkeyOld = valOld.PubKey
  239. pubkey := ed25519.GenPrivKey().PubKey()
  240. const height = 1
  241. // Swap the first validator with a new one (validator set size stays the same).
  242. header, blockID, responses := makeHeaderPartsResponsesValPubKeyChange(state, height, pubkey)
  243. // Save state etc.
  244. var err error
  245. state, err = updateState(state, blockID, &header, responses)
  246. require.Nil(t, err)
  247. nextHeight := state.LastBlockHeight + 1
  248. saveValidatorsInfo(stateDB, nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators)
  249. // Load nextheight, it should be the oldpubkey.
  250. v0, err := LoadValidators(stateDB, nextHeight)
  251. assert.Nil(t, err)
  252. assert.Equal(t, valSetSize, v0.Size())
  253. index, val := v0.GetByAddress(pubkeyOld.Address())
  254. assert.NotNil(t, val)
  255. if index < 0 {
  256. t.Fatal("expected to find old validator")
  257. }
  258. // Load nextheight+1, it should be the new pubkey.
  259. v1, err := LoadValidators(stateDB, nextHeight+1)
  260. assert.Nil(t, err)
  261. assert.Equal(t, valSetSize, v1.Size())
  262. index, val = v1.GetByAddress(pubkey.Address())
  263. assert.NotNil(t, val)
  264. if index < 0 {
  265. t.Fatal("expected to find newly added validator")
  266. }
  267. }
  268. func genValSet(size int) *types.ValidatorSet {
  269. vals := make([]*types.Validator, size)
  270. for i := 0; i < size; i++ {
  271. vals[i] = types.NewValidator(ed25519.GenPrivKey().PubKey(), 10)
  272. }
  273. return types.NewValidatorSet(vals)
  274. }
  275. func TestStateMakeBlock(t *testing.T) {
  276. tearDown, _, state := setupTestCase(t)
  277. defer tearDown(t)
  278. proposerAddress := state.Validators.GetProposer().Address
  279. stateVersion := state.Version.Consensus
  280. block := makeBlock(state, 2)
  281. // test we set some fields
  282. assert.Equal(t, stateVersion, block.Version)
  283. assert.Equal(t, proposerAddress, block.ProposerAddress)
  284. }
  285. // TestConsensusParamsChangesSaveLoad tests saving and loading consensus params
  286. // with changes.
  287. func TestConsensusParamsChangesSaveLoad(t *testing.T) {
  288. tearDown, stateDB, state := setupTestCase(t)
  289. defer tearDown(t)
  290. // Change vals at these heights.
  291. changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20}
  292. N := len(changeHeights)
  293. // Each valset is just one validator.
  294. // create list of them.
  295. params := make([]types.ConsensusParams, N+1)
  296. params[0] = state.ConsensusParams
  297. for i := 1; i < N+1; i++ {
  298. params[i] = *types.DefaultConsensusParams()
  299. params[i].BlockSize.MaxBytes += int64(i)
  300. }
  301. // Build the params history by running updateState
  302. // with the right params set for each height.
  303. highestHeight := changeHeights[N-1] + 5
  304. changeIndex := 0
  305. cp := params[changeIndex]
  306. var err error
  307. for i := int64(1); i < highestHeight; i++ {
  308. // When we get to a change height, use the next params.
  309. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
  310. changeIndex++
  311. cp = params[changeIndex]
  312. }
  313. header, blockID, responses := makeHeaderPartsResponsesParams(state, i, cp)
  314. state, err = updateState(state, blockID, &header, responses)
  315. require.Nil(t, err)
  316. nextHeight := state.LastBlockHeight + 1
  317. saveConsensusParamsInfo(stateDB, nextHeight, state.LastHeightConsensusParamsChanged, state.ConsensusParams)
  318. }
  319. // Make all the test cases by using the same params until after the change.
  320. testCases := make([]paramsChangeTestCase, highestHeight)
  321. changeIndex = 0
  322. cp = params[changeIndex]
  323. for i := int64(1); i < highestHeight+1; i++ {
  324. // We get to the height after a change height use the next pubkey (note
  325. // our counter starts at 0 this time).
  326. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
  327. changeIndex++
  328. cp = params[changeIndex]
  329. }
  330. testCases[i-1] = paramsChangeTestCase{i, cp}
  331. }
  332. for _, testCase := range testCases {
  333. p, err := LoadConsensusParams(stateDB, testCase.height)
  334. assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", testCase.height))
  335. assert.Equal(t, testCase.params, p, fmt.Sprintf(`unexpected consensus params at
  336. height %d`, testCase.height))
  337. }
  338. }
  339. func makeParams(blockBytes, blockGas, evidenceAge int64) types.ConsensusParams {
  340. return types.ConsensusParams{
  341. BlockSize: types.BlockSizeParams{
  342. MaxBytes: blockBytes,
  343. MaxGas: blockGas,
  344. },
  345. Evidence: types.EvidenceParams{
  346. MaxAge: evidenceAge,
  347. },
  348. }
  349. }
  350. func pk() []byte {
  351. return ed25519.GenPrivKey().PubKey().Bytes()
  352. }
  353. func TestApplyUpdates(t *testing.T) {
  354. initParams := makeParams(1, 2, 3)
  355. cases := [...]struct {
  356. init types.ConsensusParams
  357. updates abci.ConsensusParams
  358. expected types.ConsensusParams
  359. }{
  360. 0: {initParams, abci.ConsensusParams{}, initParams},
  361. 1: {initParams, abci.ConsensusParams{}, initParams},
  362. 2: {initParams,
  363. abci.ConsensusParams{
  364. BlockSize: &abci.BlockSizeParams{
  365. MaxBytes: 44,
  366. MaxGas: 55,
  367. },
  368. },
  369. makeParams(44, 55, 3)},
  370. 3: {initParams,
  371. abci.ConsensusParams{
  372. Evidence: &abci.EvidenceParams{
  373. MaxAge: 66,
  374. },
  375. },
  376. makeParams(1, 2, 66)},
  377. }
  378. for i, tc := range cases {
  379. res := tc.init.Update(&(tc.updates))
  380. assert.Equal(t, tc.expected, res, "case %d", i)
  381. }
  382. }
  383. func makeHeaderPartsResponsesValPubKeyChange(state State, height int64,
  384. pubkey crypto.PubKey) (types.Header, types.BlockID, *ABCIResponses) {
  385. block := makeBlock(state, state.LastBlockHeight+1)
  386. abciResponses := &ABCIResponses{
  387. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  388. }
  389. // If the pubkey is new, remove the old and add the new.
  390. _, val := state.NextValidators.GetByIndex(0)
  391. if !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) {
  392. abciResponses.EndBlock = &abci.ResponseEndBlock{
  393. ValidatorUpdates: []abci.ValidatorUpdate{
  394. types.TM2PB.NewValidatorUpdate(val.PubKey, 0),
  395. types.TM2PB.NewValidatorUpdate(pubkey, 10),
  396. },
  397. }
  398. }
  399. return block.Header, types.BlockID{block.Hash(), types.PartSetHeader{}}, abciResponses
  400. }
  401. func makeHeaderPartsResponsesValPowerChange(state State, height int64,
  402. power int64) (types.Header, types.BlockID, *ABCIResponses) {
  403. block := makeBlock(state, state.LastBlockHeight+1)
  404. abciResponses := &ABCIResponses{
  405. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  406. }
  407. // If the pubkey is new, remove the old and add the new.
  408. _, val := state.NextValidators.GetByIndex(0)
  409. if val.VotingPower != power {
  410. abciResponses.EndBlock = &abci.ResponseEndBlock{
  411. ValidatorUpdates: []abci.ValidatorUpdate{
  412. types.TM2PB.NewValidatorUpdate(val.PubKey, power),
  413. },
  414. }
  415. }
  416. return block.Header, types.BlockID{block.Hash(), types.PartSetHeader{}}, abciResponses
  417. }
  418. func makeHeaderPartsResponsesParams(state State, height int64,
  419. params types.ConsensusParams) (types.Header, types.BlockID, *ABCIResponses) {
  420. block := makeBlock(state, state.LastBlockHeight+1)
  421. abciResponses := &ABCIResponses{
  422. EndBlock: &abci.ResponseEndBlock{ConsensusParamUpdates: types.TM2PB.ConsensusParams(&params)},
  423. }
  424. return block.Header, types.BlockID{block.Hash(), types.PartSetHeader{}}, abciResponses
  425. }
  426. type paramsChangeTestCase struct {
  427. height int64
  428. params types.ConsensusParams
  429. }