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.

453 lines
15 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. next = pool.EvidenceFront()
  144. require.NotNil(t, next)
  145. }
  146. func TestEvidencePoolUpdate(t *testing.T) {
  147. height := int64(21)
  148. pool, val := defaultTestPool(height)
  149. state := pool.State()
  150. // create new block (no need to save it to blockStore)
  151. prunedEv := types.NewMockDuplicateVoteEvidenceWithValidator(1, defaultEvidenceTime.Add(1*time.Minute),
  152. val, evidenceChainID)
  153. err := pool.AddEvidence(prunedEv)
  154. require.NoError(t, err)
  155. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime.Add(21*time.Minute),
  156. val, evidenceChainID)
  157. lastCommit := makeCommit(height, val.PrivKey.PubKey().Address())
  158. block := types.MakeBlock(height+1, []types.Tx{}, lastCommit, []types.Evidence{ev})
  159. // update state (partially)
  160. state.LastBlockHeight = height + 1
  161. state.LastBlockTime = defaultEvidenceTime.Add(22 * time.Minute)
  162. err = pool.CheckEvidence(types.EvidenceList{ev})
  163. require.NoError(t, err)
  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. assert.Empty(t, evList)
  168. assert.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(height)
  178. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime.Add(1*time.Minute),
  179. val, evidenceChainID)
  180. err := pool.AddEvidence(ev)
  181. require.NoError(t, err)
  182. err = pool.CheckEvidence(types.EvidenceList{ev})
  183. assert.NoError(t, err)
  184. }
  185. func TestVerifyDuplicatedEvidenceFails(t *testing.T) {
  186. var height int64 = 1
  187. pool, val := defaultTestPool(height)
  188. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime.Add(1*time.Minute),
  189. val, evidenceChainID)
  190. err := pool.CheckEvidence(types.EvidenceList{ev, ev})
  191. if assert.Error(t, err) {
  192. assert.Equal(t, "duplicate evidence", err.(*types.ErrInvalidEvidence).Reason.Error())
  193. }
  194. }
  195. // check that valid light client evidence is correctly validated and stored in
  196. // evidence pool
  197. func TestLightClientAttackEvidenceLifecycle(t *testing.T) {
  198. var (
  199. height int64 = 100
  200. commonHeight int64 = 90
  201. )
  202. ev, trusted, common := makeLunaticEvidence(t, height, commonHeight,
  203. 10, 5, 5, defaultEvidenceTime, defaultEvidenceTime.Add(1*time.Hour))
  204. state := sm.State{
  205. LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour),
  206. LastBlockHeight: 110,
  207. ConsensusParams: *types.DefaultConsensusParams(),
  208. }
  209. stateStore := &smmocks.Store{}
  210. stateStore.On("LoadValidators", height).Return(trusted.ValidatorSet, nil)
  211. stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil)
  212. stateStore.On("Load").Return(state, nil)
  213. blockStore := &mocks.BlockStore{}
  214. blockStore.On("LoadBlockMeta", height).Return(&types.BlockMeta{Header: *trusted.Header})
  215. blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header})
  216. blockStore.On("LoadBlockCommit", height).Return(trusted.Commit)
  217. blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit)
  218. pool, err := evidence.NewPool(dbm.NewMemDB(), stateStore, blockStore)
  219. require.NoError(t, err)
  220. pool.SetLogger(log.TestingLogger())
  221. err = pool.AddEvidence(ev)
  222. assert.NoError(t, err)
  223. hash := ev.Hash()
  224. require.NoError(t, pool.AddEvidence(ev))
  225. require.NoError(t, pool.AddEvidence(ev))
  226. pendingEv, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  227. require.Equal(t, 1, len(pendingEv))
  228. require.Equal(t, ev, pendingEv[0])
  229. require.NoError(t, pool.CheckEvidence(pendingEv))
  230. require.Equal(t, ev, pendingEv[0])
  231. state.LastBlockHeight++
  232. state.LastBlockTime = state.LastBlockTime.Add(1 * time.Minute)
  233. pool.Update(state, pendingEv)
  234. require.Equal(t, hash, pendingEv[0].Hash())
  235. remaindingEv, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  236. require.Empty(t, remaindingEv)
  237. // evidence is already committed so it shouldn't pass
  238. require.Error(t, pool.CheckEvidence(types.EvidenceList{ev}))
  239. require.NoError(t, pool.AddEvidence(ev))
  240. remaindingEv, _ = pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  241. require.Empty(t, remaindingEv)
  242. }
  243. // Tests that restarting the evidence pool after a potential failure will recover the
  244. // pending evidence and continue to gossip it
  245. func TestRecoverPendingEvidence(t *testing.T) {
  246. height := int64(10)
  247. val := types.NewMockPV()
  248. valAddress := val.PrivKey.PubKey().Address()
  249. evidenceDB := dbm.NewMemDB()
  250. stateStore := initializeValidatorState(val, height)
  251. state, err := stateStore.Load()
  252. require.NoError(t, err)
  253. blockStore := initializeBlockStore(dbm.NewMemDB(), state, valAddress)
  254. // create previous pool and populate it
  255. pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore)
  256. require.NoError(t, err)
  257. pool.SetLogger(log.TestingLogger())
  258. goodEvidence := types.NewMockDuplicateVoteEvidenceWithValidator(height,
  259. defaultEvidenceTime.Add(10*time.Minute), val, evidenceChainID)
  260. expiredEvidence := types.NewMockDuplicateVoteEvidenceWithValidator(int64(1),
  261. defaultEvidenceTime.Add(1*time.Minute), val, evidenceChainID)
  262. err = pool.AddEvidence(goodEvidence)
  263. require.NoError(t, err)
  264. err = pool.AddEvidence(expiredEvidence)
  265. require.NoError(t, err)
  266. // now recover from the previous pool at a different time
  267. newStateStore := &smmocks.Store{}
  268. newStateStore.On("Load").Return(sm.State{
  269. LastBlockTime: defaultEvidenceTime.Add(25 * time.Minute),
  270. LastBlockHeight: height + 15,
  271. ConsensusParams: tmproto.ConsensusParams{
  272. Block: tmproto.BlockParams{
  273. MaxBytes: 22020096,
  274. MaxGas: -1,
  275. },
  276. Evidence: tmproto.EvidenceParams{
  277. MaxAgeNumBlocks: 20,
  278. MaxAgeDuration: 20 * time.Minute,
  279. MaxBytes: defaultEvidenceMaxBytes,
  280. },
  281. },
  282. }, nil)
  283. newPool, err := evidence.NewPool(evidenceDB, newStateStore, blockStore)
  284. assert.NoError(t, err)
  285. evList, _ := newPool.PendingEvidence(defaultEvidenceMaxBytes)
  286. assert.Equal(t, 1, len(evList))
  287. next := newPool.EvidenceFront()
  288. assert.Equal(t, goodEvidence, next.Value.(types.Evidence))
  289. }
  290. func initializeStateFromValidatorSet(valSet *types.ValidatorSet, height int64) sm.Store {
  291. stateDB := dbm.NewMemDB()
  292. stateStore := sm.NewStore(stateDB)
  293. state := sm.State{
  294. ChainID: evidenceChainID,
  295. InitialHeight: 1,
  296. LastBlockHeight: height,
  297. LastBlockTime: defaultEvidenceTime,
  298. Validators: valSet,
  299. NextValidators: valSet.CopyIncrementProposerPriority(1),
  300. LastValidators: valSet,
  301. LastHeightValidatorsChanged: 1,
  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. }
  314. // save all states up to height
  315. for i := int64(0); i <= height; i++ {
  316. state.LastBlockHeight = i
  317. if err := stateStore.Save(state); err != nil {
  318. panic(err)
  319. }
  320. }
  321. return stateStore
  322. }
  323. func initializeValidatorState(privVal types.PrivValidator, height int64) sm.Store {
  324. pubKey, _ := privVal.GetPubKey()
  325. validator := &types.Validator{Address: pubKey.Address(), VotingPower: 10, PubKey: pubKey}
  326. // create validator set and state
  327. valSet := &types.ValidatorSet{
  328. Validators: []*types.Validator{validator},
  329. Proposer: validator,
  330. }
  331. return initializeStateFromValidatorSet(valSet, height)
  332. }
  333. // initializeBlockStore creates a block storage and populates it w/ a dummy
  334. // block at +height+.
  335. func initializeBlockStore(db dbm.DB, state sm.State, valAddr []byte) *store.BlockStore {
  336. blockStore := store.NewBlockStore(db)
  337. for i := int64(1); i <= state.LastBlockHeight; i++ {
  338. lastCommit := makeCommit(i-1, valAddr)
  339. block, _ := state.MakeBlock(i, []types.Tx{}, lastCommit, nil,
  340. state.Validators.GetProposer().Address)
  341. block.Header.Time = defaultEvidenceTime.Add(time.Duration(i) * time.Minute)
  342. block.Header.Version = tmversion.Consensus{Block: version.BlockProtocol, App: 1}
  343. const parts = 1
  344. partSet := block.MakePartSet(parts)
  345. seenCommit := makeCommit(i, valAddr)
  346. blockStore.SaveBlock(block, partSet, seenCommit)
  347. }
  348. return blockStore
  349. }
  350. func makeCommit(height int64, valAddr []byte) *types.Commit {
  351. commitSigs := []types.CommitSig{{
  352. BlockIDFlag: types.BlockIDFlagCommit,
  353. ValidatorAddress: valAddr,
  354. Timestamp: defaultEvidenceTime,
  355. Signature: []byte("Signature"),
  356. }}
  357. return types.NewCommit(height, 0, types.BlockID{}, commitSigs)
  358. }
  359. func defaultTestPool(height int64) (*evidence.Pool, types.MockPV) {
  360. val := types.NewMockPV()
  361. valAddress := val.PrivKey.PubKey().Address()
  362. evidenceDB := dbm.NewMemDB()
  363. stateStore := initializeValidatorState(val, height)
  364. state, _ := stateStore.Load()
  365. blockStore := initializeBlockStore(dbm.NewMemDB(), state, valAddress)
  366. pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore)
  367. if err != nil {
  368. panic("test evidence pool could not be created")
  369. }
  370. pool.SetLogger(log.TestingLogger())
  371. return pool, val
  372. }
  373. func createState(height int64, valSet *types.ValidatorSet) sm.State {
  374. return sm.State{
  375. ChainID: evidenceChainID,
  376. LastBlockHeight: height,
  377. LastBlockTime: defaultEvidenceTime,
  378. Validators: valSet,
  379. ConsensusParams: *types.DefaultConsensusParams(),
  380. }
  381. }