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.

491 lines
15 KiB

7 years ago
  1. package evidence_test
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/mock"
  7. "github.com/stretchr/testify/require"
  8. dbm "github.com/tendermint/tm-db"
  9. "github.com/tendermint/tendermint/evidence"
  10. "github.com/tendermint/tendermint/evidence/mocks"
  11. "github.com/tendermint/tendermint/libs/log"
  12. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  13. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  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 := types.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. }
  138. func TestEvidencePoolUpdate(t *testing.T) {
  139. height := int64(21)
  140. pool, val := defaultTestPool(t, height)
  141. state := pool.State()
  142. // create new block (no need to save it to blockStore)
  143. prunedEv := types.NewMockDuplicateVoteEvidenceWithValidator(
  144. 1,
  145. defaultEvidenceTime.Add(1*time.Minute),
  146. val,
  147. evidenceChainID,
  148. )
  149. require.NoError(t, pool.AddEvidence(prunedEv))
  150. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  151. height,
  152. defaultEvidenceTime.Add(21*time.Minute),
  153. val,
  154. evidenceChainID,
  155. )
  156. lastCommit := makeCommit(height, val.PrivKey.PubKey().Address())
  157. block := types.MakeBlock(height+1, []types.Tx{}, lastCommit, []types.Evidence{ev})
  158. // update state (partially)
  159. state.LastBlockHeight = height + 1
  160. state.LastBlockTime = defaultEvidenceTime.Add(22 * time.Minute)
  161. require.NoError(t, pool.CheckEvidence(types.EvidenceList{ev}))
  162. pool.Update(state, block.Evidence.Evidence)
  163. // a) Update marks evidence as committed so pending evidence should be empty
  164. evList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes)
  165. require.Empty(t, evList)
  166. require.Zero(t, evSize)
  167. // b) If we try to check this evidence again it should fail because it has already been committed
  168. err := pool.CheckEvidence(types.EvidenceList{ev})
  169. if assert.Error(t, err) {
  170. assert.Equal(t, "evidence was already committed", err.(*types.ErrInvalidEvidence).Reason.Error())
  171. }
  172. }
  173. func TestVerifyPendingEvidencePasses(t *testing.T) {
  174. var height int64 = 1
  175. pool, val := defaultTestPool(t, height)
  176. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  177. height,
  178. defaultEvidenceTime.Add(1*time.Minute),
  179. val,
  180. evidenceChainID,
  181. )
  182. require.NoError(t, pool.AddEvidence(ev))
  183. require.NoError(t, pool.CheckEvidence(types.EvidenceList{ev}))
  184. }
  185. func TestVerifyDuplicatedEvidenceFails(t *testing.T) {
  186. var height int64 = 1
  187. pool, val := defaultTestPool(t, height)
  188. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  189. height,
  190. defaultEvidenceTime.Add(1*time.Minute),
  191. val,
  192. evidenceChainID,
  193. )
  194. err := pool.CheckEvidence(types.EvidenceList{ev, ev})
  195. if assert.Error(t, err) {
  196. assert.Equal(t, "duplicate evidence", err.(*types.ErrInvalidEvidence).Reason.Error())
  197. }
  198. }
  199. // check that valid light client evidence is correctly validated and stored in
  200. // evidence pool
  201. func TestCheckEvidenceWithLightClientAttack(t *testing.T) {
  202. var (
  203. nValidators = 5
  204. validatorPower int64 = 10
  205. height int64 = 10
  206. )
  207. conflictingVals, conflictingPrivVals := types.RandValidatorSet(nValidators, validatorPower)
  208. trustedHeader := makeHeaderRandom(height)
  209. trustedHeader.Time = defaultEvidenceTime
  210. conflictingHeader := makeHeaderRandom(height)
  211. conflictingHeader.ValidatorsHash = conflictingVals.Hash()
  212. trustedHeader.ValidatorsHash = conflictingHeader.ValidatorsHash
  213. trustedHeader.NextValidatorsHash = conflictingHeader.NextValidatorsHash
  214. trustedHeader.ConsensusHash = conflictingHeader.ConsensusHash
  215. trustedHeader.AppHash = conflictingHeader.AppHash
  216. trustedHeader.LastResultsHash = conflictingHeader.LastResultsHash
  217. // For simplicity we are simulating a duplicate vote attack where all the
  218. // validators in the conflictingVals set voted twice.
  219. blockID := makeBlockID(conflictingHeader.Hash(), 1000, []byte("partshash"))
  220. voteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), conflictingVals)
  221. commit, err := types.MakeCommit(blockID, height, 1, voteSet, conflictingPrivVals, defaultEvidenceTime)
  222. require.NoError(t, err)
  223. ev := &types.LightClientAttackEvidence{
  224. ConflictingBlock: &types.LightBlock{
  225. SignedHeader: &types.SignedHeader{
  226. Header: conflictingHeader,
  227. Commit: commit,
  228. },
  229. ValidatorSet: conflictingVals,
  230. },
  231. CommonHeight: 10,
  232. TotalVotingPower: int64(nValidators) * validatorPower,
  233. ByzantineValidators: conflictingVals.Validators,
  234. Timestamp: defaultEvidenceTime,
  235. }
  236. trustedBlockID := makeBlockID(trustedHeader.Hash(), 1000, []byte("partshash"))
  237. trustedVoteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), conflictingVals)
  238. trustedCommit, err := types.MakeCommit(
  239. trustedBlockID,
  240. height,
  241. 1,
  242. trustedVoteSet,
  243. conflictingPrivVals,
  244. defaultEvidenceTime,
  245. )
  246. require.NoError(t, err)
  247. state := sm.State{
  248. LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute),
  249. LastBlockHeight: 11,
  250. ConsensusParams: *types.DefaultConsensusParams(),
  251. }
  252. stateStore := &smmocks.Store{}
  253. stateStore.On("LoadValidators", height).Return(conflictingVals, nil)
  254. stateStore.On("Load").Return(state, nil)
  255. blockStore := &mocks.BlockStore{}
  256. blockStore.On("LoadBlockMeta", height).Return(&types.BlockMeta{Header: *trustedHeader})
  257. blockStore.On("LoadBlockCommit", height).Return(trustedCommit)
  258. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore)
  259. require.NoError(t, err)
  260. require.NoError(t, pool.AddEvidence(ev))
  261. require.NoError(t, pool.CheckEvidence(types.EvidenceList{ev}))
  262. // Take away the last signature -> there are less validators then what we have detected,
  263. // hence this should fail.
  264. commit.Signatures = append(commit.Signatures[:nValidators-1], types.NewCommitSigAbsent())
  265. require.Error(t, pool.CheckEvidence(types.EvidenceList{ev}))
  266. }
  267. // Tests that restarting the evidence pool after a potential failure will recover the
  268. // pending evidence and continue to gossip it
  269. func TestRecoverPendingEvidence(t *testing.T) {
  270. height := int64(10)
  271. val := types.NewMockPV()
  272. valAddress := val.PrivKey.PubKey().Address()
  273. evidenceDB := dbm.NewMemDB()
  274. stateStore := initializeValidatorState(t, val, height)
  275. state, err := stateStore.Load()
  276. require.NoError(t, err)
  277. blockStore := initializeBlockStore(dbm.NewMemDB(), state, valAddress)
  278. // create previous pool and populate it
  279. pool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, stateStore, blockStore)
  280. require.NoError(t, err)
  281. goodEvidence := types.NewMockDuplicateVoteEvidenceWithValidator(
  282. height,
  283. defaultEvidenceTime.Add(10*time.Minute),
  284. val,
  285. evidenceChainID,
  286. )
  287. expiredEvidence := types.NewMockDuplicateVoteEvidenceWithValidator(
  288. int64(1),
  289. defaultEvidenceTime.Add(1*time.Minute),
  290. val,
  291. evidenceChainID,
  292. )
  293. require.NoError(t, pool.AddEvidence(goodEvidence))
  294. require.NoError(t, pool.AddEvidence(expiredEvidence))
  295. // now recover from the previous pool at a different time
  296. newStateStore := &smmocks.Store{}
  297. newStateStore.On("Load").Return(sm.State{
  298. LastBlockTime: defaultEvidenceTime.Add(25 * time.Minute),
  299. LastBlockHeight: height + 15,
  300. ConsensusParams: tmproto.ConsensusParams{
  301. Block: tmproto.BlockParams{
  302. MaxBytes: 22020096,
  303. MaxGas: -1,
  304. },
  305. Evidence: tmproto.EvidenceParams{
  306. MaxAgeNumBlocks: 20,
  307. MaxAgeDuration: 20 * time.Minute,
  308. MaxBytes: 1000,
  309. },
  310. },
  311. }, nil)
  312. newPool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, newStateStore, blockStore)
  313. require.NoError(t, err)
  314. evList, _ := newPool.PendingEvidence(defaultEvidenceMaxBytes)
  315. require.Equal(t, 1, len(evList))
  316. next := newPool.EvidenceFront()
  317. require.Equal(t, goodEvidence, next.Value.(types.Evidence))
  318. }
  319. func initializeStateFromValidatorSet(t *testing.T, valSet *types.ValidatorSet, height int64) sm.Store {
  320. stateDB := dbm.NewMemDB()
  321. stateStore := sm.NewStore(stateDB)
  322. state := sm.State{
  323. ChainID: evidenceChainID,
  324. InitialHeight: 1,
  325. LastBlockHeight: height,
  326. LastBlockTime: defaultEvidenceTime,
  327. Validators: valSet,
  328. NextValidators: valSet.CopyIncrementProposerPriority(1),
  329. LastValidators: valSet,
  330. LastHeightValidatorsChanged: 1,
  331. ConsensusParams: tmproto.ConsensusParams{
  332. Block: tmproto.BlockParams{
  333. MaxBytes: 22020096,
  334. MaxGas: -1,
  335. },
  336. Evidence: tmproto.EvidenceParams{
  337. MaxAgeNumBlocks: 20,
  338. MaxAgeDuration: 20 * time.Minute,
  339. MaxBytes: 1000,
  340. },
  341. },
  342. }
  343. // save all states up to height
  344. for i := int64(0); i <= height; i++ {
  345. state.LastBlockHeight = i
  346. require.NoError(t, stateStore.Save(state))
  347. }
  348. return stateStore
  349. }
  350. func initializeValidatorState(t *testing.T, privVal types.PrivValidator, height int64) sm.Store {
  351. pubKey, _ := privVal.GetPubKey()
  352. validator := &types.Validator{Address: pubKey.Address(), VotingPower: 10, PubKey: pubKey}
  353. // create validator set and state
  354. valSet := &types.ValidatorSet{
  355. Validators: []*types.Validator{validator},
  356. Proposer: validator,
  357. }
  358. return initializeStateFromValidatorSet(t, valSet, height)
  359. }
  360. // initializeBlockStore creates a block storage and populates it w/ a dummy
  361. // block at +height+.
  362. func initializeBlockStore(db dbm.DB, state sm.State, valAddr []byte) *store.BlockStore {
  363. blockStore := store.NewBlockStore(db)
  364. for i := int64(1); i <= state.LastBlockHeight; i++ {
  365. lastCommit := makeCommit(i-1, valAddr)
  366. block, _ := state.MakeBlock(i, []types.Tx{}, lastCommit, nil,
  367. state.Validators.GetProposer().Address)
  368. block.Header.Time = defaultEvidenceTime.Add(time.Duration(i) * time.Minute)
  369. block.Header.Version = tmversion.Consensus{Block: version.BlockProtocol, App: 1}
  370. const parts = 1
  371. partSet := block.MakePartSet(parts)
  372. seenCommit := makeCommit(i, valAddr)
  373. blockStore.SaveBlock(block, partSet, seenCommit)
  374. }
  375. return blockStore
  376. }
  377. func makeCommit(height int64, valAddr []byte) *types.Commit {
  378. commitSigs := []types.CommitSig{{
  379. BlockIDFlag: types.BlockIDFlagCommit,
  380. ValidatorAddress: valAddr,
  381. Timestamp: defaultEvidenceTime,
  382. Signature: []byte("Signature"),
  383. }}
  384. return types.NewCommit(height, 0, types.BlockID{}, commitSigs)
  385. }
  386. func defaultTestPool(t *testing.T, height int64) (*evidence.Pool, types.MockPV) {
  387. val := types.NewMockPV()
  388. valAddress := val.PrivKey.PubKey().Address()
  389. evidenceDB := dbm.NewMemDB()
  390. stateStore := initializeValidatorState(t, val, height)
  391. state, _ := stateStore.Load()
  392. blockStore := initializeBlockStore(dbm.NewMemDB(), state, valAddress)
  393. pool, err := evidence.NewPool(log.TestingLogger(), evidenceDB, stateStore, blockStore)
  394. require.NoError(t, err, "test evidence pool could not be created")
  395. return pool, val
  396. }
  397. func createState(height int64, valSet *types.ValidatorSet) sm.State {
  398. return sm.State{
  399. ChainID: evidenceChainID,
  400. LastBlockHeight: height,
  401. LastBlockTime: defaultEvidenceTime,
  402. Validators: valSet,
  403. ConsensusParams: *types.DefaultConsensusParams(),
  404. }
  405. }