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.

416 lines
13 KiB

7 years ago
7 years ago
  1. package evidence_test
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/fortytw2/leaktest"
  9. "github.com/go-kit/log/term"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/mock"
  12. "github.com/stretchr/testify/require"
  13. dbm "github.com/tendermint/tm-db"
  14. cfg "github.com/tendermint/tendermint/config"
  15. "github.com/tendermint/tendermint/crypto"
  16. "github.com/tendermint/tendermint/crypto/tmhash"
  17. "github.com/tendermint/tendermint/evidence"
  18. "github.com/tendermint/tendermint/evidence/mocks"
  19. "github.com/tendermint/tendermint/libs/log"
  20. "github.com/tendermint/tendermint/p2p"
  21. p2pmocks "github.com/tendermint/tendermint/p2p/mocks"
  22. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  23. sm "github.com/tendermint/tendermint/state"
  24. "github.com/tendermint/tendermint/types"
  25. )
  26. var (
  27. numEvidence = 10
  28. timeout = 120 * time.Second // ridiculously high because CircleCI is slow
  29. )
  30. // We have N evidence reactors connected to one another. The first reactor
  31. // receives a number of evidence at varying heights. We test that all
  32. // other reactors receive the evidence and add it to their own respective
  33. // evidence pools.
  34. func TestReactorBroadcastEvidence(t *testing.T) {
  35. config := cfg.TestConfig()
  36. N := 7
  37. // create statedb for everyone
  38. stateDBs := make([]sm.Store, N)
  39. val := types.NewMockPV()
  40. // we need validators saved for heights at least as high as we have evidence for
  41. height := int64(numEvidence) + 10
  42. for i := 0; i < N; i++ {
  43. stateDBs[i] = initializeValidatorState(val, height)
  44. }
  45. // make reactors from statedb
  46. reactors, pools := makeAndConnectReactorsAndPools(config, stateDBs)
  47. // set the peer height on each reactor
  48. for _, r := range reactors {
  49. for _, peer := range r.Switch.Peers().List() {
  50. ps := peerState{height}
  51. peer.Set(types.PeerStateKey, ps)
  52. }
  53. }
  54. // send a bunch of valid evidence to the first reactor's evpool
  55. // and wait for them all to be received in the others
  56. evList := sendEvidence(t, pools[0], val, numEvidence)
  57. waitForEvidence(t, evList, pools)
  58. }
  59. // We have two evidence reactors connected to one another but are at different heights.
  60. // Reactor 1 which is ahead receives a number of evidence. It should only send the evidence
  61. // that is below the height of the peer to that peer.
  62. func TestReactorSelectiveBroadcast(t *testing.T) {
  63. config := cfg.TestConfig()
  64. val := types.NewMockPV()
  65. height1 := int64(numEvidence) + 10
  66. height2 := int64(numEvidence) / 2
  67. // DB1 is ahead of DB2
  68. stateDB1 := initializeValidatorState(val, height1)
  69. stateDB2 := initializeValidatorState(val, height2)
  70. // make reactors from statedb
  71. reactors, pools := makeAndConnectReactorsAndPools(config, []sm.Store{stateDB1, stateDB2})
  72. // set the peer height on each reactor
  73. for _, r := range reactors {
  74. for _, peer := range r.Switch.Peers().List() {
  75. ps := peerState{height1}
  76. peer.Set(types.PeerStateKey, ps)
  77. }
  78. }
  79. // update the first reactor peer's height to be very small
  80. peer := reactors[0].Switch.Peers().List()[0]
  81. ps := peerState{height2}
  82. peer.Set(types.PeerStateKey, ps)
  83. // send a bunch of valid evidence to the first reactor's evpool
  84. evList := sendEvidence(t, pools[0], val, numEvidence)
  85. // only ones less than the peers height should make it through
  86. waitForEvidence(t, evList[:numEvidence/2-1], []*evidence.Pool{pools[1]})
  87. // peers should still be connected
  88. peers := reactors[1].Switch.Peers().List()
  89. assert.Equal(t, 1, len(peers))
  90. }
  91. // This tests aims to ensure that reactors don't send evidence that they have committed or that ar
  92. // not ready for the peer through three scenarios.
  93. // First, committed evidence to a newly connected peer
  94. // Second, evidence to a peer that is behind
  95. // Third, evidence that was pending and became committed just before the peer caught up
  96. func TestReactorsGossipNoCommittedEvidence(t *testing.T) {
  97. config := cfg.TestConfig()
  98. val := types.NewMockPV()
  99. var height int64 = 10
  100. // DB1 is ahead of DB2
  101. stateDB1 := initializeValidatorState(val, height-1)
  102. stateDB2 := initializeValidatorState(val, height-2)
  103. state, err := stateDB1.Load()
  104. require.NoError(t, err)
  105. state.LastBlockHeight++
  106. // make reactors from statedb
  107. reactors, pools := makeAndConnectReactorsAndPools(config, []sm.Store{stateDB1, stateDB2})
  108. evList := sendEvidence(t, pools[0], val, 2)
  109. pools[0].Update(state, evList)
  110. require.EqualValues(t, uint32(0), pools[0].Size())
  111. time.Sleep(100 * time.Millisecond)
  112. peer := reactors[0].Switch.Peers().List()[0]
  113. ps := peerState{height - 2}
  114. peer.Set(types.PeerStateKey, ps)
  115. peer = reactors[1].Switch.Peers().List()[0]
  116. ps = peerState{height}
  117. peer.Set(types.PeerStateKey, ps)
  118. // wait to see that no evidence comes through
  119. time.Sleep(300 * time.Millisecond)
  120. // the second pool should not have received any evidence because it has already been committed
  121. assert.Equal(t, uint32(0), pools[1].Size(), "second reactor should not have received evidence")
  122. // the first reactor receives three more evidence
  123. evList = make([]types.Evidence, 3)
  124. for i := 0; i < 3; i++ {
  125. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height-3+int64(i),
  126. time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC), val, state.ChainID)
  127. err := pools[0].AddEvidence(ev)
  128. require.NoError(t, err)
  129. evList[i] = ev
  130. }
  131. // wait to see that only one evidence is sent
  132. time.Sleep(300 * time.Millisecond)
  133. // the second pool should only have received the first evidence because it is behind
  134. peerEv, _ := pools[1].PendingEvidence(10000)
  135. assert.EqualValues(t, []types.Evidence{evList[0]}, peerEv)
  136. // the last evidence is committed and the second reactor catches up in state to the first
  137. // reactor. We therefore expect that the second reactor only receives one more evidence, the
  138. // one that is still pending and not the evidence that has already been committed.
  139. state.LastBlockHeight++
  140. pools[0].Update(state, []types.Evidence{evList[2]})
  141. // the first reactor should have the two remaining pending evidence
  142. require.EqualValues(t, uint32(2), pools[0].Size())
  143. // now update the state of the second reactor
  144. pools[1].Update(state, types.EvidenceList{})
  145. peer = reactors[0].Switch.Peers().List()[0]
  146. ps = peerState{height}
  147. peer.Set(types.PeerStateKey, ps)
  148. // wait to see that only two evidence is sent
  149. time.Sleep(300 * time.Millisecond)
  150. peerEv, _ = pools[1].PendingEvidence(1000)
  151. assert.EqualValues(t, []types.Evidence{evList[0], evList[1]}, peerEv)
  152. }
  153. func TestReactorBroadcastEvidenceMemoryLeak(t *testing.T) {
  154. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  155. evidenceDB := dbm.NewMemDB()
  156. blockStore := &mocks.BlockStore{}
  157. blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(
  158. &types.BlockMeta{Header: types.Header{Time: evidenceTime}},
  159. )
  160. val := types.NewMockPV()
  161. stateStore := initializeValidatorState(val, 1)
  162. pool, err := evidence.NewPool(evidenceDB, stateStore, blockStore)
  163. require.NoError(t, err)
  164. p := &p2pmocks.Peer{}
  165. p.On("IsRunning").Once().Return(true)
  166. p.On("IsRunning").Return(false)
  167. // check that we are not leaking any go-routines
  168. // i.e. broadcastEvidenceRoutine finishes when peer is stopped
  169. defer leaktest.CheckTimeout(t, 10*time.Second)()
  170. p.On("Send", evidence.EvidenceChannel, mock.AnythingOfType("[]uint8")).Return(false)
  171. quitChan := make(<-chan struct{})
  172. p.On("Quit").Return(quitChan)
  173. ps := peerState{2}
  174. p.On("Get", types.PeerStateKey).Return(ps)
  175. p.On("ID").Return("ABC")
  176. p.On("String").Return("mock")
  177. r := evidence.NewReactor(pool)
  178. r.SetLogger(log.TestingLogger())
  179. r.AddPeer(p)
  180. _ = sendEvidence(t, pool, val, 2)
  181. }
  182. // evidenceLogger is a TestingLogger which uses a different
  183. // color for each validator ("validator" key must exist).
  184. func evidenceLogger() log.Logger {
  185. return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor {
  186. for i := 0; i < len(keyvals)-1; i += 2 {
  187. if keyvals[i] == "validator" {
  188. return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))}
  189. }
  190. }
  191. return term.FgBgColor{}
  192. })
  193. }
  194. // connect N evidence reactors through N switches
  195. func makeAndConnectReactorsAndPools(config *cfg.Config, stateStores []sm.Store) ([]*evidence.Reactor,
  196. []*evidence.Pool) {
  197. N := len(stateStores)
  198. reactors := make([]*evidence.Reactor, N)
  199. pools := make([]*evidence.Pool, N)
  200. logger := evidenceLogger()
  201. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  202. for i := 0; i < N; i++ {
  203. evidenceDB := dbm.NewMemDB()
  204. blockStore := &mocks.BlockStore{}
  205. blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(
  206. &types.BlockMeta{Header: types.Header{Time: evidenceTime}},
  207. )
  208. pool, err := evidence.NewPool(evidenceDB, stateStores[i], blockStore)
  209. if err != nil {
  210. panic(err)
  211. }
  212. pools[i] = pool
  213. reactors[i] = evidence.NewReactor(pool)
  214. reactors[i].SetLogger(logger.With("validator", i))
  215. }
  216. p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch {
  217. s.AddReactor("EVIDENCE", reactors[i])
  218. return s
  219. }, p2p.Connect2Switches)
  220. return reactors, pools
  221. }
  222. // wait for all evidence on all reactors
  223. func waitForEvidence(t *testing.T, evs types.EvidenceList, pools []*evidence.Pool) {
  224. // wait for the evidence in all evpools
  225. wg := new(sync.WaitGroup)
  226. for i := 0; i < len(pools); i++ {
  227. wg.Add(1)
  228. go _waitForEvidence(t, wg, evs, i, pools)
  229. }
  230. done := make(chan struct{})
  231. go func() {
  232. wg.Wait()
  233. close(done)
  234. }()
  235. timer := time.After(timeout)
  236. select {
  237. case <-timer:
  238. t.Fatal("Timed out waiting for evidence")
  239. case <-done:
  240. }
  241. }
  242. // wait for all evidence on a single evpool
  243. func _waitForEvidence(
  244. t *testing.T,
  245. wg *sync.WaitGroup,
  246. evs types.EvidenceList,
  247. poolIdx int,
  248. pools []*evidence.Pool,
  249. ) {
  250. evpool := pools[poolIdx]
  251. var evList []types.Evidence
  252. currentPoolSize := 0
  253. for currentPoolSize != len(evs) {
  254. evList, _ = evpool.PendingEvidence(int64(len(evs) * 500)) // each evidence should not be more than 500 bytes
  255. currentPoolSize = len(evList)
  256. time.Sleep(time.Millisecond * 100)
  257. }
  258. // put the reaped evidence in a map so we can quickly check we got everything
  259. evMap := make(map[string]types.Evidence)
  260. for _, e := range evList {
  261. evMap[string(e.Hash())] = e
  262. }
  263. for i, expectedEv := range evs {
  264. gotEv := evMap[string(expectedEv.Hash())]
  265. assert.Equal(t, expectedEv, gotEv,
  266. fmt.Sprintf("evidence at index %d on pool %d don't match: %v vs %v",
  267. i, poolIdx, expectedEv, gotEv))
  268. }
  269. wg.Done()
  270. }
  271. func sendEvidence(t *testing.T, evpool *evidence.Pool, val types.PrivValidator, n int) types.EvidenceList {
  272. evList := make([]types.Evidence, n)
  273. for i := 0; i < n; i++ {
  274. ev := types.NewMockDuplicateVoteEvidenceWithValidator(int64(i+1),
  275. time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC), val, evidenceChainID)
  276. err := evpool.AddEvidence(ev)
  277. require.NoError(t, err)
  278. evList[i] = ev
  279. }
  280. return evList
  281. }
  282. type peerState struct {
  283. height int64
  284. }
  285. func (ps peerState) GetHeight() int64 {
  286. return ps.height
  287. }
  288. func exampleVote(t byte) *types.Vote {
  289. var stamp, err = time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z")
  290. if err != nil {
  291. panic(err)
  292. }
  293. return &types.Vote{
  294. Type: tmproto.SignedMsgType(t),
  295. Height: 3,
  296. Round: 2,
  297. Timestamp: stamp,
  298. BlockID: types.BlockID{
  299. Hash: tmhash.Sum([]byte("blockID_hash")),
  300. PartSetHeader: types.PartSetHeader{
  301. Total: 1000000,
  302. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  303. },
  304. },
  305. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  306. ValidatorIndex: 56789,
  307. }
  308. }
  309. // nolint:lll //ignore line length for tests
  310. func TestEvidenceVectors(t *testing.T) {
  311. val := &types.Validator{
  312. Address: crypto.AddressHash([]byte("validator_address")),
  313. VotingPower: 10,
  314. }
  315. valSet := types.NewValidatorSet([]*types.Validator{val})
  316. dupl := types.NewDuplicateVoteEvidence(
  317. exampleVote(1),
  318. exampleVote(2),
  319. defaultEvidenceTime,
  320. valSet,
  321. )
  322. testCases := []struct {
  323. testName string
  324. evidenceList []types.Evidence
  325. expBytes string
  326. }{
  327. {"DuplicateVoteEvidence", []types.Evidence{dupl}, "0a85020a82020a79080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb031279080110031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb03180a200a2a060880dbaae105"},
  328. }
  329. for _, tc := range testCases {
  330. tc := tc
  331. evi := make([]tmproto.Evidence, len(tc.evidenceList))
  332. for i := 0; i < len(tc.evidenceList); i++ {
  333. ev, err := types.EvidenceToProto(tc.evidenceList[i])
  334. require.NoError(t, err, tc.testName)
  335. evi[i] = *ev
  336. }
  337. epl := tmproto.EvidenceList{
  338. Evidence: evi,
  339. }
  340. bz, err := epl.Marshal()
  341. require.NoError(t, err, tc.testName)
  342. require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName)
  343. }
  344. }