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.

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