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.

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