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.

641 lines
24 KiB

  1. package evidence_test
  2. import (
  3. "bytes"
  4. "context"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. dbm "github.com/tendermint/tm-db"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/tmhash"
  12. "github.com/tendermint/tendermint/internal/evidence"
  13. "github.com/tendermint/tendermint/internal/evidence/mocks"
  14. sm "github.com/tendermint/tendermint/internal/state"
  15. smmocks "github.com/tendermint/tendermint/internal/state/mocks"
  16. "github.com/tendermint/tendermint/internal/test/factory"
  17. "github.com/tendermint/tendermint/libs/log"
  18. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  19. "github.com/tendermint/tendermint/types"
  20. )
  21. const (
  22. defaultVotingPower = 10
  23. )
  24. func TestVerifyLightClientAttack_Lunatic(t *testing.T) {
  25. const (
  26. height int64 = 10
  27. commonHeight int64 = 4
  28. totalVals = 10
  29. byzVals = 4
  30. )
  31. ctx, cancel := context.WithCancel(context.Background())
  32. defer cancel()
  33. attackTime := defaultEvidenceTime.Add(1 * time.Hour)
  34. // create valid lunatic evidence
  35. ev, trusted, common := makeLunaticEvidence(ctx,
  36. t, height, commonHeight, totalVals, byzVals, totalVals-byzVals, defaultEvidenceTime, attackTime)
  37. require.NoError(t, ev.ValidateBasic())
  38. // good pass -> no error
  39. err := evidence.VerifyLightClientAttack(ev, common.SignedHeader, trusted.SignedHeader, common.ValidatorSet,
  40. defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour)
  41. assert.NoError(t, err)
  42. // trusted and conflicting hashes are the same -> an error should be returned
  43. err = evidence.VerifyLightClientAttack(ev, common.SignedHeader, ev.ConflictingBlock.SignedHeader, common.ValidatorSet,
  44. defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour)
  45. assert.Error(t, err)
  46. // evidence with different total validator power should fail
  47. ev.TotalVotingPower = 1 * defaultVotingPower
  48. err = evidence.VerifyLightClientAttack(ev, common.SignedHeader, trusted.SignedHeader, common.ValidatorSet,
  49. defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour)
  50. assert.NoError(t, err)
  51. assert.Error(t, ev.ValidateABCI(common.ValidatorSet, trusted.SignedHeader, defaultEvidenceTime))
  52. // evidence without enough malicious votes should fail
  53. ev, trusted, common = makeLunaticEvidence(ctx,
  54. t, height, commonHeight, totalVals, byzVals-1, totalVals-byzVals, defaultEvidenceTime, attackTime)
  55. err = evidence.VerifyLightClientAttack(ev, common.SignedHeader, trusted.SignedHeader, common.ValidatorSet,
  56. defaultEvidenceTime.Add(2*time.Hour), 3*time.Hour)
  57. assert.Error(t, err)
  58. }
  59. func TestVerify_LunaticAttackAgainstState(t *testing.T) {
  60. const (
  61. height int64 = 10
  62. commonHeight int64 = 4
  63. totalVals = 10
  64. byzVals = 4
  65. )
  66. ctx, cancel := context.WithCancel(context.Background())
  67. defer cancel()
  68. attackTime := defaultEvidenceTime.Add(1 * time.Hour)
  69. // create valid lunatic evidence
  70. ev, trusted, common := makeLunaticEvidence(ctx,
  71. t, height, commonHeight, totalVals, byzVals, totalVals-byzVals, defaultEvidenceTime, attackTime)
  72. // now we try to test verification against state
  73. state := sm.State{
  74. LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour),
  75. LastBlockHeight: height + 1,
  76. ConsensusParams: *types.DefaultConsensusParams(),
  77. }
  78. stateStore := &smmocks.Store{}
  79. stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil)
  80. stateStore.On("Load").Return(state, nil)
  81. blockStore := &mocks.BlockStore{}
  82. blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header})
  83. blockStore.On("LoadBlockMeta", height).Return(&types.BlockMeta{Header: *trusted.Header})
  84. blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit)
  85. blockStore.On("LoadBlockCommit", height).Return(trusted.Commit)
  86. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  87. require.NoError(t, err)
  88. evList := types.EvidenceList{ev}
  89. // check that the evidence pool correctly verifies the evidence
  90. assert.NoError(t, pool.CheckEvidence(ctx, evList))
  91. // as it was not originally in the pending bucket, it should now have been added
  92. pendingEvs, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  93. assert.Equal(t, 1, len(pendingEvs))
  94. assert.Equal(t, ev, pendingEvs[0])
  95. // if we submit evidence only against a single byzantine validator when we see there are more validators then this
  96. // should return an error
  97. ev.ByzantineValidators = ev.ByzantineValidators[:1]
  98. t.Log(evList)
  99. assert.Error(t, pool.CheckEvidence(ctx, evList))
  100. // restore original byz vals
  101. ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader)
  102. // duplicate evidence should be rejected
  103. evList = types.EvidenceList{ev, ev}
  104. pool, err = evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  105. require.NoError(t, err)
  106. assert.Error(t, pool.CheckEvidence(ctx, evList))
  107. // If evidence is submitted with an altered timestamp it should return an error
  108. ev.Timestamp = defaultEvidenceTime.Add(1 * time.Minute)
  109. pool, err = evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  110. require.NoError(t, err)
  111. require.NoError(t, setupEventBus(ctx, pool))
  112. err = pool.AddEvidence(ctx, ev)
  113. assert.Error(t, err)
  114. ev.Timestamp = defaultEvidenceTime
  115. // Evidence submitted with a different validator power should fail
  116. ev.TotalVotingPower = 1
  117. pool, err = evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  118. require.NoError(t, err)
  119. err = pool.AddEvidence(ctx, ev)
  120. assert.Error(t, err)
  121. ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower()
  122. }
  123. func TestVerify_ForwardLunaticAttack(t *testing.T) {
  124. const (
  125. nodeHeight int64 = 8
  126. attackHeight int64 = 10
  127. commonHeight int64 = 4
  128. totalVals = 10
  129. byzVals = 5
  130. )
  131. attackTime := defaultEvidenceTime.Add(1 * time.Hour)
  132. ctx, cancel := context.WithCancel(context.Background())
  133. defer cancel()
  134. // create a forward lunatic attack
  135. ev, trusted, common := makeLunaticEvidence(ctx,
  136. t, attackHeight, commonHeight, totalVals, byzVals, totalVals-byzVals, defaultEvidenceTime, attackTime)
  137. // now we try to test verification against state
  138. state := sm.State{
  139. LastBlockTime: defaultEvidenceTime.Add(2 * time.Hour),
  140. LastBlockHeight: nodeHeight,
  141. ConsensusParams: *types.DefaultConsensusParams(),
  142. }
  143. // modify trusted light block so that it is of a height less than the conflicting one
  144. trusted.Header.Height = state.LastBlockHeight
  145. trusted.Header.Time = state.LastBlockTime
  146. stateStore := &smmocks.Store{}
  147. stateStore.On("LoadValidators", commonHeight).Return(common.ValidatorSet, nil)
  148. stateStore.On("Load").Return(state, nil)
  149. blockStore := &mocks.BlockStore{}
  150. blockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header})
  151. blockStore.On("LoadBlockMeta", nodeHeight).Return(&types.BlockMeta{Header: *trusted.Header})
  152. blockStore.On("LoadBlockMeta", attackHeight).Return(nil)
  153. blockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit)
  154. blockStore.On("LoadBlockCommit", nodeHeight).Return(trusted.Commit)
  155. blockStore.On("Height").Return(nodeHeight)
  156. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  157. require.NoError(t, err)
  158. require.NoError(t, setupEventBus(ctx, pool))
  159. // check that the evidence pool correctly verifies the evidence
  160. assert.NoError(t, pool.CheckEvidence(ctx, types.EvidenceList{ev}))
  161. // now we use a time which isn't able to contradict the FLA - thus we can't verify the evidence
  162. oldBlockStore := &mocks.BlockStore{}
  163. oldHeader := trusted.Header
  164. oldHeader.Time = defaultEvidenceTime
  165. oldBlockStore.On("LoadBlockMeta", commonHeight).Return(&types.BlockMeta{Header: *common.Header})
  166. oldBlockStore.On("LoadBlockMeta", nodeHeight).Return(&types.BlockMeta{Header: *oldHeader})
  167. oldBlockStore.On("LoadBlockMeta", attackHeight).Return(nil)
  168. oldBlockStore.On("LoadBlockCommit", commonHeight).Return(common.Commit)
  169. oldBlockStore.On("LoadBlockCommit", nodeHeight).Return(trusted.Commit)
  170. oldBlockStore.On("Height").Return(nodeHeight)
  171. require.Equal(t, defaultEvidenceTime, oldBlockStore.LoadBlockMeta(nodeHeight).Header.Time)
  172. pool, err = evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, oldBlockStore, evidence.NopMetrics())
  173. require.NoError(t, err)
  174. assert.Error(t, pool.CheckEvidence(ctx, types.EvidenceList{ev}))
  175. }
  176. func TestVerifyLightClientAttack_Equivocation(t *testing.T) {
  177. ctx, cancel := context.WithCancel(context.Background())
  178. defer cancel()
  179. conflictingVals, conflictingPrivVals := factory.ValidatorSet(ctx, t, 5, 10)
  180. conflictingHeader := factory.MakeHeader(t, &types.Header{
  181. ChainID: evidenceChainID,
  182. Height: 10,
  183. Time: defaultEvidenceTime,
  184. ValidatorsHash: conflictingVals.Hash(),
  185. })
  186. trustedHeader := factory.MakeHeader(t, &types.Header{
  187. ChainID: evidenceChainID,
  188. Height: 10,
  189. Time: defaultEvidenceTime,
  190. ValidatorsHash: conflictingHeader.ValidatorsHash,
  191. NextValidatorsHash: conflictingHeader.NextValidatorsHash,
  192. ConsensusHash: conflictingHeader.ConsensusHash,
  193. AppHash: conflictingHeader.AppHash,
  194. LastResultsHash: conflictingHeader.LastResultsHash,
  195. })
  196. // we are simulating a duplicate vote attack where all the validators in the conflictingVals set
  197. // except the last validator vote twice
  198. blockID := factory.MakeBlockIDWithHash(conflictingHeader.Hash())
  199. voteSet := types.NewVoteSet(evidenceChainID, 10, 1, tmproto.SignedMsgType(2), conflictingVals)
  200. commit, err := factory.MakeCommit(ctx, blockID, 10, 1, voteSet, conflictingPrivVals[:4], defaultEvidenceTime)
  201. require.NoError(t, err)
  202. ev := &types.LightClientAttackEvidence{
  203. ConflictingBlock: &types.LightBlock{
  204. SignedHeader: &types.SignedHeader{
  205. Header: conflictingHeader,
  206. Commit: commit,
  207. },
  208. ValidatorSet: conflictingVals,
  209. },
  210. CommonHeight: 10,
  211. ByzantineValidators: conflictingVals.Validators[:4],
  212. TotalVotingPower: 50,
  213. Timestamp: defaultEvidenceTime,
  214. }
  215. trustedBlockID := makeBlockID(trustedHeader.Hash(), 1000, []byte("partshash"))
  216. trustedVoteSet := types.NewVoteSet(evidenceChainID, 10, 1, tmproto.SignedMsgType(2), conflictingVals)
  217. trustedCommit, err := factory.MakeCommit(ctx, trustedBlockID, 10, 1,
  218. trustedVoteSet, conflictingPrivVals, defaultEvidenceTime)
  219. require.NoError(t, err)
  220. trustedSignedHeader := &types.SignedHeader{
  221. Header: trustedHeader,
  222. Commit: trustedCommit,
  223. }
  224. // good pass -> no error
  225. require.NoError(t, evidence.VerifyLightClientAttack(ev, trustedSignedHeader, trustedSignedHeader, conflictingVals,
  226. defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour))
  227. // trusted and conflicting hashes are the same -> an error should be returned
  228. assert.Error(t, evidence.VerifyLightClientAttack(ev, trustedSignedHeader, ev.ConflictingBlock.SignedHeader, conflictingVals,
  229. defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour))
  230. // conflicting header has different next validators hash which should have been correctly derived from
  231. // the previous round
  232. ev.ConflictingBlock.Header.NextValidatorsHash = crypto.CRandBytes(tmhash.Size)
  233. assert.Error(t, evidence.VerifyLightClientAttack(ev, trustedSignedHeader, trustedSignedHeader, nil,
  234. defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour))
  235. // revert next validators hash
  236. ev.ConflictingBlock.Header.NextValidatorsHash = trustedHeader.NextValidatorsHash
  237. state := sm.State{
  238. LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute),
  239. LastBlockHeight: 11,
  240. ConsensusParams: *types.DefaultConsensusParams(),
  241. }
  242. stateStore := &smmocks.Store{}
  243. stateStore.On("LoadValidators", int64(10)).Return(conflictingVals, nil)
  244. stateStore.On("Load").Return(state, nil)
  245. blockStore := &mocks.BlockStore{}
  246. blockStore.On("LoadBlockMeta", int64(10)).Return(&types.BlockMeta{Header: *trustedHeader})
  247. blockStore.On("LoadBlockCommit", int64(10)).Return(trustedCommit)
  248. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  249. require.NoError(t, err)
  250. require.NoError(t, setupEventBus(ctx, pool))
  251. evList := types.EvidenceList{ev}
  252. err = pool.CheckEvidence(ctx, evList)
  253. assert.NoError(t, err)
  254. pendingEvs, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  255. assert.Equal(t, 1, len(pendingEvs))
  256. }
  257. func TestVerifyLightClientAttack_Amnesia(t *testing.T) {
  258. ctx, cancel := context.WithCancel(context.Background())
  259. defer cancel()
  260. var height int64 = 10
  261. conflictingVals, conflictingPrivVals := factory.ValidatorSet(ctx, t, 5, 10)
  262. conflictingHeader := factory.MakeHeader(t, &types.Header{
  263. ChainID: evidenceChainID,
  264. Height: height,
  265. Time: defaultEvidenceTime,
  266. ValidatorsHash: conflictingVals.Hash(),
  267. })
  268. trustedHeader := factory.MakeHeader(t, &types.Header{
  269. ChainID: evidenceChainID,
  270. Height: height,
  271. Time: defaultEvidenceTime,
  272. ValidatorsHash: conflictingHeader.ValidatorsHash,
  273. NextValidatorsHash: conflictingHeader.NextValidatorsHash,
  274. ConsensusHash: conflictingHeader.ConsensusHash,
  275. AppHash: conflictingHeader.AppHash,
  276. LastResultsHash: conflictingHeader.LastResultsHash,
  277. })
  278. // we are simulating an amnesia attack where all the validators in the conflictingVals set
  279. // except the last validator vote twice. However this time the commits are of different rounds.
  280. blockID := makeBlockID(conflictingHeader.Hash(), 1000, []byte("partshash"))
  281. voteSet := types.NewVoteSet(evidenceChainID, height, 0, tmproto.SignedMsgType(2), conflictingVals)
  282. commit, err := factory.MakeCommit(ctx, blockID, height, 0, voteSet, conflictingPrivVals, defaultEvidenceTime)
  283. require.NoError(t, err)
  284. ev := &types.LightClientAttackEvidence{
  285. ConflictingBlock: &types.LightBlock{
  286. SignedHeader: &types.SignedHeader{
  287. Header: conflictingHeader,
  288. Commit: commit,
  289. },
  290. ValidatorSet: conflictingVals,
  291. },
  292. CommonHeight: height,
  293. ByzantineValidators: nil, // with amnesia evidence no validators are submitted as abci evidence
  294. TotalVotingPower: 50,
  295. Timestamp: defaultEvidenceTime,
  296. }
  297. trustedBlockID := makeBlockID(trustedHeader.Hash(), 1000, []byte("partshash"))
  298. trustedVoteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), conflictingVals)
  299. trustedCommit, err := factory.MakeCommit(ctx, trustedBlockID, height, 1,
  300. trustedVoteSet, conflictingPrivVals, defaultEvidenceTime)
  301. require.NoError(t, err)
  302. trustedSignedHeader := &types.SignedHeader{
  303. Header: trustedHeader,
  304. Commit: trustedCommit,
  305. }
  306. // good pass -> no error
  307. require.NoError(t, evidence.VerifyLightClientAttack(ev, trustedSignedHeader, trustedSignedHeader, conflictingVals,
  308. defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour))
  309. // trusted and conflicting hashes are the same -> an error should be returned
  310. assert.Error(t, evidence.VerifyLightClientAttack(ev, trustedSignedHeader, ev.ConflictingBlock.SignedHeader, conflictingVals,
  311. defaultEvidenceTime.Add(1*time.Minute), 2*time.Hour))
  312. state := sm.State{
  313. LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute),
  314. LastBlockHeight: 11,
  315. ConsensusParams: *types.DefaultConsensusParams(),
  316. }
  317. stateStore := &smmocks.Store{}
  318. stateStore.On("LoadValidators", int64(10)).Return(conflictingVals, nil)
  319. stateStore.On("Load").Return(state, nil)
  320. blockStore := &mocks.BlockStore{}
  321. blockStore.On("LoadBlockMeta", int64(10)).Return(&types.BlockMeta{Header: *trustedHeader})
  322. blockStore.On("LoadBlockCommit", int64(10)).Return(trustedCommit)
  323. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  324. require.NoError(t, err)
  325. require.NoError(t, setupEventBus(ctx, pool))
  326. evList := types.EvidenceList{ev}
  327. err = pool.CheckEvidence(ctx, evList)
  328. assert.NoError(t, err)
  329. pendingEvs, _ := pool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  330. assert.Equal(t, 1, len(pendingEvs))
  331. }
  332. type voteData struct {
  333. vote1 *types.Vote
  334. vote2 *types.Vote
  335. valid bool
  336. }
  337. func TestVerifyDuplicateVoteEvidence(t *testing.T) {
  338. ctx, cancel := context.WithCancel(context.Background())
  339. defer cancel()
  340. val := types.NewMockPV()
  341. val2 := types.NewMockPV()
  342. valSet := types.NewValidatorSet([]*types.Validator{val.ExtractIntoValidator(ctx, 1)})
  343. blockID := makeBlockID([]byte("blockhash"), 1000, []byte("partshash"))
  344. blockID2 := makeBlockID([]byte("blockhash2"), 1000, []byte("partshash"))
  345. blockID3 := makeBlockID([]byte("blockhash"), 10000, []byte("partshash"))
  346. blockID4 := makeBlockID([]byte("blockhash"), 10000, []byte("partshash2"))
  347. const chainID = "mychain"
  348. vote1 := makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID, defaultEvidenceTime)
  349. v1 := vote1.ToProto()
  350. err := val.SignVote(ctx, chainID, v1)
  351. require.NoError(t, err)
  352. badVote := makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID, defaultEvidenceTime)
  353. bv := badVote.ToProto()
  354. err = val2.SignVote(ctx, chainID, bv)
  355. require.NoError(t, err)
  356. vote1.Signature = v1.Signature
  357. badVote.Signature = bv.Signature
  358. cases := []voteData{
  359. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID2, defaultEvidenceTime), true}, // different block ids
  360. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID3, defaultEvidenceTime), true},
  361. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID4, defaultEvidenceTime), true},
  362. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID, defaultEvidenceTime), false}, // wrong block id
  363. {vote1, makeVote(ctx, t, val, "mychain2", 0, 10, 2, 1, blockID2, defaultEvidenceTime), false}, // wrong chain id
  364. {vote1, makeVote(ctx, t, val, chainID, 0, 11, 2, 1, blockID2, defaultEvidenceTime), false}, // wrong height
  365. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 3, 1, blockID2, defaultEvidenceTime), false}, // wrong round
  366. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 2, 2, blockID2, defaultEvidenceTime), false}, // wrong step
  367. {vote1, makeVote(ctx, t, val2, chainID, 0, 10, 2, 1, blockID2, defaultEvidenceTime), false}, // wrong validator
  368. // a different vote time doesn't matter
  369. {vote1, makeVote(ctx, t, val, chainID, 0, 10, 2, 1, blockID2, time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)), true},
  370. {vote1, badVote, false}, // signed by wrong key
  371. }
  372. require.NoError(t, err)
  373. for _, c := range cases {
  374. ev := &types.DuplicateVoteEvidence{
  375. VoteA: c.vote1,
  376. VoteB: c.vote2,
  377. ValidatorPower: 1,
  378. TotalVotingPower: 1,
  379. Timestamp: defaultEvidenceTime,
  380. }
  381. if c.valid {
  382. assert.Nil(t, evidence.VerifyDuplicateVote(ev, chainID, valSet), "evidence should be valid")
  383. } else {
  384. assert.NotNil(t, evidence.VerifyDuplicateVote(ev, chainID, valSet), "evidence should be invalid")
  385. }
  386. }
  387. // create good evidence and correct validator power
  388. goodEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, 10, defaultEvidenceTime, val, chainID)
  389. require.NoError(t, err)
  390. goodEv.ValidatorPower = 1
  391. goodEv.TotalVotingPower = 1
  392. badEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, 10, defaultEvidenceTime, val, chainID)
  393. require.NoError(t, err)
  394. badTimeEv, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, 10, defaultEvidenceTime.Add(1*time.Minute), val, chainID)
  395. require.NoError(t, err)
  396. badTimeEv.ValidatorPower = 1
  397. badTimeEv.TotalVotingPower = 1
  398. state := sm.State{
  399. ChainID: chainID,
  400. LastBlockTime: defaultEvidenceTime.Add(1 * time.Minute),
  401. LastBlockHeight: 11,
  402. ConsensusParams: *types.DefaultConsensusParams(),
  403. }
  404. stateStore := &smmocks.Store{}
  405. stateStore.On("LoadValidators", int64(10)).Return(valSet, nil)
  406. stateStore.On("Load").Return(state, nil)
  407. blockStore := &mocks.BlockStore{}
  408. blockStore.On("LoadBlockMeta", int64(10)).Return(&types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}})
  409. pool, err := evidence.NewPool(log.TestingLogger(), dbm.NewMemDB(), stateStore, blockStore, evidence.NopMetrics())
  410. require.NoError(t, err)
  411. require.NoError(t, setupEventBus(ctx, pool))
  412. evList := types.EvidenceList{goodEv}
  413. err = pool.CheckEvidence(ctx, evList)
  414. assert.NoError(t, err)
  415. // evidence with a different validator power should fail
  416. evList = types.EvidenceList{badEv}
  417. err = pool.CheckEvidence(ctx, evList)
  418. assert.Error(t, err)
  419. // evidence with a different timestamp should fail
  420. evList = types.EvidenceList{badTimeEv}
  421. err = pool.CheckEvidence(ctx, evList)
  422. assert.Error(t, err)
  423. }
  424. func makeLunaticEvidence(
  425. ctx context.Context,
  426. t *testing.T,
  427. height, commonHeight int64,
  428. totalVals, byzVals, phantomVals int,
  429. commonTime, attackTime time.Time,
  430. ) (ev *types.LightClientAttackEvidence, trusted *types.LightBlock, common *types.LightBlock) {
  431. t.Helper()
  432. commonValSet, commonPrivVals := factory.ValidatorSet(ctx, t, totalVals, defaultVotingPower)
  433. require.Greater(t, totalVals, byzVals)
  434. // extract out the subset of byzantine validators in the common validator set
  435. byzValSet, byzPrivVals := commonValSet.Validators[:byzVals], commonPrivVals[:byzVals]
  436. phantomValSet, phantomPrivVals := factory.ValidatorSet(ctx, t, phantomVals, defaultVotingPower)
  437. conflictingVals := phantomValSet.Copy()
  438. require.NoError(t, conflictingVals.UpdateWithChangeSet(byzValSet))
  439. conflictingPrivVals := append(phantomPrivVals, byzPrivVals...)
  440. conflictingPrivVals = orderPrivValsByValSet(ctx, t, conflictingVals, conflictingPrivVals)
  441. commonHeader := factory.MakeHeader(t, &types.Header{
  442. ChainID: evidenceChainID,
  443. Height: commonHeight,
  444. Time: commonTime,
  445. })
  446. trustedHeader := factory.MakeHeader(t, &types.Header{
  447. ChainID: evidenceChainID,
  448. Height: height,
  449. Time: defaultEvidenceTime,
  450. })
  451. conflictingHeader := factory.MakeHeader(t, &types.Header{
  452. ChainID: evidenceChainID,
  453. Height: height,
  454. Time: attackTime,
  455. ValidatorsHash: conflictingVals.Hash(),
  456. })
  457. blockID := factory.MakeBlockIDWithHash(conflictingHeader.Hash())
  458. voteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), conflictingVals)
  459. commit, err := factory.MakeCommit(ctx, blockID, height, 1, voteSet, conflictingPrivVals, defaultEvidenceTime)
  460. require.NoError(t, err)
  461. ev = &types.LightClientAttackEvidence{
  462. ConflictingBlock: &types.LightBlock{
  463. SignedHeader: &types.SignedHeader{
  464. Header: conflictingHeader,
  465. Commit: commit,
  466. },
  467. ValidatorSet: conflictingVals,
  468. },
  469. CommonHeight: commonHeight,
  470. TotalVotingPower: commonValSet.TotalVotingPower(),
  471. ByzantineValidators: byzValSet,
  472. Timestamp: commonTime,
  473. }
  474. common = &types.LightBlock{
  475. SignedHeader: &types.SignedHeader{
  476. Header: commonHeader,
  477. // we can leave this empty because we shouldn't be checking this
  478. Commit: &types.Commit{},
  479. },
  480. ValidatorSet: commonValSet,
  481. }
  482. trustedBlockID := factory.MakeBlockIDWithHash(trustedHeader.Hash())
  483. trustedVals, privVals := factory.ValidatorSet(ctx, t, totalVals, defaultVotingPower)
  484. trustedVoteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), trustedVals)
  485. trustedCommit, err := factory.MakeCommit(ctx, trustedBlockID, height, 1, trustedVoteSet, privVals, defaultEvidenceTime)
  486. require.NoError(t, err)
  487. trusted = &types.LightBlock{
  488. SignedHeader: &types.SignedHeader{
  489. Header: trustedHeader,
  490. Commit: trustedCommit,
  491. },
  492. ValidatorSet: trustedVals,
  493. }
  494. return ev, trusted, common
  495. }
  496. func makeVote(
  497. ctx context.Context,
  498. t *testing.T, val types.PrivValidator, chainID string, valIndex int32, height int64,
  499. round int32, step int, blockID types.BlockID, time time.Time,
  500. ) *types.Vote {
  501. pubKey, err := val.GetPubKey(ctx)
  502. require.NoError(t, err)
  503. v := &types.Vote{
  504. ValidatorAddress: pubKey.Address(),
  505. ValidatorIndex: valIndex,
  506. Height: height,
  507. Round: round,
  508. Type: tmproto.SignedMsgType(step),
  509. BlockID: blockID,
  510. Timestamp: time,
  511. }
  512. vpb := v.ToProto()
  513. err = val.SignVote(ctx, chainID, vpb)
  514. require.NoError(t, err)
  515. v.Signature = vpb.Signature
  516. return v
  517. }
  518. func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID {
  519. var (
  520. h = make([]byte, tmhash.Size)
  521. psH = make([]byte, tmhash.Size)
  522. )
  523. copy(h, hash)
  524. copy(psH, partSetHash)
  525. return types.BlockID{
  526. Hash: h,
  527. PartSetHeader: types.PartSetHeader{
  528. Total: partSetSize,
  529. Hash: psH,
  530. },
  531. }
  532. }
  533. func orderPrivValsByValSet(ctx context.Context, t *testing.T, vals *types.ValidatorSet, privVals []types.PrivValidator) []types.PrivValidator {
  534. output := make([]types.PrivValidator, len(privVals))
  535. for idx, v := range vals.Validators {
  536. for _, p := range privVals {
  537. pubKey, err := p.GetPubKey(ctx)
  538. require.NoError(t, err)
  539. if bytes.Equal(v.Address, pubKey.Address()) {
  540. output[idx] = p
  541. break
  542. }
  543. }
  544. require.NotEmpty(t, output[idx])
  545. }
  546. return output
  547. }