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.

494 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. block := makeBlock(state, 2)
  280. // test we set proposer address
  281. assert.Equal(t, proposerAddress, block.ProposerAddress)
  282. }
  283. // TestConsensusParamsChangesSaveLoad tests saving and loading consensus params
  284. // with changes.
  285. func TestConsensusParamsChangesSaveLoad(t *testing.T) {
  286. tearDown, stateDB, state := setupTestCase(t)
  287. defer tearDown(t)
  288. // Change vals at these heights.
  289. changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20}
  290. N := len(changeHeights)
  291. // Each valset is just one validator.
  292. // create list of them.
  293. params := make([]types.ConsensusParams, N+1)
  294. params[0] = state.ConsensusParams
  295. for i := 1; i < N+1; i++ {
  296. params[i] = *types.DefaultConsensusParams()
  297. params[i].BlockSize.MaxBytes += int64(i)
  298. }
  299. // Build the params history by running updateState
  300. // with the right params set for each height.
  301. highestHeight := changeHeights[N-1] + 5
  302. changeIndex := 0
  303. cp := params[changeIndex]
  304. var err error
  305. for i := int64(1); i < highestHeight; i++ {
  306. // When we get to a change height, use the next params.
  307. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
  308. changeIndex++
  309. cp = params[changeIndex]
  310. }
  311. header, blockID, responses := makeHeaderPartsResponsesParams(state, i, cp)
  312. state, err = updateState(state, blockID, &header, responses)
  313. require.Nil(t, err)
  314. nextHeight := state.LastBlockHeight + 1
  315. saveConsensusParamsInfo(stateDB, nextHeight, state.LastHeightConsensusParamsChanged, state.ConsensusParams)
  316. }
  317. // Make all the test cases by using the same params until after the change.
  318. testCases := make([]paramsChangeTestCase, highestHeight)
  319. changeIndex = 0
  320. cp = params[changeIndex]
  321. for i := int64(1); i < highestHeight+1; i++ {
  322. // We get to the height after a change height use the next pubkey (note
  323. // our counter starts at 0 this time).
  324. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
  325. changeIndex++
  326. cp = params[changeIndex]
  327. }
  328. testCases[i-1] = paramsChangeTestCase{i, cp}
  329. }
  330. for _, testCase := range testCases {
  331. p, err := LoadConsensusParams(stateDB, testCase.height)
  332. assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", testCase.height))
  333. assert.Equal(t, testCase.params, p, fmt.Sprintf(`unexpected consensus params at
  334. height %d`, testCase.height))
  335. }
  336. }
  337. func makeParams(blockBytes, blockGas, evidenceAge int64) types.ConsensusParams {
  338. return types.ConsensusParams{
  339. BlockSize: types.BlockSize{
  340. MaxBytes: blockBytes,
  341. MaxGas: blockGas,
  342. },
  343. EvidenceParams: types.EvidenceParams{
  344. MaxAge: evidenceAge,
  345. },
  346. }
  347. }
  348. func pk() []byte {
  349. return ed25519.GenPrivKey().PubKey().Bytes()
  350. }
  351. func TestApplyUpdates(t *testing.T) {
  352. initParams := makeParams(1, 2, 3)
  353. cases := [...]struct {
  354. init types.ConsensusParams
  355. updates abci.ConsensusParams
  356. expected types.ConsensusParams
  357. }{
  358. 0: {initParams, abci.ConsensusParams{}, initParams},
  359. 1: {initParams, abci.ConsensusParams{}, initParams},
  360. 2: {initParams,
  361. abci.ConsensusParams{
  362. BlockSize: &abci.BlockSize{
  363. MaxBytes: 44,
  364. MaxGas: 55,
  365. },
  366. },
  367. makeParams(44, 55, 3)},
  368. 3: {initParams,
  369. abci.ConsensusParams{
  370. EvidenceParams: &abci.EvidenceParams{
  371. MaxAge: 66,
  372. },
  373. },
  374. makeParams(1, 2, 66)},
  375. }
  376. for i, tc := range cases {
  377. res := tc.init.Update(&(tc.updates))
  378. assert.Equal(t, tc.expected, res, "case %d", i)
  379. }
  380. }
  381. func makeHeaderPartsResponsesValPubKeyChange(state State, height int64,
  382. pubkey crypto.PubKey) (types.Header, types.BlockID, *ABCIResponses) {
  383. block := makeBlock(state, state.LastBlockHeight+1)
  384. abciResponses := &ABCIResponses{
  385. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  386. }
  387. // If the pubkey is new, remove the old and add the new.
  388. _, val := state.NextValidators.GetByIndex(0)
  389. if !bytes.Equal(pubkey.Bytes(), val.PubKey.Bytes()) {
  390. abciResponses.EndBlock = &abci.ResponseEndBlock{
  391. ValidatorUpdates: []abci.ValidatorUpdate{
  392. types.TM2PB.NewValidatorUpdate(val.PubKey, 0),
  393. types.TM2PB.NewValidatorUpdate(pubkey, 10),
  394. },
  395. }
  396. }
  397. return block.Header, types.BlockID{block.Hash(), types.PartSetHeader{}}, abciResponses
  398. }
  399. func makeHeaderPartsResponsesValPowerChange(state State, height int64,
  400. power int64) (types.Header, types.BlockID, *ABCIResponses) {
  401. block := makeBlock(state, state.LastBlockHeight+1)
  402. abciResponses := &ABCIResponses{
  403. EndBlock: &abci.ResponseEndBlock{ValidatorUpdates: nil},
  404. }
  405. // If the pubkey is new, remove the old and add the new.
  406. _, val := state.NextValidators.GetByIndex(0)
  407. if val.VotingPower != power {
  408. abciResponses.EndBlock = &abci.ResponseEndBlock{
  409. ValidatorUpdates: []abci.ValidatorUpdate{
  410. types.TM2PB.NewValidatorUpdate(val.PubKey, power),
  411. },
  412. }
  413. }
  414. return block.Header, types.BlockID{block.Hash(), types.PartSetHeader{}}, abciResponses
  415. }
  416. func makeHeaderPartsResponsesParams(state State, height int64,
  417. params types.ConsensusParams) (types.Header, types.BlockID, *ABCIResponses) {
  418. block := makeBlock(state, state.LastBlockHeight+1)
  419. abciResponses := &ABCIResponses{
  420. EndBlock: &abci.ResponseEndBlock{ConsensusParamUpdates: types.TM2PB.ConsensusParams(&params)},
  421. }
  422. return block.Header, types.BlockID{block.Hash(), types.PartSetHeader{}}, abciResponses
  423. }
  424. type paramsChangeTestCase struct {
  425. height int64
  426. params types.ConsensusParams
  427. }