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.

497 lines
16 KiB

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