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.

562 lines
17 KiB

  1. package evidence_test
  2. import (
  3. "encoding/hex"
  4. "math/rand"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/fortytw2/leaktest"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/mock"
  11. "github.com/stretchr/testify/require"
  12. dbm "github.com/tendermint/tm-db"
  13. "github.com/tendermint/tendermint/crypto"
  14. "github.com/tendermint/tendermint/crypto/tmhash"
  15. "github.com/tendermint/tendermint/internal/evidence"
  16. "github.com/tendermint/tendermint/internal/evidence/mocks"
  17. "github.com/tendermint/tendermint/internal/p2p"
  18. "github.com/tendermint/tendermint/internal/p2p/p2ptest"
  19. sm "github.com/tendermint/tendermint/internal/state"
  20. "github.com/tendermint/tendermint/libs/log"
  21. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  22. "github.com/tendermint/tendermint/types"
  23. )
  24. var (
  25. numEvidence = 10
  26. rng = rand.New(rand.NewSource(time.Now().UnixNano()))
  27. )
  28. type reactorTestSuite struct {
  29. network *p2ptest.Network
  30. logger log.Logger
  31. reactors map[types.NodeID]*evidence.Reactor
  32. pools map[types.NodeID]*evidence.Pool
  33. evidenceChannels map[types.NodeID]*p2p.Channel
  34. peerUpdates map[types.NodeID]*p2p.PeerUpdates
  35. peerChans map[types.NodeID]chan p2p.PeerUpdate
  36. nodes []*p2ptest.Node
  37. numStateStores int
  38. }
  39. func setup(t *testing.T, stateStores []sm.Store, chBuf uint) *reactorTestSuite {
  40. t.Helper()
  41. pID := make([]byte, 16)
  42. _, err := rng.Read(pID)
  43. require.NoError(t, err)
  44. numStateStores := len(stateStores)
  45. rts := &reactorTestSuite{
  46. numStateStores: numStateStores,
  47. logger: log.TestingLogger().With("testCase", t.Name()),
  48. network: p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: numStateStores}),
  49. reactors: make(map[types.NodeID]*evidence.Reactor, numStateStores),
  50. pools: make(map[types.NodeID]*evidence.Pool, numStateStores),
  51. peerUpdates: make(map[types.NodeID]*p2p.PeerUpdates, numStateStores),
  52. peerChans: make(map[types.NodeID]chan p2p.PeerUpdate, numStateStores),
  53. }
  54. chDesc := &p2p.ChannelDescriptor{ID: evidence.EvidenceChannel, MessageType: new(tmproto.EvidenceList)}
  55. rts.evidenceChannels = rts.network.MakeChannelsNoCleanup(t, chDesc)
  56. require.Len(t, rts.network.RandomNode().PeerManager.Peers(), 0)
  57. idx := 0
  58. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  59. for nodeID := range rts.network.Nodes {
  60. logger := rts.logger.With("validator", idx)
  61. evidenceDB := dbm.NewMemDB()
  62. blockStore := &mocks.BlockStore{}
  63. state, _ := stateStores[idx].Load()
  64. blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(func(h int64) *types.BlockMeta {
  65. if h <= state.LastBlockHeight {
  66. return &types.BlockMeta{Header: types.Header{Time: evidenceTime}}
  67. }
  68. return nil
  69. })
  70. rts.pools[nodeID], err = evidence.NewPool(logger, evidenceDB, stateStores[idx], blockStore)
  71. require.NoError(t, err)
  72. rts.peerChans[nodeID] = make(chan p2p.PeerUpdate)
  73. rts.peerUpdates[nodeID] = p2p.NewPeerUpdates(rts.peerChans[nodeID], 1)
  74. rts.network.Nodes[nodeID].PeerManager.Register(rts.peerUpdates[nodeID])
  75. rts.nodes = append(rts.nodes, rts.network.Nodes[nodeID])
  76. rts.reactors[nodeID] = evidence.NewReactor(logger,
  77. rts.evidenceChannels[nodeID],
  78. rts.peerUpdates[nodeID],
  79. rts.pools[nodeID])
  80. require.NoError(t, rts.reactors[nodeID].Start())
  81. require.True(t, rts.reactors[nodeID].IsRunning())
  82. idx++
  83. }
  84. t.Cleanup(func() {
  85. for _, r := range rts.reactors {
  86. if r.IsRunning() {
  87. require.NoError(t, r.Stop())
  88. require.False(t, r.IsRunning())
  89. }
  90. }
  91. leaktest.Check(t)
  92. })
  93. return rts
  94. }
  95. func (rts *reactorTestSuite) start(t *testing.T) {
  96. rts.network.Start(t)
  97. require.Len(t,
  98. rts.network.RandomNode().PeerManager.Peers(),
  99. rts.numStateStores-1,
  100. "network does not have expected number of nodes")
  101. }
  102. func (rts *reactorTestSuite) waitForEvidence(t *testing.T, evList types.EvidenceList, ids ...types.NodeID) {
  103. t.Helper()
  104. fn := func(pool *evidence.Pool) {
  105. var (
  106. localEvList []types.Evidence
  107. size int64
  108. loops int
  109. )
  110. // wait till we have at least the amount of evidence
  111. // that we expect. if there's more local evidence then
  112. // it doesn't make sense to wait longer and a
  113. // different assertion should catch the resulting error
  114. for len(localEvList) < len(evList) {
  115. // each evidence should not be more than 500 bytes
  116. localEvList, size = pool.PendingEvidence(int64(len(evList) * 500))
  117. if loops == 100 {
  118. t.Log("current wait status:", "|",
  119. "local", len(localEvList), "|",
  120. "waitlist", len(evList), "|",
  121. "size", size)
  122. }
  123. loops++
  124. }
  125. // put the reaped evidence in a map so we can quickly check we got everything
  126. evMap := make(map[string]types.Evidence)
  127. for _, e := range localEvList {
  128. evMap[string(e.Hash())] = e
  129. }
  130. for i, expectedEv := range evList {
  131. gotEv := evMap[string(expectedEv.Hash())]
  132. require.Equalf(
  133. t,
  134. expectedEv,
  135. gotEv,
  136. "evidence for pool %d in pool does not match; got: %v, expected: %v", i, gotEv, expectedEv,
  137. )
  138. }
  139. }
  140. if len(ids) == 1 {
  141. // special case waiting once, just to avoid the extra
  142. // goroutine, in the case that this hits a timeout,
  143. // the stack will be clearer.
  144. fn(rts.pools[ids[0]])
  145. return
  146. }
  147. wg := sync.WaitGroup{}
  148. for id := range rts.pools {
  149. if len(ids) > 0 && !p2ptest.NodeInSlice(id, ids) {
  150. // if an ID list is specified, then we only
  151. // want to wait for those pools that are
  152. // specified in the list, otherwise, wait for
  153. // all pools.
  154. continue
  155. }
  156. wg.Add(1)
  157. go func(id types.NodeID) { defer wg.Done(); fn(rts.pools[id]) }(id)
  158. }
  159. wg.Wait()
  160. }
  161. func (rts *reactorTestSuite) assertEvidenceChannelsEmpty(t *testing.T) {
  162. t.Helper()
  163. for id, r := range rts.reactors {
  164. require.NoError(t, r.Stop(), "stopping reactor #%s", id)
  165. r.Wait()
  166. require.False(t, r.IsRunning(), "reactor #%d did not stop", id)
  167. }
  168. for id, ech := range rts.evidenceChannels {
  169. require.Empty(t, ech.Out, "checking channel #%q", id)
  170. }
  171. }
  172. func createEvidenceList(
  173. t *testing.T,
  174. pool *evidence.Pool,
  175. val types.PrivValidator,
  176. numEvidence int,
  177. ) types.EvidenceList {
  178. t.Helper()
  179. evList := make([]types.Evidence, numEvidence)
  180. for i := 0; i < numEvidence; i++ {
  181. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  182. int64(i+1),
  183. time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
  184. val,
  185. evidenceChainID,
  186. )
  187. require.NoError(t, pool.AddEvidence(ev),
  188. "adding evidence it#%d of %d to pool with height %d",
  189. i, numEvidence, pool.State().LastBlockHeight)
  190. evList[i] = ev
  191. }
  192. return evList
  193. }
  194. func TestReactorMultiDisconnect(t *testing.T) {
  195. val := types.NewMockPV()
  196. height := int64(numEvidence) + 10
  197. stateDB1 := initializeValidatorState(t, val, height)
  198. stateDB2 := initializeValidatorState(t, val, height)
  199. rts := setup(t, []sm.Store{stateDB1, stateDB2}, 20)
  200. primary := rts.nodes[0]
  201. secondary := rts.nodes[1]
  202. _ = createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  203. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  204. rts.start(t)
  205. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusUp)
  206. // Ensure "disconnecting" the secondary peer from the primary more than once
  207. // is handled gracefully.
  208. primary.PeerManager.Disconnected(secondary.NodeID)
  209. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  210. _, err := primary.PeerManager.TryEvictNext()
  211. require.NoError(t, err)
  212. primary.PeerManager.Disconnected(secondary.NodeID)
  213. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  214. require.Equal(t, secondary.PeerManager.Status(primary.NodeID), p2p.PeerStatusUp)
  215. }
  216. // TestReactorBroadcastEvidence creates an environment of multiple peers that
  217. // are all at the same height. One peer, designated as a primary, gossips all
  218. // evidence to the remaining peers.
  219. func TestReactorBroadcastEvidence(t *testing.T) {
  220. numPeers := 7
  221. // create a stateDB for all test suites (nodes)
  222. stateDBs := make([]sm.Store, numPeers)
  223. val := types.NewMockPV()
  224. // We need all validators saved for heights at least as high as we have
  225. // evidence for.
  226. height := int64(numEvidence) + 10
  227. for i := 0; i < numPeers; i++ {
  228. stateDBs[i] = initializeValidatorState(t, val, height)
  229. }
  230. rts := setup(t, stateDBs, 0)
  231. rts.start(t)
  232. // Create a series of fixtures where each suite contains a reactor and
  233. // evidence pool. In addition, we mark a primary suite and the rest are
  234. // secondaries where each secondary is added as a peer via a PeerUpdate to the
  235. // primary. As a result, the primary will gossip all evidence to each secondary.
  236. primary := rts.network.RandomNode()
  237. secondaries := make([]*p2ptest.Node, 0, len(rts.network.NodeIDs())-1)
  238. secondaryIDs := make([]types.NodeID, 0, cap(secondaries))
  239. for id := range rts.network.Nodes {
  240. if id == primary.NodeID {
  241. continue
  242. }
  243. secondaries = append(secondaries, rts.network.Nodes[id])
  244. secondaryIDs = append(secondaryIDs, id)
  245. }
  246. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  247. // Add each secondary suite (node) as a peer to the primary suite (node). This
  248. // will cause the primary to gossip all evidence to the secondaries.
  249. for _, suite := range secondaries {
  250. rts.peerChans[primary.NodeID] <- p2p.PeerUpdate{
  251. Status: p2p.PeerStatusUp,
  252. NodeID: suite.NodeID,
  253. }
  254. }
  255. // Wait till all secondary suites (reactor) received all evidence from the
  256. // primary suite (node).
  257. rts.waitForEvidence(t, evList, secondaryIDs...)
  258. for _, pool := range rts.pools {
  259. require.Equal(t, numEvidence, int(pool.Size()))
  260. }
  261. rts.assertEvidenceChannelsEmpty(t)
  262. }
  263. // TestReactorSelectiveBroadcast tests a context where we have two reactors
  264. // connected to one another but are at different heights. Reactor 1 which is
  265. // ahead receives a list of evidence.
  266. func TestReactorBroadcastEvidence_Lagging(t *testing.T) {
  267. val := types.NewMockPV()
  268. height1 := int64(numEvidence) + 10
  269. height2 := int64(numEvidence) / 2
  270. // stateDB1 is ahead of stateDB2, where stateDB1 has all heights (1-20) and
  271. // stateDB2 only has heights 1-5.
  272. stateDB1 := initializeValidatorState(t, val, height1)
  273. stateDB2 := initializeValidatorState(t, val, height2)
  274. rts := setup(t, []sm.Store{stateDB1, stateDB2}, 100)
  275. rts.start(t)
  276. primary := rts.nodes[0]
  277. secondary := rts.nodes[1]
  278. // Send a list of valid evidence to the first reactor's, the one that is ahead,
  279. // evidence pool.
  280. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  281. // Add each secondary suite (node) as a peer to the primary suite (node). This
  282. // will cause the primary to gossip all evidence to the secondaries.
  283. rts.peerChans[primary.NodeID] <- p2p.PeerUpdate{
  284. Status: p2p.PeerStatusUp,
  285. NodeID: secondary.NodeID,
  286. }
  287. // only ones less than the peers height should make it through
  288. rts.waitForEvidence(t, evList[:height2], secondary.NodeID)
  289. require.Equal(t, numEvidence, int(rts.pools[primary.NodeID].Size()))
  290. require.Equal(t, int(height2), int(rts.pools[secondary.NodeID].Size()))
  291. rts.assertEvidenceChannelsEmpty(t)
  292. }
  293. func TestReactorBroadcastEvidence_Pending(t *testing.T) {
  294. val := types.NewMockPV()
  295. height := int64(10)
  296. stateDB1 := initializeValidatorState(t, val, height)
  297. stateDB2 := initializeValidatorState(t, val, height)
  298. rts := setup(t, []sm.Store{stateDB1, stateDB2}, 100)
  299. primary := rts.nodes[0]
  300. secondary := rts.nodes[1]
  301. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  302. // Manually add half the evidence to the secondary which will mark them as
  303. // pending.
  304. for i := 0; i < numEvidence/2; i++ {
  305. require.NoError(t, rts.pools[secondary.NodeID].AddEvidence(evList[i]))
  306. }
  307. // the secondary should have half the evidence as pending
  308. require.Equal(t, numEvidence/2, int(rts.pools[secondary.NodeID].Size()))
  309. rts.start(t)
  310. // The secondary reactor should have received all the evidence ignoring the
  311. // already pending evidence.
  312. rts.waitForEvidence(t, evList, secondary.NodeID)
  313. // check to make sure that all of the evidence has
  314. // propogated
  315. require.Len(t, rts.pools, 2)
  316. assert.EqualValues(t, numEvidence, rts.pools[primary.NodeID].Size(),
  317. "primary node should have all the evidence")
  318. assert.EqualValues(t, numEvidence, rts.pools[secondary.NodeID].Size(),
  319. "secondary nodes should have caught up")
  320. }
  321. func TestReactorBroadcastEvidence_Committed(t *testing.T) {
  322. val := types.NewMockPV()
  323. height := int64(10)
  324. stateDB1 := initializeValidatorState(t, val, height)
  325. stateDB2 := initializeValidatorState(t, val, height)
  326. rts := setup(t, []sm.Store{stateDB1, stateDB2}, 0)
  327. primary := rts.nodes[0]
  328. secondary := rts.nodes[1]
  329. // add all evidence to the primary reactor
  330. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  331. // Manually add half the evidence to the secondary which will mark them as
  332. // pending.
  333. for i := 0; i < numEvidence/2; i++ {
  334. require.NoError(t, rts.pools[secondary.NodeID].AddEvidence(evList[i]))
  335. }
  336. // the secondary should have half the evidence as pending
  337. require.Equal(t, numEvidence/2, int(rts.pools[secondary.NodeID].Size()))
  338. state, err := stateDB2.Load()
  339. require.NoError(t, err)
  340. // update the secondary's pool such that all pending evidence is committed
  341. state.LastBlockHeight++
  342. rts.pools[secondary.NodeID].Update(state, evList[:numEvidence/2])
  343. // the secondary should have half the evidence as committed
  344. require.Equal(t, 0, int(rts.pools[secondary.NodeID].Size()))
  345. // start the network and ensure it's configured
  346. rts.start(t)
  347. // The secondary reactor should have received all the evidence ignoring the
  348. // already committed evidence.
  349. rts.waitForEvidence(t, evList[numEvidence/2:], secondary.NodeID)
  350. require.Len(t, rts.pools, 2)
  351. assert.EqualValues(t, numEvidence, rts.pools[primary.NodeID].Size(),
  352. "primary node should have all the evidence")
  353. assert.EqualValues(t, numEvidence/2, rts.pools[secondary.NodeID].Size(),
  354. "secondary nodes should have caught up")
  355. }
  356. func TestReactorBroadcastEvidence_FullyConnected(t *testing.T) {
  357. numPeers := 7
  358. // create a stateDB for all test suites (nodes)
  359. stateDBs := make([]sm.Store, numPeers)
  360. val := types.NewMockPV()
  361. // We need all validators saved for heights at least as high as we have
  362. // evidence for.
  363. height := int64(numEvidence) + 10
  364. for i := 0; i < numPeers; i++ {
  365. stateDBs[i] = initializeValidatorState(t, val, height)
  366. }
  367. rts := setup(t, stateDBs, 0)
  368. rts.start(t)
  369. evList := createEvidenceList(t, rts.pools[rts.network.RandomNode().NodeID], val, numEvidence)
  370. // every suite (reactor) connects to every other suite (reactor)
  371. for outerID, outerChan := range rts.peerChans {
  372. for innerID := range rts.peerChans {
  373. if outerID != innerID {
  374. outerChan <- p2p.PeerUpdate{
  375. Status: p2p.PeerStatusUp,
  376. NodeID: innerID,
  377. }
  378. }
  379. }
  380. }
  381. // wait till all suites (reactors) received all evidence from other suites (reactors)
  382. rts.waitForEvidence(t, evList)
  383. for _, pool := range rts.pools {
  384. require.Equal(t, numEvidence, int(pool.Size()))
  385. // commit state so we do not continue to repeat gossiping the same evidence
  386. state := pool.State()
  387. state.LastBlockHeight++
  388. pool.Update(state, evList)
  389. }
  390. }
  391. // nolint:lll
  392. func TestEvidenceListSerialization(t *testing.T) {
  393. exampleVote := func(msgType byte) *types.Vote {
  394. var stamp, err = time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z")
  395. require.NoError(t, err)
  396. return &types.Vote{
  397. Type: tmproto.SignedMsgType(msgType),
  398. Height: 3,
  399. Round: 2,
  400. Timestamp: stamp,
  401. BlockID: types.BlockID{
  402. Hash: tmhash.Sum([]byte("blockID_hash")),
  403. PartSetHeader: types.PartSetHeader{
  404. Total: 1000000,
  405. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  406. },
  407. },
  408. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  409. ValidatorIndex: 56789,
  410. }
  411. }
  412. val := &types.Validator{
  413. Address: crypto.AddressHash([]byte("validator_address")),
  414. VotingPower: 10,
  415. }
  416. valSet := types.NewValidatorSet([]*types.Validator{val})
  417. dupl, err := types.NewDuplicateVoteEvidence(
  418. exampleVote(1),
  419. exampleVote(2),
  420. defaultEvidenceTime,
  421. valSet,
  422. )
  423. require.NoError(t, err)
  424. testCases := map[string]struct {
  425. evidenceList []types.Evidence
  426. expBytes string
  427. }{
  428. "DuplicateVoteEvidence": {
  429. []types.Evidence{dupl},
  430. "0a85020a82020a79080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb031279080110031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb03180a200a2a060880dbaae105",
  431. },
  432. }
  433. for name, tc := range testCases {
  434. tc := tc
  435. t.Run(name, func(t *testing.T) {
  436. protoEv := make([]tmproto.Evidence, len(tc.evidenceList))
  437. for i := 0; i < len(tc.evidenceList); i++ {
  438. ev, err := types.EvidenceToProto(tc.evidenceList[i])
  439. require.NoError(t, err)
  440. protoEv[i] = *ev
  441. }
  442. epl := tmproto.EvidenceList{
  443. Evidence: protoEv,
  444. }
  445. bz, err := epl.Marshal()
  446. require.NoError(t, err)
  447. require.Equal(t, tc.expBytes, hex.EncodeToString(bz))
  448. })
  449. }
  450. }