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.

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