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.

488 lines
15 KiB

7 years ago
  1. package evidence_test
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/mock"
  8. "github.com/stretchr/testify/require"
  9. dbm "github.com/tendermint/tm-db"
  10. "github.com/tendermint/tendermint/evidence"
  11. "github.com/tendermint/tendermint/evidence/mocks"
  12. "github.com/tendermint/tendermint/internal/test/factory"
  13. "github.com/tendermint/tendermint/libs/log"
  14. sm "github.com/tendermint/tendermint/state"
  15. smmocks "github.com/tendermint/tendermint/state/mocks"
  16. "github.com/tendermint/tendermint/store"
  17. "github.com/tendermint/tendermint/types"
  18. "github.com/tendermint/tendermint/version"
  19. )
  20. const evidenceChainID = "test_chain"
  21. var (
  22. defaultEvidenceTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  23. defaultEvidenceMaxBytes int64 = 1000
  24. )
  25. func TestEvidencePoolBasic(t *testing.T) {
  26. var (
  27. height = int64(1)
  28. stateStore = &smmocks.Store{}
  29. evidenceDB = dbm.NewMemDB()
  30. blockStore = &mocks.BlockStore{}
  31. )
  32. valSet, privVals := factory.RandValidatorSet(1, 10)
  33. blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(
  34. &types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}},
  35. )
  36. stateStore.On("LoadValidators", mock.AnythingOfType("int64")).Return(valSet, nil)
  37. stateStore.On("Load").Return(createState(height+1, valSet), nil)
  38. pool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, stateStore, blockStore)
  39. require.NoError(t, err)
  40. // evidence not seen yet:
  41. evs, size := pool.PendingEvidence(defaultEvidenceMaxBytes)
  42. require.Equal(t, 0, len(evs))
  43. require.Zero(t, size)
  44. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, privVals[0], evidenceChainID)
  45. // good evidence
  46. evAdded := make(chan struct{})
  47. go func() {
  48. <-pool.EvidenceWaitChan()
  49. close(evAdded)
  50. }()
  51. // evidence seen but not yet committed:
  52. require.NoError(t, pool.AddEvidence(ev))
  53. select {
  54. case <-evAdded:
  55. case <-time.After(5 * time.Second):
  56. t.Fatal("evidence was not added to list after 5s")
  57. }
  58. next := pool.EvidenceFront()
  59. require.Equal(t, ev, next.Value.(types.Evidence))
  60. const evidenceBytes int64 = 372
  61. evs, size = pool.PendingEvidence(evidenceBytes)
  62. require.Equal(t, 1, len(evs))
  63. require.Equal(t, evidenceBytes, size) // check that the size of the single evidence in bytes is correct
  64. // shouldn't be able to add evidence twice
  65. require.NoError(t, pool.AddEvidence(ev))
  66. evs, _ = pool.PendingEvidence(defaultEvidenceMaxBytes)
  67. require.Equal(t, 1, len(evs))
  68. }
  69. // Tests inbound evidence for the right time and height
  70. func TestAddExpiredEvidence(t *testing.T) {
  71. var (
  72. val = types.NewMockPV()
  73. height = int64(30)
  74. stateStore = initializeValidatorState(t, val, height)
  75. evidenceDB = dbm.NewMemDB()
  76. blockStore = &mocks.BlockStore{}
  77. expiredEvidenceTime = time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC)
  78. expiredHeight = int64(2)
  79. )
  80. blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(func(h int64) *types.BlockMeta {
  81. if h == height || h == expiredHeight {
  82. return &types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}}
  83. }
  84. return &types.BlockMeta{Header: types.Header{Time: expiredEvidenceTime}}
  85. })
  86. pool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, stateStore, blockStore)
  87. require.NoError(t, err)
  88. testCases := []struct {
  89. evHeight int64
  90. evTime time.Time
  91. expErr bool
  92. evDescription string
  93. }{
  94. {height, defaultEvidenceTime, false, "valid evidence"},
  95. {expiredHeight, defaultEvidenceTime, false, "valid evidence (despite old height)"},
  96. {height - 1, expiredEvidenceTime, false, "valid evidence (despite old time)"},
  97. {expiredHeight - 1, expiredEvidenceTime, true,
  98. "evidence from height 1 (created at: 2019-01-01 00:00:00 +0000 UTC) is too old"},
  99. {height, defaultEvidenceTime.Add(1 * time.Minute), true, "evidence time and block time is different"},
  100. }
  101. for _, tc := range testCases {
  102. tc := tc
  103. t.Run(tc.evDescription, func(t *testing.T) {
  104. ev := types.NewMockDuplicateVoteEvidenceWithValidator(tc.evHeight, tc.evTime, val, evidenceChainID)
  105. err := pool.AddEvidence(ev)
  106. if tc.expErr {
  107. require.Error(t, err)
  108. } else {
  109. require.NoError(t, err)
  110. }
  111. })
  112. }
  113. }
  114. func TestReportConflictingVotes(t *testing.T) {
  115. var height int64 = 10
  116. pool, pv := defaultTestPool(t, height)
  117. val := types.NewValidator(pv.PrivKey.PubKey(), 10)
  118. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height+1, defaultEvidenceTime, pv, evidenceChainID)
  119. pool.ReportConflictingVotes(ev.VoteA, ev.VoteB)
  120. // shouldn't be able to submit the same evidence twice
  121. pool.ReportConflictingVotes(ev.VoteA, ev.VoteB)
  122. // evidence from consensus should not be added immediately but reside in the consensus buffer
  123. evList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes)
  124. require.Empty(t, evList)
  125. require.Zero(t, evSize)
  126. next := pool.EvidenceFront()
  127. require.Nil(t, next)
  128. // move to next height and update state and evidence pool
  129. state := pool.State()
  130. state.LastBlockHeight++
  131. state.LastBlockTime = ev.Time()
  132. state.LastValidators = types.NewValidatorSet([]*types.Validator{val})
  133. pool.Update(state, []types.Evidence{})
  134. // should be able to retrieve evidence from pool
  135. evList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes)
  136. require.Equal(t, []types.Evidence{ev}, evList)
  137. next = pool.EvidenceFront()
  138. require.NotNil(t, next)
  139. }
  140. func TestEvidencePoolUpdate(t *testing.T) {
  141. height := int64(21)
  142. pool, val := defaultTestPool(t, height)
  143. state := pool.State()
  144. // create two lots of old evidence that we expect to be pruned when we update
  145. prunedEv := types.NewMockDuplicateVoteEvidenceWithValidator(
  146. 1,
  147. defaultEvidenceTime.Add(1*time.Minute),
  148. val,
  149. evidenceChainID,
  150. )
  151. notPrunedEv := types.NewMockDuplicateVoteEvidenceWithValidator(
  152. 2,
  153. defaultEvidenceTime.Add(2*time.Minute),
  154. val,
  155. evidenceChainID,
  156. )
  157. require.NoError(t, pool.AddEvidence(prunedEv))
  158. require.NoError(t, pool.AddEvidence(notPrunedEv))
  159. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  160. height,
  161. defaultEvidenceTime.Add(21*time.Minute),
  162. val,
  163. evidenceChainID,
  164. )
  165. lastCommit := makeCommit(height, val.PrivKey.PubKey().Address())
  166. block := types.MakeBlock(height+1, []types.Tx{}, lastCommit, []types.Evidence{ev})
  167. // update state (partially)
  168. state.LastBlockHeight = height + 1
  169. state.LastBlockTime = defaultEvidenceTime.Add(22 * time.Minute)
  170. evList, _ := pool.PendingEvidence(2 * defaultEvidenceMaxBytes)
  171. require.Equal(t, 2, len(evList))
  172. require.Equal(t, uint32(2), pool.Size())
  173. require.NoError(t, pool.CheckEvidence(types.EvidenceList{ev}))
  174. evList, _ = pool.PendingEvidence(3 * defaultEvidenceMaxBytes)
  175. require.Equal(t, 3, len(evList))
  176. require.Equal(t, uint32(3), pool.Size())
  177. pool.Update(state, block.Evidence.Evidence)
  178. // a) Update marks evidence as committed so pending evidence should be empty
  179. evList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes)
  180. require.Equal(t, []types.Evidence{notPrunedEv}, evList)
  181. // b) If we try to check this evidence again it should fail because it has already been committed
  182. err := pool.CheckEvidence(types.EvidenceList{ev})
  183. if assert.Error(t, err) {
  184. assert.Equal(t, "evidence was already committed", err.(*types.ErrInvalidEvidence).Reason.Error())
  185. }
  186. }
  187. func TestVerifyPendingEvidencePasses(t *testing.T) {
  188. var height int64 = 1
  189. pool, val := defaultTestPool(t, height)
  190. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  191. height,
  192. defaultEvidenceTime.Add(1*time.Minute),
  193. val,
  194. evidenceChainID,
  195. )
  196. require.NoError(t, pool.AddEvidence(ev))
  197. require.NoError(t, pool.CheckEvidence(types.EvidenceList{ev}))
  198. }
  199. func TestVerifyDuplicatedEvidenceFails(t *testing.T) {
  200. var height int64 = 1
  201. pool, val := defaultTestPool(t, height)
  202. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  203. height,
  204. defaultEvidenceTime.Add(1*time.Minute),
  205. val,
  206. evidenceChainID,
  207. )
  208. err := pool.CheckEvidence(types.EvidenceList{ev, ev})
  209. if assert.Error(t, err) {
  210. assert.Equal(t, "duplicate evidence", err.(*types.ErrInvalidEvidence).Reason.Error())
  211. }
  212. }
  213. // check that valid light client evidence is correctly validated and stored in
  214. // evidence pool
  215. func TestLightClientAttackEvidenceLifecycle(t *testing.T) {
  216. var (
  217. height int64 = 100
  218. commonHeight int64 = 90
  219. )
  220. ev, trusted, common := makeLunaticEvidence(t, height, commonHeight,
  221. 10, 5, 5, defaultEvidenceTime, defaultEvidenceTime.Add(1*time.Hour))
  222. state := sm.State{
  223. LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour),
  224. LastBlockHeight: 110,
  225. ConsensusParams: *types.DefaultConsensusParams(),
  226. }
  227. stateStore := &smmocks.Store{}
  228. stateStore.On("LoadValidators", height).Return(trusted.ValidatorSet, nil)
  229. stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil)
  230. stateStore.On("Load").Return(state, nil)
  231. blockStore := &mocks.BlockStore{}
  232. blockStore.On("LoadBlockMeta", height).Return(&types.BlockMeta{Header: *trusted.Header})
  233. blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header})
  234. blockStore.On("LoadBlockCommit", height).Return(trusted.Commit)
  235. blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit)
  236. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore)
  237. require.NoError(t, err)
  238. hash := ev.Hash()
  239. require.NoError(t, pool.AddEvidence(ev))
  240. require.NoError(t, pool.AddEvidence(ev))
  241. pendingEv, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  242. require.Equal(t, 1, len(pendingEv))
  243. require.Equal(t, ev, pendingEv[0])
  244. require.NoError(t, pool.CheckEvidence(pendingEv))
  245. require.Equal(t, ev, pendingEv[0])
  246. state.LastBlockHeight++
  247. state.LastBlockTime = state.LastBlockTime.Add(1 * time.Minute)
  248. pool.Update(state, pendingEv)
  249. require.Equal(t, hash, pendingEv[0].Hash())
  250. remaindingEv, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  251. require.Empty(t, remaindingEv)
  252. // evidence is already committed so it shouldn't pass
  253. require.Error(t, pool.CheckEvidence(types.EvidenceList{ev}))
  254. require.NoError(t, pool.AddEvidence(ev))
  255. remaindingEv, _ = pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  256. require.Empty(t, remaindingEv)
  257. }
  258. // Tests that restarting the evidence pool after a potential failure will recover the
  259. // pending evidence and continue to gossip it
  260. func TestRecoverPendingEvidence(t *testing.T) {
  261. height := int64(10)
  262. val := types.NewMockPV()
  263. valAddress := val.PrivKey.PubKey().Address()
  264. evidenceDB := dbm.NewMemDB()
  265. stateStore := initializeValidatorState(t, val, height)
  266. state, err := stateStore.Load()
  267. require.NoError(t, err)
  268. blockStore := initializeBlockStore(dbm.NewMemDB(), state, valAddress)
  269. // create previous pool and populate it
  270. pool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, stateStore, blockStore)
  271. require.NoError(t, err)
  272. goodEvidence := types.NewMockDuplicateVoteEvidenceWithValidator(
  273. height,
  274. defaultEvidenceTime.Add(10*time.Minute),
  275. val,
  276. evidenceChainID,
  277. )
  278. expiredEvidence := types.NewMockDuplicateVoteEvidenceWithValidator(
  279. int64(1),
  280. defaultEvidenceTime.Add(1*time.Minute),
  281. val,
  282. evidenceChainID,
  283. )
  284. require.NoError(t, pool.AddEvidence(goodEvidence))
  285. require.NoError(t, pool.AddEvidence(expiredEvidence))
  286. // now recover from the previous pool at a different time
  287. newStateStore := &smmocks.Store{}
  288. newStateStore.On("Load").Return(sm.State{
  289. LastBlockTime: defaultEvidenceTime.Add(25 * time.Minute),
  290. LastBlockHeight: height + 15,
  291. ConsensusParams: types.ConsensusParams{
  292. Block: types.BlockParams{
  293. MaxBytes: 22020096,
  294. MaxGas: -1,
  295. },
  296. Evidence: types.EvidenceParams{
  297. MaxAgeNumBlocks: 20,
  298. MaxAgeDuration: 20 * time.Minute,
  299. MaxBytes: defaultEvidenceMaxBytes,
  300. },
  301. },
  302. }, nil)
  303. newPool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, newStateStore, blockStore)
  304. require.NoError(t, err)
  305. evList, _ := newPool.PendingEvidence(defaultEvidenceMaxBytes)
  306. require.Equal(t, 1, len(evList))
  307. next := newPool.EvidenceFront()
  308. require.Equal(t, goodEvidence, next.Value.(types.Evidence))
  309. }
  310. func initializeStateFromValidatorSet(t *testing.T, valSet *types.ValidatorSet, height int64) sm.Store {
  311. stateDB := dbm.NewMemDB()
  312. stateStore := sm.NewStore(stateDB)
  313. state := sm.State{
  314. ChainID: evidenceChainID,
  315. InitialHeight: 1,
  316. LastBlockHeight: height,
  317. LastBlockTime: defaultEvidenceTime,
  318. Validators: valSet,
  319. NextValidators: valSet.CopyIncrementProposerPriority(1),
  320. LastValidators: valSet,
  321. LastHeightValidatorsChanged: 1,
  322. ConsensusParams: types.ConsensusParams{
  323. Block: types.BlockParams{
  324. MaxBytes: 22020096,
  325. MaxGas: -1,
  326. },
  327. Evidence: types.EvidenceParams{
  328. MaxAgeNumBlocks: 20,
  329. MaxAgeDuration: 20 * time.Minute,
  330. MaxBytes: 1000,
  331. },
  332. },
  333. }
  334. // save all states up to height
  335. for i := int64(0); i <= height; i++ {
  336. state.LastBlockHeight = i
  337. require.NoError(t, stateStore.Save(state))
  338. }
  339. return stateStore
  340. }
  341. func initializeValidatorState(t *testing.T, privVal types.PrivValidator, height int64) sm.Store {
  342. pubKey, _ := privVal.GetPubKey(context.Background())
  343. validator := &types.Validator{Address: pubKey.Address(), VotingPower: 10, PubKey: pubKey}
  344. // create validator set and state
  345. valSet := &types.ValidatorSet{
  346. Validators: []*types.Validator{validator},
  347. Proposer: validator,
  348. }
  349. return initializeStateFromValidatorSet(t, valSet, height)
  350. }
  351. // initializeBlockStore creates a block storage and populates it w/ a dummy
  352. // block at +height+.
  353. func initializeBlockStore(db dbm.DB, state sm.State, valAddr []byte) *store.BlockStore {
  354. blockStore := store.NewBlockStore(db)
  355. for i := int64(1); i <= state.LastBlockHeight; i++ {
  356. lastCommit := makeCommit(i-1, valAddr)
  357. block, _ := state.MakeBlock(i, []types.Tx{}, lastCommit, nil,
  358. state.Validators.GetProposer().Address)
  359. block.Header.Time = defaultEvidenceTime.Add(time.Duration(i) * time.Minute)
  360. block.Header.Version = version.Consensus{Block: version.BlockProtocol, App: 1}
  361. const parts = 1
  362. partSet := block.MakePartSet(parts)
  363. seenCommit := makeCommit(i, valAddr)
  364. blockStore.SaveBlock(block, partSet, seenCommit)
  365. }
  366. return blockStore
  367. }
  368. func makeCommit(height int64, valAddr []byte) *types.Commit {
  369. commitSigs := []types.CommitSig{{
  370. BlockIDFlag: types.BlockIDFlagCommit,
  371. ValidatorAddress: valAddr,
  372. Timestamp: defaultEvidenceTime,
  373. Signature: []byte("Signature"),
  374. }}
  375. return types.NewCommit(height, 0, types.BlockID{}, commitSigs)
  376. }
  377. func defaultTestPool(t *testing.T, height int64) (*evidence.Pool, types.MockPV) {
  378. val := types.NewMockPV()
  379. valAddress := val.PrivKey.PubKey().Address()
  380. evidenceDB := dbm.NewMemDB()
  381. stateStore := initializeValidatorState(t, val, height)
  382. state, _ := stateStore.Load()
  383. blockStore := initializeBlockStore(dbm.NewMemDB(), state, valAddress)
  384. pool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, stateStore, blockStore)
  385. require.NoError(t, err, "test evidence pool could not be created")
  386. return pool, val
  387. }
  388. func createState(height int64, valSet *types.ValidatorSet) sm.State {
  389. return sm.State{
  390. ChainID: evidenceChainID,
  391. LastBlockHeight: height,
  392. LastBlockTime: defaultEvidenceTime,
  393. Validators: valSet,
  394. ConsensusParams: *types.DefaultConsensusParams(),
  395. }
  396. }