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.

554 lines
16 KiB

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