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.

465 lines
16 KiB

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